Completed
Push — master ( 42f450...2cd491 )
by
unknown
66:17 queued 24:43
created
lib/private/Encryption/EncryptionWrapper.php 1 patch
Indentation   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -26,68 +26,68 @@
 block discarded – undo
26 26
  * @package OC\Encryption
27 27
  */
28 28
 class EncryptionWrapper {
29
-	/** @var ArrayCache */
30
-	private $arrayCache;
29
+    /** @var ArrayCache */
30
+    private $arrayCache;
31 31
 
32
-	/** @var Manager */
33
-	private $manager;
32
+    /** @var Manager */
33
+    private $manager;
34 34
 
35
-	private LoggerInterface $logger;
35
+    private LoggerInterface $logger;
36 36
 
37
-	/**
38
-	 * EncryptionWrapper constructor.
39
-	 */
40
-	public function __construct(ArrayCache $arrayCache,
41
-		Manager $manager,
42
-		LoggerInterface $logger,
43
-	) {
44
-		$this->arrayCache = $arrayCache;
45
-		$this->manager = $manager;
46
-		$this->logger = $logger;
47
-	}
37
+    /**
38
+     * EncryptionWrapper constructor.
39
+     */
40
+    public function __construct(ArrayCache $arrayCache,
41
+        Manager $manager,
42
+        LoggerInterface $logger,
43
+    ) {
44
+        $this->arrayCache = $arrayCache;
45
+        $this->manager = $manager;
46
+        $this->logger = $logger;
47
+    }
48 48
 
49
-	/**
50
-	 * Wraps the given storage when it is not a shared storage
51
-	 *
52
-	 * @param string $mountPoint
53
-	 * @param IStorage $storage
54
-	 * @param IMountPoint $mount
55
-	 * @param bool $force apply the wrapper even if the storage normally has encryption disabled, helpful for repair steps
56
-	 * @return Encryption|IStorage
57
-	 */
58
-	public function wrapStorage(string $mountPoint, IStorage $storage, IMountPoint $mount, bool $force = false) {
59
-		$parameters = [
60
-			'storage' => $storage,
61
-			'mountPoint' => $mountPoint,
62
-			'mount' => $mount
63
-		];
49
+    /**
50
+     * Wraps the given storage when it is not a shared storage
51
+     *
52
+     * @param string $mountPoint
53
+     * @param IStorage $storage
54
+     * @param IMountPoint $mount
55
+     * @param bool $force apply the wrapper even if the storage normally has encryption disabled, helpful for repair steps
56
+     * @return Encryption|IStorage
57
+     */
58
+    public function wrapStorage(string $mountPoint, IStorage $storage, IMountPoint $mount, bool $force = false) {
59
+        $parameters = [
60
+            'storage' => $storage,
61
+            'mountPoint' => $mountPoint,
62
+            'mount' => $mount
63
+        ];
64 64
 
65
-		if ($force || (!$storage->instanceOfStorage(IDisableEncryptionStorage::class) && $mountPoint !== '/')) {
66
-			$user = \OC::$server->getUserSession()->getUser();
67
-			$mountManager = Filesystem::getMountManager();
68
-			$uid = $user ? $user->getUID() : null;
69
-			$fileHelper = \OC::$server->get(IFile::class);
70
-			$keyStorage = \OC::$server->get(EncryptionKeysStorage::class);
65
+        if ($force || (!$storage->instanceOfStorage(IDisableEncryptionStorage::class) && $mountPoint !== '/')) {
66
+            $user = \OC::$server->getUserSession()->getUser();
67
+            $mountManager = Filesystem::getMountManager();
68
+            $uid = $user ? $user->getUID() : null;
69
+            $fileHelper = \OC::$server->get(IFile::class);
70
+            $keyStorage = \OC::$server->get(EncryptionKeysStorage::class);
71 71
 
72
-			$util = new Util(
73
-				new View(),
74
-				\OC::$server->getUserManager(),
75
-				\OC::$server->getGroupManager(),
76
-				\OC::$server->getConfig()
77
-			);
78
-			return new Encryption(
79
-				$parameters,
80
-				$this->manager,
81
-				$util,
82
-				$this->logger,
83
-				$fileHelper,
84
-				$uid,
85
-				$keyStorage,
86
-				$mountManager,
87
-				$this->arrayCache
88
-			);
89
-		} else {
90
-			return $storage;
91
-		}
92
-	}
72
+            $util = new Util(
73
+                new View(),
74
+                \OC::$server->getUserManager(),
75
+                \OC::$server->getGroupManager(),
76
+                \OC::$server->getConfig()
77
+            );
78
+            return new Encryption(
79
+                $parameters,
80
+                $this->manager,
81
+                $util,
82
+                $this->logger,
83
+                $fileHelper,
84
+                $uid,
85
+                $keyStorage,
86
+                $mountManager,
87
+                $this->arrayCache
88
+            );
89
+        } else {
90
+            return $storage;
91
+        }
92
+    }
93 93
 }
Please login to merge, or discard this patch.
lib/private/Encryption/Update.php 1 patch
Indentation   +84 added lines, -84 removed lines patch added patch discarded remove patch
@@ -22,97 +22,97 @@
 block discarded – undo
22 22
  * update encrypted files, e.g. because a file was shared
23 23
  */
24 24
 class Update {
25
-	public function __construct(
26
-		protected Util $util,
27
-		protected Manager $encryptionManager,
28
-		protected File $file,
29
-		protected LoggerInterface $logger,
30
-		protected string $uid,
31
-	) {
32
-	}
25
+    public function __construct(
26
+        protected Util $util,
27
+        protected Manager $encryptionManager,
28
+        protected File $file,
29
+        protected LoggerInterface $logger,
30
+        protected string $uid,
31
+    ) {
32
+    }
33 33
 
34
-	/**
35
-	 * hook after file was shared
36
-	 */
37
-	public function postShared(OCPFile|Folder $node): void {
38
-		$this->update($node);
39
-	}
34
+    /**
35
+     * hook after file was shared
36
+     */
37
+    public function postShared(OCPFile|Folder $node): void {
38
+        $this->update($node);
39
+    }
40 40
 
41
-	/**
42
-	 * hook after file was unshared
43
-	 */
44
-	public function postUnshared(OCPFile|Folder $node): void {
45
-		$this->update($node);
46
-	}
41
+    /**
42
+     * hook after file was unshared
43
+     */
44
+    public function postUnshared(OCPFile|Folder $node): void {
45
+        $this->update($node);
46
+    }
47 47
 
48
-	/**
49
-	 * inform encryption module that a file was restored from the trash bin,
50
-	 * e.g. to update the encryption keys
51
-	 */
52
-	public function postRestore(OCPFile|Folder $node): void {
53
-		$this->update($node);
54
-	}
48
+    /**
49
+     * inform encryption module that a file was restored from the trash bin,
50
+     * e.g. to update the encryption keys
51
+     */
52
+    public function postRestore(OCPFile|Folder $node): void {
53
+        $this->update($node);
54
+    }
55 55
 
56
-	/**
57
-	 * inform encryption module that a file was renamed,
58
-	 * e.g. to update the encryption keys
59
-	 */
60
-	public function postRename(OCPFile|Folder $source, OCPFile|Folder $target): void {
61
-		if (dirname($source->getPath()) !== dirname($target->getPath())) {
62
-			$this->update($target);
63
-		}
64
-	}
56
+    /**
57
+     * inform encryption module that a file was renamed,
58
+     * e.g. to update the encryption keys
59
+     */
60
+    public function postRename(OCPFile|Folder $source, OCPFile|Folder $target): void {
61
+        if (dirname($source->getPath()) !== dirname($target->getPath())) {
62
+            $this->update($target);
63
+        }
64
+    }
65 65
 
66
-	/**
67
-	 * get owner and path relative to data/
68
-	 *
69
-	 * @throws \InvalidArgumentException
70
-	 */
71
-	protected function getOwnerPath(OCPFile|Folder $node): string {
72
-		$owner = $node->getOwner()?->getUID();
73
-		if ($owner === null) {
74
-			throw new InvalidArgumentException('No owner found for ' . $node->getId());
75
-		}
76
-		$view = new View('/' . $owner . '/files');
77
-		try {
78
-			$path = $view->getPath($node->getId());
79
-		} catch (NotFoundException $e) {
80
-			throw new InvalidArgumentException('No file found for ' . $node->getId(), previous:$e);
81
-		}
82
-		return '/' . $owner . '/files/' . $path;
83
-	}
66
+    /**
67
+     * get owner and path relative to data/
68
+     *
69
+     * @throws \InvalidArgumentException
70
+     */
71
+    protected function getOwnerPath(OCPFile|Folder $node): string {
72
+        $owner = $node->getOwner()?->getUID();
73
+        if ($owner === null) {
74
+            throw new InvalidArgumentException('No owner found for ' . $node->getId());
75
+        }
76
+        $view = new View('/' . $owner . '/files');
77
+        try {
78
+            $path = $view->getPath($node->getId());
79
+        } catch (NotFoundException $e) {
80
+            throw new InvalidArgumentException('No file found for ' . $node->getId(), previous:$e);
81
+        }
82
+        return '/' . $owner . '/files/' . $path;
83
+    }
84 84
 
85
-	/**
86
-	 * notify encryption module about added/removed users from a file/folder
87
-	 *
88
-	 * @param string $path relative to data/
89
-	 * @throws Exceptions\ModuleDoesNotExistsException
90
-	 */
91
-	public function update(OCPFile|Folder $node): void {
92
-		$encryptionModule = $this->encryptionManager->getEncryptionModule();
85
+    /**
86
+     * notify encryption module about added/removed users from a file/folder
87
+     *
88
+     * @param string $path relative to data/
89
+     * @throws Exceptions\ModuleDoesNotExistsException
90
+     */
91
+    public function update(OCPFile|Folder $node): void {
92
+        $encryptionModule = $this->encryptionManager->getEncryptionModule();
93 93
 
94
-		// if the encryption module doesn't encrypt the files on a per-user basis
95
-		// we have nothing to do here.
96
-		if ($encryptionModule->needDetailedAccessList() === false) {
97
-			return;
98
-		}
94
+        // if the encryption module doesn't encrypt the files on a per-user basis
95
+        // we have nothing to do here.
96
+        if ($encryptionModule->needDetailedAccessList() === false) {
97
+            return;
98
+        }
99 99
 
100
-		$path = $this->getOwnerPath($node);
101
-		// if a folder was shared, get a list of all (sub-)folders
102
-		if ($node instanceof Folder) {
103
-			$allFiles = $this->util->getAllFiles($path);
104
-		} else {
105
-			$allFiles = [$path];
106
-		}
100
+        $path = $this->getOwnerPath($node);
101
+        // if a folder was shared, get a list of all (sub-)folders
102
+        if ($node instanceof Folder) {
103
+            $allFiles = $this->util->getAllFiles($path);
104
+        } else {
105
+            $allFiles = [$path];
106
+        }
107 107
 
108
-		foreach ($allFiles as $file) {
109
-			$usersSharing = $this->file->getAccessList($file);
110
-			try {
111
-				$encryptionModule->update($file, $this->uid, $usersSharing);
112
-			} catch (GenericEncryptionException $e) {
113
-				// If the update of an individual file fails e.g. due to a corrupt key we should continue the operation and just log the failure
114
-				$this->logger->error('Failed to update encryption module for ' . $this->uid . ' ' . $file, [ 'exception' => $e ]);
115
-			}
116
-		}
117
-	}
108
+        foreach ($allFiles as $file) {
109
+            $usersSharing = $this->file->getAccessList($file);
110
+            try {
111
+                $encryptionModule->update($file, $this->uid, $usersSharing);
112
+            } catch (GenericEncryptionException $e) {
113
+                // If the update of an individual file fails e.g. due to a corrupt key we should continue the operation and just log the failure
114
+                $this->logger->error('Failed to update encryption module for ' . $this->uid . ' ' . $file, [ 'exception' => $e ]);
115
+            }
116
+        }
117
+    }
118 118
 }
Please login to merge, or discard this patch.
lib/private/Encryption/Util.php 1 patch
Indentation   +366 added lines, -366 removed lines patch added patch discarded remove patch
@@ -20,370 +20,370 @@
 block discarded – undo
20 20
 use OCP\IUserManager;
21 21
 
22 22
 class Util {
23
-	public const HEADER_START = 'HBEGIN';
24
-	public const HEADER_END = 'HEND';
25
-	public const HEADER_PADDING_CHAR = '-';
26
-
27
-	public const HEADER_ENCRYPTION_MODULE_KEY = 'oc_encryption_module';
28
-
29
-	/**
30
-	 * block size will always be 8192 for a PHP stream
31
-	 * @see https://bugs.php.net/bug.php?id=21641
32
-	 * @var integer
33
-	 */
34
-	protected $headerSize = 8192;
35
-
36
-	/**
37
-	 * block size will always be 8192 for a PHP stream
38
-	 * @see https://bugs.php.net/bug.php?id=21641
39
-	 * @var integer
40
-	 */
41
-	protected $blockSize = 8192;
42
-
43
-	/** @var View */
44
-	protected $rootView;
45
-
46
-	/** @var array */
47
-	protected $ocHeaderKeys;
48
-
49
-	/** @var IConfig */
50
-	protected $config;
51
-
52
-	/** @var array paths excluded from encryption */
53
-	protected array $excludedPaths = [];
54
-	protected IGroupManager $groupManager;
55
-	protected IUserManager $userManager;
56
-
57
-	/**
58
-	 *
59
-	 * @param View $rootView
60
-	 * @param IConfig $config
61
-	 */
62
-	public function __construct(
63
-		View $rootView,
64
-		IUserManager $userManager,
65
-		IGroupManager $groupManager,
66
-		IConfig $config) {
67
-		$this->ocHeaderKeys = [
68
-			self::HEADER_ENCRYPTION_MODULE_KEY
69
-		];
70
-
71
-		$this->rootView = $rootView;
72
-		$this->userManager = $userManager;
73
-		$this->groupManager = $groupManager;
74
-		$this->config = $config;
75
-
76
-		$this->excludedPaths[] = 'files_encryption';
77
-		$this->excludedPaths[] = 'appdata_' . $config->getSystemValueString('instanceid');
78
-		$this->excludedPaths[] = 'files_external';
79
-	}
80
-
81
-	/**
82
-	 * read encryption module ID from header
83
-	 *
84
-	 * @param array $header
85
-	 * @return string
86
-	 * @throws ModuleDoesNotExistsException
87
-	 */
88
-	public function getEncryptionModuleId(?array $header = null) {
89
-		$id = '';
90
-		$encryptionModuleKey = self::HEADER_ENCRYPTION_MODULE_KEY;
91
-
92
-		if (isset($header[$encryptionModuleKey])) {
93
-			$id = $header[$encryptionModuleKey];
94
-		} elseif (isset($header['cipher'])) {
95
-			if (class_exists('\OCA\Encryption\Crypto\Encryption')) {
96
-				// fall back to default encryption if the user migrated from
97
-				// ownCloud <= 8.0 with the old encryption
98
-				$id = \OCA\Encryption\Crypto\Encryption::ID;
99
-			} else {
100
-				throw new ModuleDoesNotExistsException('Default encryption module missing');
101
-			}
102
-		}
103
-
104
-		return $id;
105
-	}
106
-
107
-	/**
108
-	 * create header for encrypted file
109
-	 *
110
-	 * @param array $headerData
111
-	 * @param IEncryptionModule $encryptionModule
112
-	 * @return string
113
-	 * @throws EncryptionHeaderToLargeException if header has to many arguments
114
-	 * @throws EncryptionHeaderKeyExistsException if header key is already in use
115
-	 */
116
-	public function createHeader(array $headerData, IEncryptionModule $encryptionModule) {
117
-		$header = self::HEADER_START . ':' . self::HEADER_ENCRYPTION_MODULE_KEY . ':' . $encryptionModule->getId() . ':';
118
-		foreach ($headerData as $key => $value) {
119
-			if (in_array($key, $this->ocHeaderKeys)) {
120
-				throw new EncryptionHeaderKeyExistsException($key);
121
-			}
122
-			$header .= $key . ':' . $value . ':';
123
-		}
124
-		$header .= self::HEADER_END;
125
-
126
-		if (strlen($header) > $this->getHeaderSize()) {
127
-			throw new EncryptionHeaderToLargeException();
128
-		}
129
-
130
-		$paddedHeader = str_pad($header, $this->headerSize, self::HEADER_PADDING_CHAR, STR_PAD_RIGHT);
131
-
132
-		return $paddedHeader;
133
-	}
134
-
135
-	/**
136
-	 * go recursively through a dir and collect all files and sub files.
137
-	 *
138
-	 * @param string $dir relative to the users files folder
139
-	 * @return array with list of files relative to the users files folder
140
-	 */
141
-	public function getAllFiles($dir) {
142
-		$result = [];
143
-		$dirList = [$dir];
144
-
145
-		while ($dirList) {
146
-			$dir = array_pop($dirList);
147
-			$content = $this->rootView->getDirectoryContent($dir);
148
-
149
-			foreach ($content as $c) {
150
-				if ($c->getType() === 'dir') {
151
-					$dirList[] = $c->getPath();
152
-				} else {
153
-					$result[] = $c->getPath();
154
-				}
155
-			}
156
-		}
157
-
158
-		return $result;
159
-	}
160
-
161
-	/**
162
-	 * check if it is a file uploaded by the user stored in data/user/files
163
-	 * or a metadata file
164
-	 *
165
-	 * @param string $path relative to the data/ folder
166
-	 * @return boolean
167
-	 */
168
-	public function isFile($path) {
169
-		$parts = explode('/', Filesystem::normalizePath($path), 4);
170
-		if (isset($parts[2]) && $parts[2] === 'files') {
171
-			return true;
172
-		}
173
-		return false;
174
-	}
175
-
176
-	/**
177
-	 * return size of encryption header
178
-	 *
179
-	 * @return integer
180
-	 */
181
-	public function getHeaderSize() {
182
-		return $this->headerSize;
183
-	}
184
-
185
-	/**
186
-	 * return size of block read by a PHP stream
187
-	 *
188
-	 * @return integer
189
-	 */
190
-	public function getBlockSize() {
191
-		return $this->blockSize;
192
-	}
193
-
194
-	/**
195
-	 * get the owner and the path for the file relative to the owners files folder
196
-	 *
197
-	 * @param string $path
198
-	 * @return array{0: string, 1: string}
199
-	 * @throws \BadMethodCallException
200
-	 */
201
-	public function getUidAndFilename($path) {
202
-		$parts = explode('/', $path);
203
-		$uid = '';
204
-		if (count($parts) > 2) {
205
-			$uid = $parts[1];
206
-		}
207
-		if (!$this->userManager->userExists($uid)) {
208
-			throw new \BadMethodCallException(
209
-				'path needs to be relative to the system wide data folder and point to a user specific file'
210
-			);
211
-		}
212
-
213
-		$ownerPath = implode('/', array_slice($parts, 2));
214
-
215
-		return [$uid, Filesystem::normalizePath($ownerPath)];
216
-	}
217
-
218
-	/**
219
-	 * Remove .path extension from a file path
220
-	 * @param string $path Path that may identify a .part file
221
-	 * @return string File path without .part extension
222
-	 * @note this is needed for reusing keys
223
-	 */
224
-	public function stripPartialFileExtension($path) {
225
-		$extension = pathinfo($path, PATHINFO_EXTENSION);
226
-
227
-		if ($extension === 'part') {
228
-			$newLength = strlen($path) - 5; // 5 = strlen(".part")
229
-			$fPath = substr($path, 0, $newLength);
230
-
231
-			// if path also contains a transaction id, we remove it too
232
-			$extension = pathinfo($fPath, PATHINFO_EXTENSION);
233
-			if (substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId")
234
-				$newLength = strlen($fPath) - strlen($extension) - 1;
235
-				$fPath = substr($fPath, 0, $newLength);
236
-			}
237
-			return $fPath;
238
-		} else {
239
-			return $path;
240
-		}
241
-	}
242
-
243
-	public function getUserWithAccessToMountPoint($users, $groups) {
244
-		$result = [];
245
-		if ($users === [] && $groups === []) {
246
-			$users = $this->userManager->search('', null, null);
247
-			$result = array_map(function (IUser $user) {
248
-				return $user->getUID();
249
-			}, $users);
250
-		} else {
251
-			$result = array_merge($result, $users);
252
-
253
-			$groupManager = $this->groupManager;
254
-			foreach ($groups as $group) {
255
-				$groupObject = $groupManager->get($group);
256
-				if ($groupObject) {
257
-					$foundUsers = $groupObject->searchUsers('', -1, 0);
258
-					$userIds = [];
259
-					foreach ($foundUsers as $user) {
260
-						$userIds[] = $user->getUID();
261
-					}
262
-					$result = array_merge($result, $userIds);
263
-				}
264
-			}
265
-		}
266
-
267
-		return $result;
268
-	}
269
-
270
-	/**
271
-	 * check if the file is stored on a system wide mount point
272
-	 * @param string $path relative to /data/user with leading '/'
273
-	 * @param string $uid
274
-	 * @return boolean
275
-	 */
276
-	public function isSystemWideMountPoint(string $path, string $uid) {
277
-		$mount = Filesystem::getMountManager()->find('/' . $uid . $path);
278
-		return $mount instanceof ISystemMountPoint;
279
-	}
280
-
281
-	/**
282
-	 * check if it is a path which is excluded by ownCloud from encryption
283
-	 *
284
-	 * @param string $path
285
-	 * @return boolean
286
-	 */
287
-	public function isExcluded($path) {
288
-		$normalizedPath = Filesystem::normalizePath($path);
289
-		$root = explode('/', $normalizedPath, 4);
290
-		if (count($root) > 1) {
291
-			// detect alternative key storage root
292
-			$rootDir = $this->getKeyStorageRoot();
293
-			if ($rootDir !== '' &&
294
-				str_starts_with(Filesystem::normalizePath($path), Filesystem::normalizePath($rootDir))
295
-			) {
296
-				return true;
297
-			}
298
-
299
-
300
-			//detect system wide folders
301
-			if (in_array($root[1], $this->excludedPaths)) {
302
-				return true;
303
-			}
304
-
305
-			// detect user specific folders
306
-			if ($this->userManager->userExists($root[1])
307
-				&& in_array($root[2] ?? '', $this->excludedPaths)) {
308
-				return true;
309
-			}
310
-		}
311
-		return false;
312
-	}
313
-
314
-	/**
315
-	 * Check if recovery key is enabled for user
316
-	 */
317
-	public function recoveryEnabled(string $uid): bool {
318
-		$enabled = $this->config->getUserValue($uid, 'encryption', 'recovery_enabled', '0');
319
-
320
-		return $enabled === '1';
321
-	}
322
-
323
-	/**
324
-	 * Set new key storage root
325
-	 *
326
-	 * @param string $root new key store root relative to the data folder
327
-	 */
328
-	public function setKeyStorageRoot(string $root): void {
329
-		$this->config->setAppValue('core', 'encryption_key_storage_root', $root);
330
-	}
331
-
332
-	/**
333
-	 * Get key storage root
334
-	 *
335
-	 * @return string key storage root
336
-	 */
337
-	public function getKeyStorageRoot(): string {
338
-		return $this->config->getAppValue('core', 'encryption_key_storage_root', '');
339
-	}
340
-
341
-	/**
342
-	 * parse raw header to array
343
-	 *
344
-	 * @param string $rawHeader
345
-	 * @return array
346
-	 */
347
-	public function parseRawHeader(string $rawHeader) {
348
-		$result = [];
349
-		if (str_starts_with($rawHeader, Util::HEADER_START)) {
350
-			$header = $rawHeader;
351
-			$endAt = strpos($header, Util::HEADER_END);
352
-			if ($endAt !== false) {
353
-				$header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
354
-
355
-				// +1 to not start with an ':' which would result in empty element at the beginning
356
-				$exploded = explode(':', substr($header, strlen(Util::HEADER_START) + 1));
357
-
358
-				$element = array_shift($exploded);
359
-				while ($element !== Util::HEADER_END && $element !== null) {
360
-					$result[$element] = array_shift($exploded);
361
-					$element = array_shift($exploded);
362
-				}
363
-			}
364
-		}
365
-
366
-		return $result;
367
-	}
368
-
369
-	/**
370
-	 * get path to key folder for a given file
371
-	 *
372
-	 * @param string $encryptionModuleId
373
-	 * @param string $path path to the file, relative to data/
374
-	 * @return string
375
-	 */
376
-	public function getFileKeyDir(string $encryptionModuleId, string $path): string {
377
-		[$owner, $filename] = $this->getUidAndFilename($path);
378
-		$root = $this->getKeyStorageRoot();
379
-
380
-		// in case of system-wide mount points the keys are stored directly in the data directory
381
-		if ($this->isSystemWideMountPoint($filename, $owner)) {
382
-			$keyPath = $root . '/' . '/files_encryption/keys' . $filename . '/';
383
-		} else {
384
-			$keyPath = $root . '/' . $owner . '/files_encryption/keys' . $filename . '/';
385
-		}
386
-
387
-		return Filesystem::normalizePath($keyPath . $encryptionModuleId . '/', false);
388
-	}
23
+    public const HEADER_START = 'HBEGIN';
24
+    public const HEADER_END = 'HEND';
25
+    public const HEADER_PADDING_CHAR = '-';
26
+
27
+    public const HEADER_ENCRYPTION_MODULE_KEY = 'oc_encryption_module';
28
+
29
+    /**
30
+     * block size will always be 8192 for a PHP stream
31
+     * @see https://bugs.php.net/bug.php?id=21641
32
+     * @var integer
33
+     */
34
+    protected $headerSize = 8192;
35
+
36
+    /**
37
+     * block size will always be 8192 for a PHP stream
38
+     * @see https://bugs.php.net/bug.php?id=21641
39
+     * @var integer
40
+     */
41
+    protected $blockSize = 8192;
42
+
43
+    /** @var View */
44
+    protected $rootView;
45
+
46
+    /** @var array */
47
+    protected $ocHeaderKeys;
48
+
49
+    /** @var IConfig */
50
+    protected $config;
51
+
52
+    /** @var array paths excluded from encryption */
53
+    protected array $excludedPaths = [];
54
+    protected IGroupManager $groupManager;
55
+    protected IUserManager $userManager;
56
+
57
+    /**
58
+     *
59
+     * @param View $rootView
60
+     * @param IConfig $config
61
+     */
62
+    public function __construct(
63
+        View $rootView,
64
+        IUserManager $userManager,
65
+        IGroupManager $groupManager,
66
+        IConfig $config) {
67
+        $this->ocHeaderKeys = [
68
+            self::HEADER_ENCRYPTION_MODULE_KEY
69
+        ];
70
+
71
+        $this->rootView = $rootView;
72
+        $this->userManager = $userManager;
73
+        $this->groupManager = $groupManager;
74
+        $this->config = $config;
75
+
76
+        $this->excludedPaths[] = 'files_encryption';
77
+        $this->excludedPaths[] = 'appdata_' . $config->getSystemValueString('instanceid');
78
+        $this->excludedPaths[] = 'files_external';
79
+    }
80
+
81
+    /**
82
+     * read encryption module ID from header
83
+     *
84
+     * @param array $header
85
+     * @return string
86
+     * @throws ModuleDoesNotExistsException
87
+     */
88
+    public function getEncryptionModuleId(?array $header = null) {
89
+        $id = '';
90
+        $encryptionModuleKey = self::HEADER_ENCRYPTION_MODULE_KEY;
91
+
92
+        if (isset($header[$encryptionModuleKey])) {
93
+            $id = $header[$encryptionModuleKey];
94
+        } elseif (isset($header['cipher'])) {
95
+            if (class_exists('\OCA\Encryption\Crypto\Encryption')) {
96
+                // fall back to default encryption if the user migrated from
97
+                // ownCloud <= 8.0 with the old encryption
98
+                $id = \OCA\Encryption\Crypto\Encryption::ID;
99
+            } else {
100
+                throw new ModuleDoesNotExistsException('Default encryption module missing');
101
+            }
102
+        }
103
+
104
+        return $id;
105
+    }
106
+
107
+    /**
108
+     * create header for encrypted file
109
+     *
110
+     * @param array $headerData
111
+     * @param IEncryptionModule $encryptionModule
112
+     * @return string
113
+     * @throws EncryptionHeaderToLargeException if header has to many arguments
114
+     * @throws EncryptionHeaderKeyExistsException if header key is already in use
115
+     */
116
+    public function createHeader(array $headerData, IEncryptionModule $encryptionModule) {
117
+        $header = self::HEADER_START . ':' . self::HEADER_ENCRYPTION_MODULE_KEY . ':' . $encryptionModule->getId() . ':';
118
+        foreach ($headerData as $key => $value) {
119
+            if (in_array($key, $this->ocHeaderKeys)) {
120
+                throw new EncryptionHeaderKeyExistsException($key);
121
+            }
122
+            $header .= $key . ':' . $value . ':';
123
+        }
124
+        $header .= self::HEADER_END;
125
+
126
+        if (strlen($header) > $this->getHeaderSize()) {
127
+            throw new EncryptionHeaderToLargeException();
128
+        }
129
+
130
+        $paddedHeader = str_pad($header, $this->headerSize, self::HEADER_PADDING_CHAR, STR_PAD_RIGHT);
131
+
132
+        return $paddedHeader;
133
+    }
134
+
135
+    /**
136
+     * go recursively through a dir and collect all files and sub files.
137
+     *
138
+     * @param string $dir relative to the users files folder
139
+     * @return array with list of files relative to the users files folder
140
+     */
141
+    public function getAllFiles($dir) {
142
+        $result = [];
143
+        $dirList = [$dir];
144
+
145
+        while ($dirList) {
146
+            $dir = array_pop($dirList);
147
+            $content = $this->rootView->getDirectoryContent($dir);
148
+
149
+            foreach ($content as $c) {
150
+                if ($c->getType() === 'dir') {
151
+                    $dirList[] = $c->getPath();
152
+                } else {
153
+                    $result[] = $c->getPath();
154
+                }
155
+            }
156
+        }
157
+
158
+        return $result;
159
+    }
160
+
161
+    /**
162
+     * check if it is a file uploaded by the user stored in data/user/files
163
+     * or a metadata file
164
+     *
165
+     * @param string $path relative to the data/ folder
166
+     * @return boolean
167
+     */
168
+    public function isFile($path) {
169
+        $parts = explode('/', Filesystem::normalizePath($path), 4);
170
+        if (isset($parts[2]) && $parts[2] === 'files') {
171
+            return true;
172
+        }
173
+        return false;
174
+    }
175
+
176
+    /**
177
+     * return size of encryption header
178
+     *
179
+     * @return integer
180
+     */
181
+    public function getHeaderSize() {
182
+        return $this->headerSize;
183
+    }
184
+
185
+    /**
186
+     * return size of block read by a PHP stream
187
+     *
188
+     * @return integer
189
+     */
190
+    public function getBlockSize() {
191
+        return $this->blockSize;
192
+    }
193
+
194
+    /**
195
+     * get the owner and the path for the file relative to the owners files folder
196
+     *
197
+     * @param string $path
198
+     * @return array{0: string, 1: string}
199
+     * @throws \BadMethodCallException
200
+     */
201
+    public function getUidAndFilename($path) {
202
+        $parts = explode('/', $path);
203
+        $uid = '';
204
+        if (count($parts) > 2) {
205
+            $uid = $parts[1];
206
+        }
207
+        if (!$this->userManager->userExists($uid)) {
208
+            throw new \BadMethodCallException(
209
+                'path needs to be relative to the system wide data folder and point to a user specific file'
210
+            );
211
+        }
212
+
213
+        $ownerPath = implode('/', array_slice($parts, 2));
214
+
215
+        return [$uid, Filesystem::normalizePath($ownerPath)];
216
+    }
217
+
218
+    /**
219
+     * Remove .path extension from a file path
220
+     * @param string $path Path that may identify a .part file
221
+     * @return string File path without .part extension
222
+     * @note this is needed for reusing keys
223
+     */
224
+    public function stripPartialFileExtension($path) {
225
+        $extension = pathinfo($path, PATHINFO_EXTENSION);
226
+
227
+        if ($extension === 'part') {
228
+            $newLength = strlen($path) - 5; // 5 = strlen(".part")
229
+            $fPath = substr($path, 0, $newLength);
230
+
231
+            // if path also contains a transaction id, we remove it too
232
+            $extension = pathinfo($fPath, PATHINFO_EXTENSION);
233
+            if (substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId")
234
+                $newLength = strlen($fPath) - strlen($extension) - 1;
235
+                $fPath = substr($fPath, 0, $newLength);
236
+            }
237
+            return $fPath;
238
+        } else {
239
+            return $path;
240
+        }
241
+    }
242
+
243
+    public function getUserWithAccessToMountPoint($users, $groups) {
244
+        $result = [];
245
+        if ($users === [] && $groups === []) {
246
+            $users = $this->userManager->search('', null, null);
247
+            $result = array_map(function (IUser $user) {
248
+                return $user->getUID();
249
+            }, $users);
250
+        } else {
251
+            $result = array_merge($result, $users);
252
+
253
+            $groupManager = $this->groupManager;
254
+            foreach ($groups as $group) {
255
+                $groupObject = $groupManager->get($group);
256
+                if ($groupObject) {
257
+                    $foundUsers = $groupObject->searchUsers('', -1, 0);
258
+                    $userIds = [];
259
+                    foreach ($foundUsers as $user) {
260
+                        $userIds[] = $user->getUID();
261
+                    }
262
+                    $result = array_merge($result, $userIds);
263
+                }
264
+            }
265
+        }
266
+
267
+        return $result;
268
+    }
269
+
270
+    /**
271
+     * check if the file is stored on a system wide mount point
272
+     * @param string $path relative to /data/user with leading '/'
273
+     * @param string $uid
274
+     * @return boolean
275
+     */
276
+    public function isSystemWideMountPoint(string $path, string $uid) {
277
+        $mount = Filesystem::getMountManager()->find('/' . $uid . $path);
278
+        return $mount instanceof ISystemMountPoint;
279
+    }
280
+
281
+    /**
282
+     * check if it is a path which is excluded by ownCloud from encryption
283
+     *
284
+     * @param string $path
285
+     * @return boolean
286
+     */
287
+    public function isExcluded($path) {
288
+        $normalizedPath = Filesystem::normalizePath($path);
289
+        $root = explode('/', $normalizedPath, 4);
290
+        if (count($root) > 1) {
291
+            // detect alternative key storage root
292
+            $rootDir = $this->getKeyStorageRoot();
293
+            if ($rootDir !== '' &&
294
+                str_starts_with(Filesystem::normalizePath($path), Filesystem::normalizePath($rootDir))
295
+            ) {
296
+                return true;
297
+            }
298
+
299
+
300
+            //detect system wide folders
301
+            if (in_array($root[1], $this->excludedPaths)) {
302
+                return true;
303
+            }
304
+
305
+            // detect user specific folders
306
+            if ($this->userManager->userExists($root[1])
307
+                && in_array($root[2] ?? '', $this->excludedPaths)) {
308
+                return true;
309
+            }
310
+        }
311
+        return false;
312
+    }
313
+
314
+    /**
315
+     * Check if recovery key is enabled for user
316
+     */
317
+    public function recoveryEnabled(string $uid): bool {
318
+        $enabled = $this->config->getUserValue($uid, 'encryption', 'recovery_enabled', '0');
319
+
320
+        return $enabled === '1';
321
+    }
322
+
323
+    /**
324
+     * Set new key storage root
325
+     *
326
+     * @param string $root new key store root relative to the data folder
327
+     */
328
+    public function setKeyStorageRoot(string $root): void {
329
+        $this->config->setAppValue('core', 'encryption_key_storage_root', $root);
330
+    }
331
+
332
+    /**
333
+     * Get key storage root
334
+     *
335
+     * @return string key storage root
336
+     */
337
+    public function getKeyStorageRoot(): string {
338
+        return $this->config->getAppValue('core', 'encryption_key_storage_root', '');
339
+    }
340
+
341
+    /**
342
+     * parse raw header to array
343
+     *
344
+     * @param string $rawHeader
345
+     * @return array
346
+     */
347
+    public function parseRawHeader(string $rawHeader) {
348
+        $result = [];
349
+        if (str_starts_with($rawHeader, Util::HEADER_START)) {
350
+            $header = $rawHeader;
351
+            $endAt = strpos($header, Util::HEADER_END);
352
+            if ($endAt !== false) {
353
+                $header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
354
+
355
+                // +1 to not start with an ':' which would result in empty element at the beginning
356
+                $exploded = explode(':', substr($header, strlen(Util::HEADER_START) + 1));
357
+
358
+                $element = array_shift($exploded);
359
+                while ($element !== Util::HEADER_END && $element !== null) {
360
+                    $result[$element] = array_shift($exploded);
361
+                    $element = array_shift($exploded);
362
+                }
363
+            }
364
+        }
365
+
366
+        return $result;
367
+    }
368
+
369
+    /**
370
+     * get path to key folder for a given file
371
+     *
372
+     * @param string $encryptionModuleId
373
+     * @param string $path path to the file, relative to data/
374
+     * @return string
375
+     */
376
+    public function getFileKeyDir(string $encryptionModuleId, string $path): string {
377
+        [$owner, $filename] = $this->getUidAndFilename($path);
378
+        $root = $this->getKeyStorageRoot();
379
+
380
+        // in case of system-wide mount points the keys are stored directly in the data directory
381
+        if ($this->isSystemWideMountPoint($filename, $owner)) {
382
+            $keyPath = $root . '/' . '/files_encryption/keys' . $filename . '/';
383
+        } else {
384
+            $keyPath = $root . '/' . $owner . '/files_encryption/keys' . $filename . '/';
385
+        }
386
+
387
+        return Filesystem::normalizePath($keyPath . $encryptionModuleId . '/', false);
388
+    }
389 389
 }
Please login to merge, or discard this patch.
lib/private/Encryption/EncryptionEventListener.php 1 patch
Indentation   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -25,69 +25,69 @@
 block discarded – undo
25 25
 
26 26
 /** @template-implements IEventListener<NodeRenamedEvent|ShareCreatedEvent|ShareDeletedEvent|NodeRestoredEvent> */
27 27
 class EncryptionEventListener implements IEventListener {
28
-	private ?Update $updater = null;
28
+    private ?Update $updater = null;
29 29
 
30
-	public function __construct(
31
-		private IUserSession $userSession,
32
-		private SetupManager $setupManager,
33
-		private Manager $encryptionManager,
34
-	) {
35
-	}
30
+    public function __construct(
31
+        private IUserSession $userSession,
32
+        private SetupManager $setupManager,
33
+        private Manager $encryptionManager,
34
+    ) {
35
+    }
36 36
 
37
-	public static function register(IEventDispatcher $dispatcher): void {
38
-		$dispatcher->addServiceListener(NodeRenamedEvent::class, static::class);
39
-		$dispatcher->addServiceListener(ShareCreatedEvent::class, static::class);
40
-		$dispatcher->addServiceListener(ShareDeletedEvent::class, static::class);
41
-		$dispatcher->addServiceListener(NodeRestoredEvent::class, static::class);
42
-	}
37
+    public static function register(IEventDispatcher $dispatcher): void {
38
+        $dispatcher->addServiceListener(NodeRenamedEvent::class, static::class);
39
+        $dispatcher->addServiceListener(ShareCreatedEvent::class, static::class);
40
+        $dispatcher->addServiceListener(ShareDeletedEvent::class, static::class);
41
+        $dispatcher->addServiceListener(NodeRestoredEvent::class, static::class);
42
+    }
43 43
 
44
-	public function handle(Event $event): void {
45
-		if (!$this->encryptionManager->isEnabled()) {
46
-			return;
47
-		}
48
-		if ($event instanceof NodeRenamedEvent) {
49
-			$this->getUpdate()->postRename($event->getSource(), $event->getTarget());
50
-		} elseif ($event instanceof ShareCreatedEvent) {
51
-			$this->getUpdate()->postShared($event->getShare()->getNode());
52
-		} elseif ($event instanceof ShareDeletedEvent) {
53
-			// In case the unsharing happens in a background job, we don't have
54
-			// a session and we load instead the user from the UserManager
55
-			$owner = $event->getShare()->getNode()->getOwner();
56
-			$this->getUpdate($owner)->postUnshared($event->getShare()->getNode());
57
-		} elseif ($event instanceof NodeRestoredEvent) {
58
-			$this->getUpdate()->postRestore($event->getTarget());
59
-		}
60
-	}
44
+    public function handle(Event $event): void {
45
+        if (!$this->encryptionManager->isEnabled()) {
46
+            return;
47
+        }
48
+        if ($event instanceof NodeRenamedEvent) {
49
+            $this->getUpdate()->postRename($event->getSource(), $event->getTarget());
50
+        } elseif ($event instanceof ShareCreatedEvent) {
51
+            $this->getUpdate()->postShared($event->getShare()->getNode());
52
+        } elseif ($event instanceof ShareDeletedEvent) {
53
+            // In case the unsharing happens in a background job, we don't have
54
+            // a session and we load instead the user from the UserManager
55
+            $owner = $event->getShare()->getNode()->getOwner();
56
+            $this->getUpdate($owner)->postUnshared($event->getShare()->getNode());
57
+        } elseif ($event instanceof NodeRestoredEvent) {
58
+            $this->getUpdate()->postRestore($event->getTarget());
59
+        }
60
+    }
61 61
 
62
-	private function getUpdate(?IUser $owner = null): Update {
63
-		if (is_null($this->updater)) {
64
-			$user = $this->userSession->getUser();
65
-			if (!$user && ($owner !== null)) {
66
-				$user = $owner;
67
-			}
68
-			if (!$user) {
69
-				throw new \Exception('Inconsistent data, File unshared, but owner not found. Should not happen');
70
-			}
62
+    private function getUpdate(?IUser $owner = null): Update {
63
+        if (is_null($this->updater)) {
64
+            $user = $this->userSession->getUser();
65
+            if (!$user && ($owner !== null)) {
66
+                $user = $owner;
67
+            }
68
+            if (!$user) {
69
+                throw new \Exception('Inconsistent data, File unshared, but owner not found. Should not happen');
70
+            }
71 71
 
72
-			$uid = $user->getUID();
72
+            $uid = $user->getUID();
73 73
 
74
-			if (!$this->setupManager->isSetupComplete($user)) {
75
-				$this->setupManager->setupForUser($user);
76
-			}
74
+            if (!$this->setupManager->isSetupComplete($user)) {
75
+                $this->setupManager->setupForUser($user);
76
+            }
77 77
 
78
-			$this->updater = new Update(
79
-				new Util(
80
-					new View(),
81
-					\OC::$server->getUserManager(),
82
-					\OC::$server->getGroupManager(),
83
-					\OC::$server->getConfig()),
84
-				\OC::$server->getEncryptionManager(),
85
-				\OC::$server->get(IFile::class),
86
-				\OC::$server->get(LoggerInterface::class),
87
-				$uid
88
-			);
89
-		}
78
+            $this->updater = new Update(
79
+                new Util(
80
+                    new View(),
81
+                    \OC::$server->getUserManager(),
82
+                    \OC::$server->getGroupManager(),
83
+                    \OC::$server->getConfig()),
84
+                \OC::$server->getEncryptionManager(),
85
+                \OC::$server->get(IFile::class),
86
+                \OC::$server->get(LoggerInterface::class),
87
+                $uid
88
+            );
89
+        }
90 90
 
91
-		return $this->updater;
92
-	}
91
+        return $this->updater;
92
+    }
93 93
 }
Please login to merge, or discard this patch.
lib/private/Files/Storage/Wrapper/Encryption.php 1 patch
Indentation   +901 added lines, -901 removed lines patch added patch discarded remove patch
@@ -27,905 +27,905 @@
 block discarded – undo
27 27
 use Psr\Log\LoggerInterface;
28 28
 
29 29
 class Encryption extends Wrapper {
30
-	use LocalTempFileTrait;
31
-
32
-	private string $mountPoint;
33
-	protected array $unencryptedSize = [];
34
-	private IMountPoint $mount;
35
-	/** for which path we execute the repair step to avoid recursions */
36
-	private array $fixUnencryptedSizeOf = [];
37
-	/** @var CappedMemoryCache<bool> */
38
-	private CappedMemoryCache $encryptedPaths;
39
-	private bool $enabled = true;
40
-
41
-	/**
42
-	 * @param array $parameters
43
-	 */
44
-	public function __construct(
45
-		array $parameters,
46
-		private IManager $encryptionManager,
47
-		private Util $util,
48
-		private LoggerInterface $logger,
49
-		private IFile $fileHelper,
50
-		private ?string $uid,
51
-		private IStorage $keyStorage,
52
-		private Manager $mountManager,
53
-		private ArrayCache $arrayCache,
54
-	) {
55
-		$this->mountPoint = $parameters['mountPoint'];
56
-		$this->mount = $parameters['mount'];
57
-		$this->encryptedPaths = new CappedMemoryCache();
58
-		parent::__construct($parameters);
59
-	}
60
-
61
-	public function filesize(string $path): int|float|false {
62
-		$fullPath = $this->getFullPath($path);
63
-
64
-		$info = $this->getCache()->get($path);
65
-		if ($info === false) {
66
-			/* Pass call to wrapped storage, it may be a special file like a part file */
67
-			return $this->storage->filesize($path);
68
-		}
69
-		if (isset($this->unencryptedSize[$fullPath])) {
70
-			$size = $this->unencryptedSize[$fullPath];
71
-
72
-			// Update file cache (only if file is already cached).
73
-			// Certain files are not cached (e.g. *.part).
74
-			if (isset($info['fileid'])) {
75
-				if ($info instanceof ICacheEntry) {
76
-					$info['encrypted'] = $info['encryptedVersion'];
77
-				} else {
78
-					/**
79
-					 * @psalm-suppress RedundantCondition
80
-					 */
81
-					if (!is_array($info)) {
82
-						$info = [];
83
-					}
84
-					$info['encrypted'] = true;
85
-					$info = new CacheEntry($info);
86
-				}
87
-
88
-				if ($size !== $info->getUnencryptedSize()) {
89
-					$this->getCache()->update($info->getId(), [
90
-						'unencrypted_size' => $size
91
-					]);
92
-				}
93
-			}
94
-
95
-			return $size;
96
-		}
97
-
98
-		if (isset($info['fileid']) && $info['encrypted']) {
99
-			return $this->verifyUnencryptedSize($path, $info->getUnencryptedSize());
100
-		}
101
-
102
-		return $this->storage->filesize($path);
103
-	}
104
-
105
-	private function modifyMetaData(string $path, array $data): array {
106
-		$fullPath = $this->getFullPath($path);
107
-		$info = $this->getCache()->get($path);
108
-
109
-		if (isset($this->unencryptedSize[$fullPath])) {
110
-			$data['encrypted'] = true;
111
-			$data['size'] = $this->unencryptedSize[$fullPath];
112
-			$data['unencrypted_size'] = $data['size'];
113
-		} else {
114
-			if (isset($info['fileid']) && $info['encrypted']) {
115
-				$data['size'] = $this->verifyUnencryptedSize($path, $info->getUnencryptedSize());
116
-				$data['encrypted'] = true;
117
-				$data['unencrypted_size'] = $data['size'];
118
-			}
119
-		}
120
-
121
-		if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
122
-			$data['encryptedVersion'] = $info['encryptedVersion'];
123
-		}
124
-
125
-		return $data;
126
-	}
127
-
128
-	public function getMetaData(string $path): ?array {
129
-		$data = $this->storage->getMetaData($path);
130
-		if (is_null($data)) {
131
-			return null;
132
-		}
133
-		return $this->modifyMetaData($path, $data);
134
-	}
135
-
136
-	public function getDirectoryContent(string $directory): \Traversable {
137
-		$parent = rtrim($directory, '/');
138
-		foreach ($this->getWrapperStorage()->getDirectoryContent($directory) as $data) {
139
-			yield $this->modifyMetaData($parent . '/' . $data['name'], $data);
140
-		}
141
-	}
142
-
143
-	public function file_get_contents(string $path): string|false {
144
-		$encryptionModule = $this->getEncryptionModule($path);
145
-
146
-		if ($encryptionModule) {
147
-			$handle = $this->fopen($path, 'r');
148
-			if (!$handle) {
149
-				return false;
150
-			}
151
-			$data = stream_get_contents($handle);
152
-			fclose($handle);
153
-			return $data;
154
-		}
155
-		return $this->storage->file_get_contents($path);
156
-	}
157
-
158
-	public function file_put_contents(string $path, mixed $data): int|float|false {
159
-		// file put content will always be translated to a stream write
160
-		$handle = $this->fopen($path, 'w');
161
-		if (is_resource($handle)) {
162
-			$written = fwrite($handle, $data);
163
-			fclose($handle);
164
-			return $written;
165
-		}
166
-
167
-		return false;
168
-	}
169
-
170
-	public function unlink(string $path): bool {
171
-		$fullPath = $this->getFullPath($path);
172
-		if ($this->util->isExcluded($fullPath)) {
173
-			return $this->storage->unlink($path);
174
-		}
175
-
176
-		$encryptionModule = $this->getEncryptionModule($path);
177
-		if ($encryptionModule) {
178
-			$this->keyStorage->deleteAllFileKeys($fullPath);
179
-		}
180
-
181
-		return $this->storage->unlink($path);
182
-	}
183
-
184
-	public function rename(string $source, string $target): bool {
185
-		$result = $this->storage->rename($source, $target);
186
-
187
-		if ($result &&
188
-			// versions always use the keys from the original file, so we can skip
189
-			// this step for versions
190
-			$this->isVersion($target) === false &&
191
-			$this->encryptionManager->isEnabled()) {
192
-			$sourcePath = $this->getFullPath($source);
193
-			if (!$this->util->isExcluded($sourcePath)) {
194
-				$targetPath = $this->getFullPath($target);
195
-				if (isset($this->unencryptedSize[$sourcePath])) {
196
-					$this->unencryptedSize[$targetPath] = $this->unencryptedSize[$sourcePath];
197
-				}
198
-				$this->keyStorage->renameKeys($sourcePath, $targetPath);
199
-				$module = $this->getEncryptionModule($target);
200
-				if ($module) {
201
-					$module->update($targetPath, $this->uid, []);
202
-				}
203
-			}
204
-		}
205
-
206
-		return $result;
207
-	}
208
-
209
-	public function rmdir(string $path): bool {
210
-		$result = $this->storage->rmdir($path);
211
-		$fullPath = $this->getFullPath($path);
212
-		if ($result &&
213
-			$this->util->isExcluded($fullPath) === false &&
214
-			$this->encryptionManager->isEnabled()
215
-		) {
216
-			$this->keyStorage->deleteAllFileKeys($fullPath);
217
-		}
218
-
219
-		return $result;
220
-	}
221
-
222
-	public function isReadable(string $path): bool {
223
-		$isReadable = true;
224
-
225
-		$metaData = $this->getMetaData($path);
226
-		if (
227
-			!$this->is_dir($path) &&
228
-			isset($metaData['encrypted']) &&
229
-			$metaData['encrypted'] === true
230
-		) {
231
-			$fullPath = $this->getFullPath($path);
232
-			$module = $this->getEncryptionModule($path);
233
-			$isReadable = $module->isReadable($fullPath, $this->uid);
234
-		}
235
-
236
-		return $this->storage->isReadable($path) && $isReadable;
237
-	}
238
-
239
-	public function copy(string $source, string $target): bool {
240
-		$sourcePath = $this->getFullPath($source);
241
-
242
-		if ($this->util->isExcluded($sourcePath)) {
243
-			return $this->storage->copy($source, $target);
244
-		}
245
-
246
-		// need to stream copy file by file in case we copy between a encrypted
247
-		// and a unencrypted storage
248
-		$this->unlink($target);
249
-		return $this->copyFromStorage($this, $source, $target);
250
-	}
251
-
252
-	public function fopen(string $path, string $mode) {
253
-		// check if the file is stored in the array cache, this means that we
254
-		// copy a file over to the versions folder, in this case we don't want to
255
-		// decrypt it
256
-		if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
257
-			$this->arrayCache->remove('encryption_copy_version_' . $path);
258
-			return $this->storage->fopen($path, $mode);
259
-		}
260
-
261
-		if (!$this->enabled) {
262
-			return $this->storage->fopen($path, $mode);
263
-		}
264
-
265
-		$encryptionEnabled = $this->encryptionManager->isEnabled();
266
-		$shouldEncrypt = false;
267
-		$encryptionModule = null;
268
-		$header = $this->getHeader($path);
269
-		$signed = isset($header['signed']) && $header['signed'] === 'true';
270
-		$fullPath = $this->getFullPath($path);
271
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
272
-
273
-		if ($this->util->isExcluded($fullPath) === false) {
274
-			$size = $unencryptedSize = 0;
275
-			$realFile = $this->util->stripPartialFileExtension($path);
276
-			$targetExists = $this->is_file($realFile) || $this->file_exists($path);
277
-			$targetIsEncrypted = false;
278
-			if ($targetExists) {
279
-				// in case the file exists we require the explicit module as
280
-				// specified in the file header - otherwise we need to fail hard to
281
-				// prevent data loss on client side
282
-				if (!empty($encryptionModuleId)) {
283
-					$targetIsEncrypted = true;
284
-					$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
285
-				}
286
-
287
-				if ($this->file_exists($path)) {
288
-					$size = $this->storage->filesize($path);
289
-					$unencryptedSize = $this->filesize($path);
290
-				} else {
291
-					$size = $unencryptedSize = 0;
292
-				}
293
-			}
294
-
295
-			try {
296
-				if (
297
-					$mode === 'w'
298
-					|| $mode === 'w+'
299
-					|| $mode === 'wb'
300
-					|| $mode === 'wb+'
301
-				) {
302
-					// if we update a encrypted file with a un-encrypted one we change the db flag
303
-					if ($targetIsEncrypted && $encryptionEnabled === false) {
304
-						$cache = $this->storage->getCache();
305
-						$entry = $cache->get($path);
306
-						$cache->update($entry->getId(), ['encrypted' => 0]);
307
-					}
308
-					if ($encryptionEnabled) {
309
-						// if $encryptionModuleId is empty, the default module will be used
310
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
311
-						$shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
312
-						$signed = true;
313
-					}
314
-				} else {
315
-					$info = $this->getCache()->get($path);
316
-					// only get encryption module if we found one in the header
317
-					// or if file should be encrypted according to the file cache
318
-					if (!empty($encryptionModuleId)) {
319
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
320
-						$shouldEncrypt = true;
321
-					} elseif ($info !== false && $info['encrypted'] === true) {
322
-						// we come from a old installation. No header and/or no module defined
323
-						// but the file is encrypted. In this case we need to use the
324
-						// OC_DEFAULT_MODULE to read the file
325
-						$encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
326
-						$shouldEncrypt = true;
327
-						$targetIsEncrypted = true;
328
-					}
329
-				}
330
-			} catch (ModuleDoesNotExistsException $e) {
331
-				$this->logger->warning('Encryption module "' . $encryptionModuleId . '" not found, file will be stored unencrypted', [
332
-					'exception' => $e,
333
-					'app' => 'core',
334
-				]);
335
-			}
336
-
337
-			// encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
338
-			if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
339
-				if (!$targetExists || !$targetIsEncrypted) {
340
-					$shouldEncrypt = false;
341
-				}
342
-			}
343
-
344
-			if ($shouldEncrypt === true && $encryptionModule !== null) {
345
-				$this->encryptedPaths->set($this->util->stripPartialFileExtension($path), true);
346
-				$headerSize = $this->getHeaderSize($path);
347
-				if ($mode === 'r' && $headerSize === 0) {
348
-					$firstBlock = $this->readFirstBlock($path);
349
-					if (!$firstBlock) {
350
-						throw new InvalidHeaderException("Unable to get header block for $path");
351
-					} elseif (!str_starts_with($firstBlock, Util::HEADER_START)) {
352
-						throw new InvalidHeaderException("Unable to get header size for $path, file doesn't start with encryption header");
353
-					} else {
354
-						throw new InvalidHeaderException("Unable to get header size for $path, even though file does start with encryption header");
355
-					}
356
-				}
357
-				$source = $this->storage->fopen($path, $mode);
358
-				if (!is_resource($source)) {
359
-					return false;
360
-				}
361
-				$handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
362
-					$this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
363
-					$size, $unencryptedSize, $headerSize, $signed);
364
-
365
-				return $handle;
366
-			}
367
-		}
368
-
369
-		return $this->storage->fopen($path, $mode);
370
-	}
371
-
372
-
373
-	/**
374
-	 * perform some plausibility checks if the unencrypted size is correct.
375
-	 * If not, we calculate the correct unencrypted size and return it
376
-	 *
377
-	 * @param string $path internal path relative to the storage root
378
-	 * @param int $unencryptedSize size of the unencrypted file
379
-	 *
380
-	 * @return int unencrypted size
381
-	 */
382
-	protected function verifyUnencryptedSize(string $path, int $unencryptedSize): int {
383
-		$size = $this->storage->filesize($path);
384
-		$result = $unencryptedSize;
385
-
386
-		if ($unencryptedSize < 0 ||
387
-			($size > 0 && $unencryptedSize === $size) ||
388
-			$unencryptedSize > $size
389
-		) {
390
-			// check if we already calculate the unencrypted size for the
391
-			// given path to avoid recursions
392
-			if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
393
-				$this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
394
-				try {
395
-					$result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
396
-				} catch (\Exception $e) {
397
-					$this->logger->error('Couldn\'t re-calculate unencrypted size for ' . $path, ['exception' => $e]);
398
-				}
399
-				unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
400
-			}
401
-		}
402
-
403
-		return $result;
404
-	}
405
-
406
-	/**
407
-	 * calculate the unencrypted size
408
-	 *
409
-	 * @param string $path internal path relative to the storage root
410
-	 * @param int $size size of the physical file
411
-	 * @param int $unencryptedSize size of the unencrypted file
412
-	 */
413
-	protected function fixUnencryptedSize(string $path, int $size, int $unencryptedSize): int|float {
414
-		$headerSize = $this->getHeaderSize($path);
415
-		$header = $this->getHeader($path);
416
-		$encryptionModule = $this->getEncryptionModule($path);
417
-
418
-		$stream = $this->storage->fopen($path, 'r');
419
-
420
-		// if we couldn't open the file we return the old unencrypted size
421
-		if (!is_resource($stream)) {
422
-			$this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
423
-			return $unencryptedSize;
424
-		}
425
-
426
-		$newUnencryptedSize = 0;
427
-		$size -= $headerSize;
428
-		$blockSize = $this->util->getBlockSize();
429
-
430
-		// if a header exists we skip it
431
-		if ($headerSize > 0) {
432
-			$this->fread_block($stream, $headerSize);
433
-		}
434
-
435
-		// fast path, else the calculation for $lastChunkNr is bogus
436
-		if ($size === 0) {
437
-			return 0;
438
-		}
439
-
440
-		$signed = isset($header['signed']) && $header['signed'] === 'true';
441
-		$unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
442
-
443
-		// calculate last chunk nr
444
-		// next highest is end of chunks, one subtracted is last one
445
-		// we have to read the last chunk, we can't just calculate it (because of padding etc)
446
-
447
-		$lastChunkNr = ceil($size / $blockSize) - 1;
448
-		// calculate last chunk position
449
-		$lastChunkPos = ($lastChunkNr * $blockSize);
450
-		// try to fseek to the last chunk, if it fails we have to read the whole file
451
-		if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
452
-			$newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
453
-		}
454
-
455
-		$lastChunkContentEncrypted = '';
456
-		$count = $blockSize;
457
-
458
-		while ($count > 0) {
459
-			$data = $this->fread_block($stream, $blockSize);
460
-			$count = strlen($data);
461
-			$lastChunkContentEncrypted .= $data;
462
-			if (strlen($lastChunkContentEncrypted) > $blockSize) {
463
-				$newUnencryptedSize += $unencryptedBlockSize;
464
-				$lastChunkContentEncrypted = substr($lastChunkContentEncrypted, $blockSize);
465
-			}
466
-		}
467
-
468
-		fclose($stream);
469
-
470
-		// we have to decrypt the last chunk to get it actual size
471
-		$encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
472
-		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
473
-		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
474
-
475
-		// calc the real file size with the size of the last chunk
476
-		$newUnencryptedSize += strlen($decryptedLastChunk);
477
-
478
-		$this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
479
-
480
-		// write to cache if applicable
481
-		$cache = $this->storage->getCache();
482
-		$entry = $cache->get($path);
483
-		$cache->update($entry['fileid'], [
484
-			'unencrypted_size' => $newUnencryptedSize
485
-		]);
486
-
487
-		return $newUnencryptedSize;
488
-	}
489
-
490
-	/**
491
-	 * fread_block
492
-	 *
493
-	 * This function is a wrapper around the fread function.  It is based on the
494
-	 * stream_read_block function from lib/private/Files/Streams/Encryption.php
495
-	 * It calls stream read until the requested $blockSize was received or no remaining data is present.
496
-	 * This is required as stream_read only returns smaller chunks of data when the stream fetches from a
497
-	 * remote storage over the internet and it does not care about the given $blockSize.
498
-	 *
499
-	 * @param resource $handle the stream to read from
500
-	 * @param int $blockSize Length of requested data block in bytes
501
-	 * @return string Data fetched from stream.
502
-	 */
503
-	private function fread_block($handle, int $blockSize): string {
504
-		$remaining = $blockSize;
505
-		$data = '';
506
-
507
-		do {
508
-			$chunk = fread($handle, $remaining);
509
-			$chunk_len = strlen($chunk);
510
-			$data .= $chunk;
511
-			$remaining -= $chunk_len;
512
-		} while (($remaining > 0) && ($chunk_len > 0));
513
-
514
-		return $data;
515
-	}
516
-
517
-	public function moveFromStorage(
518
-		Storage\IStorage $sourceStorage,
519
-		string $sourceInternalPath,
520
-		string $targetInternalPath,
521
-		$preserveMtime = true,
522
-	): bool {
523
-		if ($sourceStorage === $this) {
524
-			return $this->rename($sourceInternalPath, $targetInternalPath);
525
-		}
526
-
527
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
528
-		// - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
529
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
530
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
531
-		// - remove $this->copyBetweenStorage
532
-
533
-		if (!$sourceStorage->isDeletable($sourceInternalPath)) {
534
-			return false;
535
-		}
536
-
537
-		$result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
538
-		if ($result) {
539
-			$setPreserveCacheOnDelete = $sourceStorage->instanceOfStorage(ObjectStoreStorage::class) && !$this->instanceOfStorage(ObjectStoreStorage::class);
540
-			if ($setPreserveCacheOnDelete) {
541
-				/** @var ObjectStoreStorage $sourceStorage */
542
-				$sourceStorage->setPreserveCacheOnDelete(true);
543
-			}
544
-			try {
545
-				if ($sourceStorage->is_dir($sourceInternalPath)) {
546
-					$result = $sourceStorage->rmdir($sourceInternalPath);
547
-				} else {
548
-					$result = $sourceStorage->unlink($sourceInternalPath);
549
-				}
550
-			} finally {
551
-				if ($setPreserveCacheOnDelete) {
552
-					/** @var ObjectStoreStorage $sourceStorage */
553
-					$sourceStorage->setPreserveCacheOnDelete(false);
554
-				}
555
-			}
556
-		}
557
-		return $result;
558
-	}
559
-
560
-	public function copyFromStorage(
561
-		Storage\IStorage $sourceStorage,
562
-		string $sourceInternalPath,
563
-		string $targetInternalPath,
564
-		$preserveMtime = false,
565
-		$isRename = false,
566
-	): bool {
567
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
568
-		// - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
569
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
570
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
571
-		// - remove $this->copyBetweenStorage
572
-
573
-		return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
574
-	}
575
-
576
-	/**
577
-	 * Update the encrypted cache version in the database
578
-	 */
579
-	private function updateEncryptedVersion(
580
-		Storage\IStorage $sourceStorage,
581
-		string $sourceInternalPath,
582
-		string $targetInternalPath,
583
-		bool $isRename,
584
-		bool $keepEncryptionVersion,
585
-	): void {
586
-		$isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath);
587
-		$cacheInformation = [
588
-			'encrypted' => $isEncrypted,
589
-		];
590
-		if ($isEncrypted) {
591
-			$sourceCacheEntry = $sourceStorage->getCache()->get($sourceInternalPath);
592
-			$targetCacheEntry = $this->getCache()->get($targetInternalPath);
593
-
594
-			// Rename of the cache already happened, so we do the cleanup on the target
595
-			if ($sourceCacheEntry === false && $targetCacheEntry !== false) {
596
-				$encryptedVersion = $targetCacheEntry['encryptedVersion'];
597
-				$isRename = false;
598
-			} else {
599
-				$encryptedVersion = $sourceCacheEntry['encryptedVersion'];
600
-			}
601
-
602
-			// In case of a move operation from an unencrypted to an encrypted
603
-			// storage the old encrypted version would stay with "0" while the
604
-			// correct value would be "1". Thus we manually set the value to "1"
605
-			// for those cases.
606
-			// See also https://github.com/owncloud/core/issues/23078
607
-			if ($encryptedVersion === 0 || !$keepEncryptionVersion) {
608
-				$encryptedVersion = 1;
609
-			}
610
-
611
-			$cacheInformation['encryptedVersion'] = $encryptedVersion;
612
-		}
613
-
614
-		// in case of a rename we need to manipulate the source cache because
615
-		// this information will be kept for the new target
616
-		if ($isRename) {
617
-			$sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
618
-		} else {
619
-			$this->getCache()->put($targetInternalPath, $cacheInformation);
620
-		}
621
-	}
622
-
623
-	/**
624
-	 * copy file between two storages
625
-	 * @throws \Exception
626
-	 */
627
-	private function copyBetweenStorage(
628
-		Storage\IStorage $sourceStorage,
629
-		string $sourceInternalPath,
630
-		string $targetInternalPath,
631
-		bool $preserveMtime,
632
-		bool $isRename,
633
-	): bool {
634
-		// for versions we have nothing to do, because versions should always use the
635
-		// key from the original file. Just create a 1:1 copy and done
636
-		if ($this->isVersion($targetInternalPath) ||
637
-			$this->isVersion($sourceInternalPath)) {
638
-			// remember that we try to create a version so that we can detect it during
639
-			// fopen($sourceInternalPath) and by-pass the encryption in order to
640
-			// create a 1:1 copy of the file
641
-			$this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
642
-			$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
643
-			$this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
644
-			if ($result) {
645
-				$info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
646
-				// make sure that we update the unencrypted size for the version
647
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
648
-					$this->updateUnencryptedSize(
649
-						$this->getFullPath($targetInternalPath),
650
-						$info->getUnencryptedSize()
651
-					);
652
-				}
653
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, true);
654
-			}
655
-			return $result;
656
-		}
657
-
658
-		// first copy the keys that we reuse the existing file key on the target location
659
-		// and don't create a new one which would break versions for example.
660
-		if ($sourceStorage->instanceOfStorage(Common::class) && $sourceStorage->getMountOption('mount_point')) {
661
-			$mountPoint = $sourceStorage->getMountOption('mount_point');
662
-			$source = $mountPoint . '/' . $sourceInternalPath;
663
-			$target = $this->getFullPath($targetInternalPath);
664
-			$this->copyKeys($source, $target);
665
-		} else {
666
-			$this->logger->error('Could not find mount point, can\'t keep encryption keys');
667
-		}
668
-
669
-		if ($sourceStorage->is_dir($sourceInternalPath)) {
670
-			$dh = $sourceStorage->opendir($sourceInternalPath);
671
-			if (!$this->is_dir($targetInternalPath)) {
672
-				$result = $this->mkdir($targetInternalPath);
673
-			} else {
674
-				$result = true;
675
-			}
676
-			if (is_resource($dh)) {
677
-				while ($result && ($file = readdir($dh)) !== false) {
678
-					if (!Filesystem::isIgnoredDir($file)) {
679
-						$result = $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, $preserveMtime, $isRename);
680
-					}
681
-				}
682
-			}
683
-		} else {
684
-			try {
685
-				$source = $sourceStorage->fopen($sourceInternalPath, 'r');
686
-				$target = $this->fopen($targetInternalPath, 'w');
687
-				[, $result] = \OC_Helper::streamCopy($source, $target);
688
-			} finally {
689
-				if (is_resource($source)) {
690
-					fclose($source);
691
-				}
692
-				if (is_resource($target)) {
693
-					fclose($target);
694
-				}
695
-			}
696
-			if ($result) {
697
-				if ($preserveMtime) {
698
-					$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
699
-				}
700
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, false);
701
-			} else {
702
-				// delete partially written target file
703
-				$this->unlink($targetInternalPath);
704
-				// delete cache entry that was created by fopen
705
-				$this->getCache()->remove($targetInternalPath);
706
-			}
707
-		}
708
-		return (bool)$result;
709
-	}
710
-
711
-	public function getLocalFile(string $path): string|false {
712
-		if ($this->encryptionManager->isEnabled()) {
713
-			$cachedFile = $this->getCachedFile($path);
714
-			if (is_string($cachedFile)) {
715
-				return $cachedFile;
716
-			}
717
-		}
718
-		return $this->storage->getLocalFile($path);
719
-	}
720
-
721
-	public function isLocal(): bool {
722
-		if ($this->encryptionManager->isEnabled()) {
723
-			return false;
724
-		}
725
-		return $this->storage->isLocal();
726
-	}
727
-
728
-	public function stat(string $path): array|false {
729
-		$stat = $this->storage->stat($path);
730
-		if (!$stat) {
731
-			return false;
732
-		}
733
-		$fileSize = $this->filesize($path);
734
-		$stat['size'] = $fileSize;
735
-		$stat[7] = $fileSize;
736
-		$stat['hasHeader'] = $this->getHeaderSize($path) > 0;
737
-		return $stat;
738
-	}
739
-
740
-	public function hash(string $type, string $path, bool $raw = false): string|false {
741
-		$fh = $this->fopen($path, 'rb');
742
-		$ctx = hash_init($type);
743
-		hash_update_stream($ctx, $fh);
744
-		fclose($fh);
745
-		return hash_final($ctx, $raw);
746
-	}
747
-
748
-	/**
749
-	 * return full path, including mount point
750
-	 *
751
-	 * @param string $path relative to mount point
752
-	 * @return string full path including mount point
753
-	 */
754
-	protected function getFullPath(string $path): string {
755
-		return Filesystem::normalizePath($this->mountPoint . '/' . $path);
756
-	}
757
-
758
-	/**
759
-	 * read first block of encrypted file, typically this will contain the
760
-	 * encryption header
761
-	 */
762
-	protected function readFirstBlock(string $path): string {
763
-		$firstBlock = '';
764
-		if ($this->storage->is_file($path)) {
765
-			$handle = $this->storage->fopen($path, 'r');
766
-			$firstBlock = fread($handle, $this->util->getHeaderSize());
767
-			fclose($handle);
768
-		}
769
-		return $firstBlock;
770
-	}
771
-
772
-	/**
773
-	 * return header size of given file
774
-	 */
775
-	protected function getHeaderSize(string $path): int {
776
-		$headerSize = 0;
777
-		$realFile = $this->util->stripPartialFileExtension($path);
778
-		if ($this->storage->is_file($realFile)) {
779
-			$path = $realFile;
780
-		}
781
-		$firstBlock = $this->readFirstBlock($path);
782
-
783
-		if (str_starts_with($firstBlock, Util::HEADER_START)) {
784
-			$headerSize = $this->util->getHeaderSize();
785
-		}
786
-
787
-		return $headerSize;
788
-	}
789
-
790
-	/**
791
-	 * read header from file
792
-	 */
793
-	protected function getHeader(string $path): array {
794
-		$realFile = $this->util->stripPartialFileExtension($path);
795
-		$exists = $this->storage->is_file($realFile);
796
-		if ($exists) {
797
-			$path = $realFile;
798
-		}
799
-
800
-		$result = [];
801
-
802
-		$isEncrypted = $this->encryptedPaths->get($realFile);
803
-		if (is_null($isEncrypted)) {
804
-			$info = $this->getCache()->get($path);
805
-			$isEncrypted = isset($info['encrypted']) && $info['encrypted'] === true;
806
-		}
807
-
808
-		if ($isEncrypted) {
809
-			$firstBlock = $this->readFirstBlock($path);
810
-			$result = $this->util->parseRawHeader($firstBlock);
811
-
812
-			// if the header doesn't contain a encryption module we check if it is a
813
-			// legacy file. If true, we add the default encryption module
814
-			if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY]) && (!empty($result) || $exists)) {
815
-				$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
816
-			}
817
-		}
818
-
819
-		return $result;
820
-	}
821
-
822
-	/**
823
-	 * read encryption module needed to read/write the file located at $path
824
-	 *
825
-	 * @throws ModuleDoesNotExistsException
826
-	 * @throws \Exception
827
-	 */
828
-	protected function getEncryptionModule(string $path): ?\OCP\Encryption\IEncryptionModule {
829
-		$encryptionModule = null;
830
-		$header = $this->getHeader($path);
831
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
832
-		if (!empty($encryptionModuleId)) {
833
-			try {
834
-				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
835
-			} catch (ModuleDoesNotExistsException $e) {
836
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
837
-				throw $e;
838
-			}
839
-		}
840
-
841
-		return $encryptionModule;
842
-	}
843
-
844
-	public function updateUnencryptedSize(string $path, int|float $unencryptedSize): void {
845
-		$this->unencryptedSize[$path] = $unencryptedSize;
846
-	}
847
-
848
-	/**
849
-	 * copy keys to new location
850
-	 *
851
-	 * @param string $source path relative to data/
852
-	 * @param string $target path relative to data/
853
-	 */
854
-	protected function copyKeys(string $source, string $target): bool {
855
-		if (!$this->util->isExcluded($source)) {
856
-			return $this->keyStorage->copyKeys($source, $target);
857
-		}
858
-
859
-		return false;
860
-	}
861
-
862
-	/**
863
-	 * check if path points to a files version
864
-	 */
865
-	protected function isVersion(string $path): bool {
866
-		$normalized = Filesystem::normalizePath($path);
867
-		return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
868
-	}
869
-
870
-	/**
871
-	 * check if the given storage should be encrypted or not
872
-	 */
873
-	protected function shouldEncrypt(string $path): bool {
874
-		$fullPath = $this->getFullPath($path);
875
-		$mountPointConfig = $this->mount->getOption('encrypt', true);
876
-		if ($mountPointConfig === false) {
877
-			return false;
878
-		}
879
-
880
-		try {
881
-			$encryptionModule = $this->getEncryptionModule($fullPath);
882
-		} catch (ModuleDoesNotExistsException $e) {
883
-			return false;
884
-		}
885
-
886
-		if ($encryptionModule === null) {
887
-			$encryptionModule = $this->encryptionManager->getEncryptionModule();
888
-		}
889
-
890
-		return $encryptionModule->shouldEncrypt($fullPath);
891
-	}
892
-
893
-	public function writeStream(string $path, $stream, ?int $size = null): int {
894
-		// always fall back to fopen
895
-		$target = $this->fopen($path, 'w');
896
-		[$count, $result] = \OC_Helper::streamCopy($stream, $target);
897
-		fclose($stream);
898
-		fclose($target);
899
-
900
-		// object store, stores the size after write and doesn't update this during scan
901
-		// manually store the unencrypted size
902
-		if ($result && $this->getWrapperStorage()->instanceOfStorage(ObjectStoreStorage::class) && $this->shouldEncrypt($path)) {
903
-			$this->getCache()->put($path, ['unencrypted_size' => $count]);
904
-		}
905
-
906
-		return $count;
907
-	}
908
-
909
-	public function clearIsEncryptedCache(): void {
910
-		$this->encryptedPaths->clear();
911
-	}
912
-
913
-	/**
914
-	 * Allow temporarily disabling the wrapper
915
-	 */
916
-	public function setEnabled(bool $enabled): void {
917
-		$this->enabled = $enabled;
918
-	}
919
-
920
-	/**
921
-	 * Check if the on-disk data for a file has a valid encrypted header
922
-	 *
923
-	 * @param string $path
924
-	 * @return bool
925
-	 */
926
-	public function hasValidHeader(string $path): bool {
927
-		$firstBlock = $this->readFirstBlock($path);
928
-		$header = $this->util->parseRawHeader($firstBlock);
929
-		return (count($header) > 0);
930
-	}
30
+    use LocalTempFileTrait;
31
+
32
+    private string $mountPoint;
33
+    protected array $unencryptedSize = [];
34
+    private IMountPoint $mount;
35
+    /** for which path we execute the repair step to avoid recursions */
36
+    private array $fixUnencryptedSizeOf = [];
37
+    /** @var CappedMemoryCache<bool> */
38
+    private CappedMemoryCache $encryptedPaths;
39
+    private bool $enabled = true;
40
+
41
+    /**
42
+     * @param array $parameters
43
+     */
44
+    public function __construct(
45
+        array $parameters,
46
+        private IManager $encryptionManager,
47
+        private Util $util,
48
+        private LoggerInterface $logger,
49
+        private IFile $fileHelper,
50
+        private ?string $uid,
51
+        private IStorage $keyStorage,
52
+        private Manager $mountManager,
53
+        private ArrayCache $arrayCache,
54
+    ) {
55
+        $this->mountPoint = $parameters['mountPoint'];
56
+        $this->mount = $parameters['mount'];
57
+        $this->encryptedPaths = new CappedMemoryCache();
58
+        parent::__construct($parameters);
59
+    }
60
+
61
+    public function filesize(string $path): int|float|false {
62
+        $fullPath = $this->getFullPath($path);
63
+
64
+        $info = $this->getCache()->get($path);
65
+        if ($info === false) {
66
+            /* Pass call to wrapped storage, it may be a special file like a part file */
67
+            return $this->storage->filesize($path);
68
+        }
69
+        if (isset($this->unencryptedSize[$fullPath])) {
70
+            $size = $this->unencryptedSize[$fullPath];
71
+
72
+            // Update file cache (only if file is already cached).
73
+            // Certain files are not cached (e.g. *.part).
74
+            if (isset($info['fileid'])) {
75
+                if ($info instanceof ICacheEntry) {
76
+                    $info['encrypted'] = $info['encryptedVersion'];
77
+                } else {
78
+                    /**
79
+                     * @psalm-suppress RedundantCondition
80
+                     */
81
+                    if (!is_array($info)) {
82
+                        $info = [];
83
+                    }
84
+                    $info['encrypted'] = true;
85
+                    $info = new CacheEntry($info);
86
+                }
87
+
88
+                if ($size !== $info->getUnencryptedSize()) {
89
+                    $this->getCache()->update($info->getId(), [
90
+                        'unencrypted_size' => $size
91
+                    ]);
92
+                }
93
+            }
94
+
95
+            return $size;
96
+        }
97
+
98
+        if (isset($info['fileid']) && $info['encrypted']) {
99
+            return $this->verifyUnencryptedSize($path, $info->getUnencryptedSize());
100
+        }
101
+
102
+        return $this->storage->filesize($path);
103
+    }
104
+
105
+    private function modifyMetaData(string $path, array $data): array {
106
+        $fullPath = $this->getFullPath($path);
107
+        $info = $this->getCache()->get($path);
108
+
109
+        if (isset($this->unencryptedSize[$fullPath])) {
110
+            $data['encrypted'] = true;
111
+            $data['size'] = $this->unencryptedSize[$fullPath];
112
+            $data['unencrypted_size'] = $data['size'];
113
+        } else {
114
+            if (isset($info['fileid']) && $info['encrypted']) {
115
+                $data['size'] = $this->verifyUnencryptedSize($path, $info->getUnencryptedSize());
116
+                $data['encrypted'] = true;
117
+                $data['unencrypted_size'] = $data['size'];
118
+            }
119
+        }
120
+
121
+        if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
122
+            $data['encryptedVersion'] = $info['encryptedVersion'];
123
+        }
124
+
125
+        return $data;
126
+    }
127
+
128
+    public function getMetaData(string $path): ?array {
129
+        $data = $this->storage->getMetaData($path);
130
+        if (is_null($data)) {
131
+            return null;
132
+        }
133
+        return $this->modifyMetaData($path, $data);
134
+    }
135
+
136
+    public function getDirectoryContent(string $directory): \Traversable {
137
+        $parent = rtrim($directory, '/');
138
+        foreach ($this->getWrapperStorage()->getDirectoryContent($directory) as $data) {
139
+            yield $this->modifyMetaData($parent . '/' . $data['name'], $data);
140
+        }
141
+    }
142
+
143
+    public function file_get_contents(string $path): string|false {
144
+        $encryptionModule = $this->getEncryptionModule($path);
145
+
146
+        if ($encryptionModule) {
147
+            $handle = $this->fopen($path, 'r');
148
+            if (!$handle) {
149
+                return false;
150
+            }
151
+            $data = stream_get_contents($handle);
152
+            fclose($handle);
153
+            return $data;
154
+        }
155
+        return $this->storage->file_get_contents($path);
156
+    }
157
+
158
+    public function file_put_contents(string $path, mixed $data): int|float|false {
159
+        // file put content will always be translated to a stream write
160
+        $handle = $this->fopen($path, 'w');
161
+        if (is_resource($handle)) {
162
+            $written = fwrite($handle, $data);
163
+            fclose($handle);
164
+            return $written;
165
+        }
166
+
167
+        return false;
168
+    }
169
+
170
+    public function unlink(string $path): bool {
171
+        $fullPath = $this->getFullPath($path);
172
+        if ($this->util->isExcluded($fullPath)) {
173
+            return $this->storage->unlink($path);
174
+        }
175
+
176
+        $encryptionModule = $this->getEncryptionModule($path);
177
+        if ($encryptionModule) {
178
+            $this->keyStorage->deleteAllFileKeys($fullPath);
179
+        }
180
+
181
+        return $this->storage->unlink($path);
182
+    }
183
+
184
+    public function rename(string $source, string $target): bool {
185
+        $result = $this->storage->rename($source, $target);
186
+
187
+        if ($result &&
188
+            // versions always use the keys from the original file, so we can skip
189
+            // this step for versions
190
+            $this->isVersion($target) === false &&
191
+            $this->encryptionManager->isEnabled()) {
192
+            $sourcePath = $this->getFullPath($source);
193
+            if (!$this->util->isExcluded($sourcePath)) {
194
+                $targetPath = $this->getFullPath($target);
195
+                if (isset($this->unencryptedSize[$sourcePath])) {
196
+                    $this->unencryptedSize[$targetPath] = $this->unencryptedSize[$sourcePath];
197
+                }
198
+                $this->keyStorage->renameKeys($sourcePath, $targetPath);
199
+                $module = $this->getEncryptionModule($target);
200
+                if ($module) {
201
+                    $module->update($targetPath, $this->uid, []);
202
+                }
203
+            }
204
+        }
205
+
206
+        return $result;
207
+    }
208
+
209
+    public function rmdir(string $path): bool {
210
+        $result = $this->storage->rmdir($path);
211
+        $fullPath = $this->getFullPath($path);
212
+        if ($result &&
213
+            $this->util->isExcluded($fullPath) === false &&
214
+            $this->encryptionManager->isEnabled()
215
+        ) {
216
+            $this->keyStorage->deleteAllFileKeys($fullPath);
217
+        }
218
+
219
+        return $result;
220
+    }
221
+
222
+    public function isReadable(string $path): bool {
223
+        $isReadable = true;
224
+
225
+        $metaData = $this->getMetaData($path);
226
+        if (
227
+            !$this->is_dir($path) &&
228
+            isset($metaData['encrypted']) &&
229
+            $metaData['encrypted'] === true
230
+        ) {
231
+            $fullPath = $this->getFullPath($path);
232
+            $module = $this->getEncryptionModule($path);
233
+            $isReadable = $module->isReadable($fullPath, $this->uid);
234
+        }
235
+
236
+        return $this->storage->isReadable($path) && $isReadable;
237
+    }
238
+
239
+    public function copy(string $source, string $target): bool {
240
+        $sourcePath = $this->getFullPath($source);
241
+
242
+        if ($this->util->isExcluded($sourcePath)) {
243
+            return $this->storage->copy($source, $target);
244
+        }
245
+
246
+        // need to stream copy file by file in case we copy between a encrypted
247
+        // and a unencrypted storage
248
+        $this->unlink($target);
249
+        return $this->copyFromStorage($this, $source, $target);
250
+    }
251
+
252
+    public function fopen(string $path, string $mode) {
253
+        // check if the file is stored in the array cache, this means that we
254
+        // copy a file over to the versions folder, in this case we don't want to
255
+        // decrypt it
256
+        if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
257
+            $this->arrayCache->remove('encryption_copy_version_' . $path);
258
+            return $this->storage->fopen($path, $mode);
259
+        }
260
+
261
+        if (!$this->enabled) {
262
+            return $this->storage->fopen($path, $mode);
263
+        }
264
+
265
+        $encryptionEnabled = $this->encryptionManager->isEnabled();
266
+        $shouldEncrypt = false;
267
+        $encryptionModule = null;
268
+        $header = $this->getHeader($path);
269
+        $signed = isset($header['signed']) && $header['signed'] === 'true';
270
+        $fullPath = $this->getFullPath($path);
271
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
272
+
273
+        if ($this->util->isExcluded($fullPath) === false) {
274
+            $size = $unencryptedSize = 0;
275
+            $realFile = $this->util->stripPartialFileExtension($path);
276
+            $targetExists = $this->is_file($realFile) || $this->file_exists($path);
277
+            $targetIsEncrypted = false;
278
+            if ($targetExists) {
279
+                // in case the file exists we require the explicit module as
280
+                // specified in the file header - otherwise we need to fail hard to
281
+                // prevent data loss on client side
282
+                if (!empty($encryptionModuleId)) {
283
+                    $targetIsEncrypted = true;
284
+                    $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
285
+                }
286
+
287
+                if ($this->file_exists($path)) {
288
+                    $size = $this->storage->filesize($path);
289
+                    $unencryptedSize = $this->filesize($path);
290
+                } else {
291
+                    $size = $unencryptedSize = 0;
292
+                }
293
+            }
294
+
295
+            try {
296
+                if (
297
+                    $mode === 'w'
298
+                    || $mode === 'w+'
299
+                    || $mode === 'wb'
300
+                    || $mode === 'wb+'
301
+                ) {
302
+                    // if we update a encrypted file with a un-encrypted one we change the db flag
303
+                    if ($targetIsEncrypted && $encryptionEnabled === false) {
304
+                        $cache = $this->storage->getCache();
305
+                        $entry = $cache->get($path);
306
+                        $cache->update($entry->getId(), ['encrypted' => 0]);
307
+                    }
308
+                    if ($encryptionEnabled) {
309
+                        // if $encryptionModuleId is empty, the default module will be used
310
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
311
+                        $shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
312
+                        $signed = true;
313
+                    }
314
+                } else {
315
+                    $info = $this->getCache()->get($path);
316
+                    // only get encryption module if we found one in the header
317
+                    // or if file should be encrypted according to the file cache
318
+                    if (!empty($encryptionModuleId)) {
319
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
320
+                        $shouldEncrypt = true;
321
+                    } elseif ($info !== false && $info['encrypted'] === true) {
322
+                        // we come from a old installation. No header and/or no module defined
323
+                        // but the file is encrypted. In this case we need to use the
324
+                        // OC_DEFAULT_MODULE to read the file
325
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
326
+                        $shouldEncrypt = true;
327
+                        $targetIsEncrypted = true;
328
+                    }
329
+                }
330
+            } catch (ModuleDoesNotExistsException $e) {
331
+                $this->logger->warning('Encryption module "' . $encryptionModuleId . '" not found, file will be stored unencrypted', [
332
+                    'exception' => $e,
333
+                    'app' => 'core',
334
+                ]);
335
+            }
336
+
337
+            // encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
338
+            if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
339
+                if (!$targetExists || !$targetIsEncrypted) {
340
+                    $shouldEncrypt = false;
341
+                }
342
+            }
343
+
344
+            if ($shouldEncrypt === true && $encryptionModule !== null) {
345
+                $this->encryptedPaths->set($this->util->stripPartialFileExtension($path), true);
346
+                $headerSize = $this->getHeaderSize($path);
347
+                if ($mode === 'r' && $headerSize === 0) {
348
+                    $firstBlock = $this->readFirstBlock($path);
349
+                    if (!$firstBlock) {
350
+                        throw new InvalidHeaderException("Unable to get header block for $path");
351
+                    } elseif (!str_starts_with($firstBlock, Util::HEADER_START)) {
352
+                        throw new InvalidHeaderException("Unable to get header size for $path, file doesn't start with encryption header");
353
+                    } else {
354
+                        throw new InvalidHeaderException("Unable to get header size for $path, even though file does start with encryption header");
355
+                    }
356
+                }
357
+                $source = $this->storage->fopen($path, $mode);
358
+                if (!is_resource($source)) {
359
+                    return false;
360
+                }
361
+                $handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
362
+                    $this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
363
+                    $size, $unencryptedSize, $headerSize, $signed);
364
+
365
+                return $handle;
366
+            }
367
+        }
368
+
369
+        return $this->storage->fopen($path, $mode);
370
+    }
371
+
372
+
373
+    /**
374
+     * perform some plausibility checks if the unencrypted size is correct.
375
+     * If not, we calculate the correct unencrypted size and return it
376
+     *
377
+     * @param string $path internal path relative to the storage root
378
+     * @param int $unencryptedSize size of the unencrypted file
379
+     *
380
+     * @return int unencrypted size
381
+     */
382
+    protected function verifyUnencryptedSize(string $path, int $unencryptedSize): int {
383
+        $size = $this->storage->filesize($path);
384
+        $result = $unencryptedSize;
385
+
386
+        if ($unencryptedSize < 0 ||
387
+            ($size > 0 && $unencryptedSize === $size) ||
388
+            $unencryptedSize > $size
389
+        ) {
390
+            // check if we already calculate the unencrypted size for the
391
+            // given path to avoid recursions
392
+            if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
393
+                $this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
394
+                try {
395
+                    $result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
396
+                } catch (\Exception $e) {
397
+                    $this->logger->error('Couldn\'t re-calculate unencrypted size for ' . $path, ['exception' => $e]);
398
+                }
399
+                unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
400
+            }
401
+        }
402
+
403
+        return $result;
404
+    }
405
+
406
+    /**
407
+     * calculate the unencrypted size
408
+     *
409
+     * @param string $path internal path relative to the storage root
410
+     * @param int $size size of the physical file
411
+     * @param int $unencryptedSize size of the unencrypted file
412
+     */
413
+    protected function fixUnencryptedSize(string $path, int $size, int $unencryptedSize): int|float {
414
+        $headerSize = $this->getHeaderSize($path);
415
+        $header = $this->getHeader($path);
416
+        $encryptionModule = $this->getEncryptionModule($path);
417
+
418
+        $stream = $this->storage->fopen($path, 'r');
419
+
420
+        // if we couldn't open the file we return the old unencrypted size
421
+        if (!is_resource($stream)) {
422
+            $this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
423
+            return $unencryptedSize;
424
+        }
425
+
426
+        $newUnencryptedSize = 0;
427
+        $size -= $headerSize;
428
+        $blockSize = $this->util->getBlockSize();
429
+
430
+        // if a header exists we skip it
431
+        if ($headerSize > 0) {
432
+            $this->fread_block($stream, $headerSize);
433
+        }
434
+
435
+        // fast path, else the calculation for $lastChunkNr is bogus
436
+        if ($size === 0) {
437
+            return 0;
438
+        }
439
+
440
+        $signed = isset($header['signed']) && $header['signed'] === 'true';
441
+        $unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
442
+
443
+        // calculate last chunk nr
444
+        // next highest is end of chunks, one subtracted is last one
445
+        // we have to read the last chunk, we can't just calculate it (because of padding etc)
446
+
447
+        $lastChunkNr = ceil($size / $blockSize) - 1;
448
+        // calculate last chunk position
449
+        $lastChunkPos = ($lastChunkNr * $blockSize);
450
+        // try to fseek to the last chunk, if it fails we have to read the whole file
451
+        if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
452
+            $newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
453
+        }
454
+
455
+        $lastChunkContentEncrypted = '';
456
+        $count = $blockSize;
457
+
458
+        while ($count > 0) {
459
+            $data = $this->fread_block($stream, $blockSize);
460
+            $count = strlen($data);
461
+            $lastChunkContentEncrypted .= $data;
462
+            if (strlen($lastChunkContentEncrypted) > $blockSize) {
463
+                $newUnencryptedSize += $unencryptedBlockSize;
464
+                $lastChunkContentEncrypted = substr($lastChunkContentEncrypted, $blockSize);
465
+            }
466
+        }
467
+
468
+        fclose($stream);
469
+
470
+        // we have to decrypt the last chunk to get it actual size
471
+        $encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
472
+        $decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
473
+        $decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
474
+
475
+        // calc the real file size with the size of the last chunk
476
+        $newUnencryptedSize += strlen($decryptedLastChunk);
477
+
478
+        $this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
479
+
480
+        // write to cache if applicable
481
+        $cache = $this->storage->getCache();
482
+        $entry = $cache->get($path);
483
+        $cache->update($entry['fileid'], [
484
+            'unencrypted_size' => $newUnencryptedSize
485
+        ]);
486
+
487
+        return $newUnencryptedSize;
488
+    }
489
+
490
+    /**
491
+     * fread_block
492
+     *
493
+     * This function is a wrapper around the fread function.  It is based on the
494
+     * stream_read_block function from lib/private/Files/Streams/Encryption.php
495
+     * It calls stream read until the requested $blockSize was received or no remaining data is present.
496
+     * This is required as stream_read only returns smaller chunks of data when the stream fetches from a
497
+     * remote storage over the internet and it does not care about the given $blockSize.
498
+     *
499
+     * @param resource $handle the stream to read from
500
+     * @param int $blockSize Length of requested data block in bytes
501
+     * @return string Data fetched from stream.
502
+     */
503
+    private function fread_block($handle, int $blockSize): string {
504
+        $remaining = $blockSize;
505
+        $data = '';
506
+
507
+        do {
508
+            $chunk = fread($handle, $remaining);
509
+            $chunk_len = strlen($chunk);
510
+            $data .= $chunk;
511
+            $remaining -= $chunk_len;
512
+        } while (($remaining > 0) && ($chunk_len > 0));
513
+
514
+        return $data;
515
+    }
516
+
517
+    public function moveFromStorage(
518
+        Storage\IStorage $sourceStorage,
519
+        string $sourceInternalPath,
520
+        string $targetInternalPath,
521
+        $preserveMtime = true,
522
+    ): bool {
523
+        if ($sourceStorage === $this) {
524
+            return $this->rename($sourceInternalPath, $targetInternalPath);
525
+        }
526
+
527
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
528
+        // - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
529
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
530
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
531
+        // - remove $this->copyBetweenStorage
532
+
533
+        if (!$sourceStorage->isDeletable($sourceInternalPath)) {
534
+            return false;
535
+        }
536
+
537
+        $result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
538
+        if ($result) {
539
+            $setPreserveCacheOnDelete = $sourceStorage->instanceOfStorage(ObjectStoreStorage::class) && !$this->instanceOfStorage(ObjectStoreStorage::class);
540
+            if ($setPreserveCacheOnDelete) {
541
+                /** @var ObjectStoreStorage $sourceStorage */
542
+                $sourceStorage->setPreserveCacheOnDelete(true);
543
+            }
544
+            try {
545
+                if ($sourceStorage->is_dir($sourceInternalPath)) {
546
+                    $result = $sourceStorage->rmdir($sourceInternalPath);
547
+                } else {
548
+                    $result = $sourceStorage->unlink($sourceInternalPath);
549
+                }
550
+            } finally {
551
+                if ($setPreserveCacheOnDelete) {
552
+                    /** @var ObjectStoreStorage $sourceStorage */
553
+                    $sourceStorage->setPreserveCacheOnDelete(false);
554
+                }
555
+            }
556
+        }
557
+        return $result;
558
+    }
559
+
560
+    public function copyFromStorage(
561
+        Storage\IStorage $sourceStorage,
562
+        string $sourceInternalPath,
563
+        string $targetInternalPath,
564
+        $preserveMtime = false,
565
+        $isRename = false,
566
+    ): bool {
567
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
568
+        // - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
569
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
570
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
571
+        // - remove $this->copyBetweenStorage
572
+
573
+        return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
574
+    }
575
+
576
+    /**
577
+     * Update the encrypted cache version in the database
578
+     */
579
+    private function updateEncryptedVersion(
580
+        Storage\IStorage $sourceStorage,
581
+        string $sourceInternalPath,
582
+        string $targetInternalPath,
583
+        bool $isRename,
584
+        bool $keepEncryptionVersion,
585
+    ): void {
586
+        $isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath);
587
+        $cacheInformation = [
588
+            'encrypted' => $isEncrypted,
589
+        ];
590
+        if ($isEncrypted) {
591
+            $sourceCacheEntry = $sourceStorage->getCache()->get($sourceInternalPath);
592
+            $targetCacheEntry = $this->getCache()->get($targetInternalPath);
593
+
594
+            // Rename of the cache already happened, so we do the cleanup on the target
595
+            if ($sourceCacheEntry === false && $targetCacheEntry !== false) {
596
+                $encryptedVersion = $targetCacheEntry['encryptedVersion'];
597
+                $isRename = false;
598
+            } else {
599
+                $encryptedVersion = $sourceCacheEntry['encryptedVersion'];
600
+            }
601
+
602
+            // In case of a move operation from an unencrypted to an encrypted
603
+            // storage the old encrypted version would stay with "0" while the
604
+            // correct value would be "1". Thus we manually set the value to "1"
605
+            // for those cases.
606
+            // See also https://github.com/owncloud/core/issues/23078
607
+            if ($encryptedVersion === 0 || !$keepEncryptionVersion) {
608
+                $encryptedVersion = 1;
609
+            }
610
+
611
+            $cacheInformation['encryptedVersion'] = $encryptedVersion;
612
+        }
613
+
614
+        // in case of a rename we need to manipulate the source cache because
615
+        // this information will be kept for the new target
616
+        if ($isRename) {
617
+            $sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
618
+        } else {
619
+            $this->getCache()->put($targetInternalPath, $cacheInformation);
620
+        }
621
+    }
622
+
623
+    /**
624
+     * copy file between two storages
625
+     * @throws \Exception
626
+     */
627
+    private function copyBetweenStorage(
628
+        Storage\IStorage $sourceStorage,
629
+        string $sourceInternalPath,
630
+        string $targetInternalPath,
631
+        bool $preserveMtime,
632
+        bool $isRename,
633
+    ): bool {
634
+        // for versions we have nothing to do, because versions should always use the
635
+        // key from the original file. Just create a 1:1 copy and done
636
+        if ($this->isVersion($targetInternalPath) ||
637
+            $this->isVersion($sourceInternalPath)) {
638
+            // remember that we try to create a version so that we can detect it during
639
+            // fopen($sourceInternalPath) and by-pass the encryption in order to
640
+            // create a 1:1 copy of the file
641
+            $this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
642
+            $result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
643
+            $this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
644
+            if ($result) {
645
+                $info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
646
+                // make sure that we update the unencrypted size for the version
647
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
648
+                    $this->updateUnencryptedSize(
649
+                        $this->getFullPath($targetInternalPath),
650
+                        $info->getUnencryptedSize()
651
+                    );
652
+                }
653
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, true);
654
+            }
655
+            return $result;
656
+        }
657
+
658
+        // first copy the keys that we reuse the existing file key on the target location
659
+        // and don't create a new one which would break versions for example.
660
+        if ($sourceStorage->instanceOfStorage(Common::class) && $sourceStorage->getMountOption('mount_point')) {
661
+            $mountPoint = $sourceStorage->getMountOption('mount_point');
662
+            $source = $mountPoint . '/' . $sourceInternalPath;
663
+            $target = $this->getFullPath($targetInternalPath);
664
+            $this->copyKeys($source, $target);
665
+        } else {
666
+            $this->logger->error('Could not find mount point, can\'t keep encryption keys');
667
+        }
668
+
669
+        if ($sourceStorage->is_dir($sourceInternalPath)) {
670
+            $dh = $sourceStorage->opendir($sourceInternalPath);
671
+            if (!$this->is_dir($targetInternalPath)) {
672
+                $result = $this->mkdir($targetInternalPath);
673
+            } else {
674
+                $result = true;
675
+            }
676
+            if (is_resource($dh)) {
677
+                while ($result && ($file = readdir($dh)) !== false) {
678
+                    if (!Filesystem::isIgnoredDir($file)) {
679
+                        $result = $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, $preserveMtime, $isRename);
680
+                    }
681
+                }
682
+            }
683
+        } else {
684
+            try {
685
+                $source = $sourceStorage->fopen($sourceInternalPath, 'r');
686
+                $target = $this->fopen($targetInternalPath, 'w');
687
+                [, $result] = \OC_Helper::streamCopy($source, $target);
688
+            } finally {
689
+                if (is_resource($source)) {
690
+                    fclose($source);
691
+                }
692
+                if (is_resource($target)) {
693
+                    fclose($target);
694
+                }
695
+            }
696
+            if ($result) {
697
+                if ($preserveMtime) {
698
+                    $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
699
+                }
700
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, false);
701
+            } else {
702
+                // delete partially written target file
703
+                $this->unlink($targetInternalPath);
704
+                // delete cache entry that was created by fopen
705
+                $this->getCache()->remove($targetInternalPath);
706
+            }
707
+        }
708
+        return (bool)$result;
709
+    }
710
+
711
+    public function getLocalFile(string $path): string|false {
712
+        if ($this->encryptionManager->isEnabled()) {
713
+            $cachedFile = $this->getCachedFile($path);
714
+            if (is_string($cachedFile)) {
715
+                return $cachedFile;
716
+            }
717
+        }
718
+        return $this->storage->getLocalFile($path);
719
+    }
720
+
721
+    public function isLocal(): bool {
722
+        if ($this->encryptionManager->isEnabled()) {
723
+            return false;
724
+        }
725
+        return $this->storage->isLocal();
726
+    }
727
+
728
+    public function stat(string $path): array|false {
729
+        $stat = $this->storage->stat($path);
730
+        if (!$stat) {
731
+            return false;
732
+        }
733
+        $fileSize = $this->filesize($path);
734
+        $stat['size'] = $fileSize;
735
+        $stat[7] = $fileSize;
736
+        $stat['hasHeader'] = $this->getHeaderSize($path) > 0;
737
+        return $stat;
738
+    }
739
+
740
+    public function hash(string $type, string $path, bool $raw = false): string|false {
741
+        $fh = $this->fopen($path, 'rb');
742
+        $ctx = hash_init($type);
743
+        hash_update_stream($ctx, $fh);
744
+        fclose($fh);
745
+        return hash_final($ctx, $raw);
746
+    }
747
+
748
+    /**
749
+     * return full path, including mount point
750
+     *
751
+     * @param string $path relative to mount point
752
+     * @return string full path including mount point
753
+     */
754
+    protected function getFullPath(string $path): string {
755
+        return Filesystem::normalizePath($this->mountPoint . '/' . $path);
756
+    }
757
+
758
+    /**
759
+     * read first block of encrypted file, typically this will contain the
760
+     * encryption header
761
+     */
762
+    protected function readFirstBlock(string $path): string {
763
+        $firstBlock = '';
764
+        if ($this->storage->is_file($path)) {
765
+            $handle = $this->storage->fopen($path, 'r');
766
+            $firstBlock = fread($handle, $this->util->getHeaderSize());
767
+            fclose($handle);
768
+        }
769
+        return $firstBlock;
770
+    }
771
+
772
+    /**
773
+     * return header size of given file
774
+     */
775
+    protected function getHeaderSize(string $path): int {
776
+        $headerSize = 0;
777
+        $realFile = $this->util->stripPartialFileExtension($path);
778
+        if ($this->storage->is_file($realFile)) {
779
+            $path = $realFile;
780
+        }
781
+        $firstBlock = $this->readFirstBlock($path);
782
+
783
+        if (str_starts_with($firstBlock, Util::HEADER_START)) {
784
+            $headerSize = $this->util->getHeaderSize();
785
+        }
786
+
787
+        return $headerSize;
788
+    }
789
+
790
+    /**
791
+     * read header from file
792
+     */
793
+    protected function getHeader(string $path): array {
794
+        $realFile = $this->util->stripPartialFileExtension($path);
795
+        $exists = $this->storage->is_file($realFile);
796
+        if ($exists) {
797
+            $path = $realFile;
798
+        }
799
+
800
+        $result = [];
801
+
802
+        $isEncrypted = $this->encryptedPaths->get($realFile);
803
+        if (is_null($isEncrypted)) {
804
+            $info = $this->getCache()->get($path);
805
+            $isEncrypted = isset($info['encrypted']) && $info['encrypted'] === true;
806
+        }
807
+
808
+        if ($isEncrypted) {
809
+            $firstBlock = $this->readFirstBlock($path);
810
+            $result = $this->util->parseRawHeader($firstBlock);
811
+
812
+            // if the header doesn't contain a encryption module we check if it is a
813
+            // legacy file. If true, we add the default encryption module
814
+            if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY]) && (!empty($result) || $exists)) {
815
+                $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
816
+            }
817
+        }
818
+
819
+        return $result;
820
+    }
821
+
822
+    /**
823
+     * read encryption module needed to read/write the file located at $path
824
+     *
825
+     * @throws ModuleDoesNotExistsException
826
+     * @throws \Exception
827
+     */
828
+    protected function getEncryptionModule(string $path): ?\OCP\Encryption\IEncryptionModule {
829
+        $encryptionModule = null;
830
+        $header = $this->getHeader($path);
831
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
832
+        if (!empty($encryptionModuleId)) {
833
+            try {
834
+                $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
835
+            } catch (ModuleDoesNotExistsException $e) {
836
+                $this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
837
+                throw $e;
838
+            }
839
+        }
840
+
841
+        return $encryptionModule;
842
+    }
843
+
844
+    public function updateUnencryptedSize(string $path, int|float $unencryptedSize): void {
845
+        $this->unencryptedSize[$path] = $unencryptedSize;
846
+    }
847
+
848
+    /**
849
+     * copy keys to new location
850
+     *
851
+     * @param string $source path relative to data/
852
+     * @param string $target path relative to data/
853
+     */
854
+    protected function copyKeys(string $source, string $target): bool {
855
+        if (!$this->util->isExcluded($source)) {
856
+            return $this->keyStorage->copyKeys($source, $target);
857
+        }
858
+
859
+        return false;
860
+    }
861
+
862
+    /**
863
+     * check if path points to a files version
864
+     */
865
+    protected function isVersion(string $path): bool {
866
+        $normalized = Filesystem::normalizePath($path);
867
+        return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
868
+    }
869
+
870
+    /**
871
+     * check if the given storage should be encrypted or not
872
+     */
873
+    protected function shouldEncrypt(string $path): bool {
874
+        $fullPath = $this->getFullPath($path);
875
+        $mountPointConfig = $this->mount->getOption('encrypt', true);
876
+        if ($mountPointConfig === false) {
877
+            return false;
878
+        }
879
+
880
+        try {
881
+            $encryptionModule = $this->getEncryptionModule($fullPath);
882
+        } catch (ModuleDoesNotExistsException $e) {
883
+            return false;
884
+        }
885
+
886
+        if ($encryptionModule === null) {
887
+            $encryptionModule = $this->encryptionManager->getEncryptionModule();
888
+        }
889
+
890
+        return $encryptionModule->shouldEncrypt($fullPath);
891
+    }
892
+
893
+    public function writeStream(string $path, $stream, ?int $size = null): int {
894
+        // always fall back to fopen
895
+        $target = $this->fopen($path, 'w');
896
+        [$count, $result] = \OC_Helper::streamCopy($stream, $target);
897
+        fclose($stream);
898
+        fclose($target);
899
+
900
+        // object store, stores the size after write and doesn't update this during scan
901
+        // manually store the unencrypted size
902
+        if ($result && $this->getWrapperStorage()->instanceOfStorage(ObjectStoreStorage::class) && $this->shouldEncrypt($path)) {
903
+            $this->getCache()->put($path, ['unencrypted_size' => $count]);
904
+        }
905
+
906
+        return $count;
907
+    }
908
+
909
+    public function clearIsEncryptedCache(): void {
910
+        $this->encryptedPaths->clear();
911
+    }
912
+
913
+    /**
914
+     * Allow temporarily disabling the wrapper
915
+     */
916
+    public function setEnabled(bool $enabled): void {
917
+        $this->enabled = $enabled;
918
+    }
919
+
920
+    /**
921
+     * Check if the on-disk data for a file has a valid encrypted header
922
+     *
923
+     * @param string $path
924
+     * @return bool
925
+     */
926
+    public function hasValidHeader(string $path): bool {
927
+        $firstBlock = $this->readFirstBlock($path);
928
+        $header = $this->util->parseRawHeader($firstBlock);
929
+        return (count($header) > 0);
930
+    }
931 931
 }
Please login to merge, or discard this patch.
lib/base.php 1 patch
Indentation   +1146 added lines, -1146 removed lines patch added patch discarded remove patch
@@ -39,1152 +39,1152 @@
 block discarded – undo
39 39
  * OC_autoload!
40 40
  */
41 41
 class OC {
42
-	/**
43
-	 * Associative array for autoloading. classname => filename
44
-	 */
45
-	public static array $CLASSPATH = [];
46
-	/**
47
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
48
-	 */
49
-	public static string $SERVERROOT = '';
50
-	/**
51
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
52
-	 */
53
-	private static string $SUBURI = '';
54
-	/**
55
-	 * the Nextcloud root path for http requests (e.g. /nextcloud)
56
-	 */
57
-	public static string $WEBROOT = '';
58
-	/**
59
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
60
-	 * web path in 'url'
61
-	 */
62
-	public static array $APPSROOTS = [];
63
-
64
-	public static string $configDir;
65
-
66
-	/**
67
-	 * requested app
68
-	 */
69
-	public static string $REQUESTEDAPP = '';
70
-
71
-	/**
72
-	 * check if Nextcloud runs in cli mode
73
-	 */
74
-	public static bool $CLI = false;
75
-
76
-	public static \OC\Autoloader $loader;
77
-
78
-	public static \Composer\Autoload\ClassLoader $composerAutoloader;
79
-
80
-	public static \OC\Server $server;
81
-
82
-	private static \OC\Config $config;
83
-
84
-	/**
85
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
86
-	 *                           the app path list is empty or contains an invalid path
87
-	 */
88
-	public static function initPaths(): void {
89
-		if (defined('PHPUNIT_CONFIG_DIR')) {
90
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
91
-		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
92
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
93
-		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
94
-			self::$configDir = rtrim($dir, '/') . '/';
95
-		} else {
96
-			self::$configDir = OC::$SERVERROOT . '/config/';
97
-		}
98
-		self::$config = new \OC\Config(self::$configDir);
99
-
100
-		OC::$SUBURI = str_replace('\\', '/', substr(realpath($_SERVER['SCRIPT_FILENAME'] ?? ''), strlen(OC::$SERVERROOT)));
101
-		/**
102
-		 * FIXME: The following lines are required because we can't yet instantiate
103
-		 *        Server::get(\OCP\IRequest::class) since \OC::$server does not yet exist.
104
-		 */
105
-		$params = [
106
-			'server' => [
107
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'] ?? null,
108
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'] ?? null,
109
-			],
110
-		];
111
-		if (isset($_SERVER['REMOTE_ADDR'])) {
112
-			$params['server']['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR'];
113
-		}
114
-		$fakeRequest = new \OC\AppFramework\Http\Request(
115
-			$params,
116
-			new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()),
117
-			new \OC\AllConfig(new \OC\SystemConfig(self::$config))
118
-		);
119
-		$scriptName = $fakeRequest->getScriptName();
120
-		if (substr($scriptName, -1) == '/') {
121
-			$scriptName .= 'index.php';
122
-			//make sure suburi follows the same rules as scriptName
123
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
124
-				if (substr(OC::$SUBURI, -1) != '/') {
125
-					OC::$SUBURI = OC::$SUBURI . '/';
126
-				}
127
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
128
-			}
129
-		}
130
-
131
-		if (OC::$CLI) {
132
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
133
-		} else {
134
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
135
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
136
-
137
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
138
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
139
-				}
140
-			} else {
141
-				// The scriptName is not ending with OC::$SUBURI
142
-				// This most likely means that we are calling from CLI.
143
-				// However some cron jobs still need to generate
144
-				// a web URL, so we use overwritewebroot as a fallback.
145
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
146
-			}
147
-
148
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
149
-			// slash which is required by URL generation.
150
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
151
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
152
-				header('Location: ' . \OC::$WEBROOT . '/');
153
-				exit();
154
-			}
155
-		}
156
-
157
-		// search the apps folder
158
-		$config_paths = self::$config->getValue('apps_paths', []);
159
-		if (!empty($config_paths)) {
160
-			foreach ($config_paths as $paths) {
161
-				if (isset($paths['url']) && isset($paths['path'])) {
162
-					$paths['url'] = rtrim($paths['url'], '/');
163
-					$paths['path'] = rtrim($paths['path'], '/');
164
-					OC::$APPSROOTS[] = $paths;
165
-				}
166
-			}
167
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
168
-			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
169
-		}
170
-
171
-		if (empty(OC::$APPSROOTS)) {
172
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
173
-				. '. You can also configure the location in the config.php file.');
174
-		}
175
-		$paths = [];
176
-		foreach (OC::$APPSROOTS as $path) {
177
-			$paths[] = $path['path'];
178
-			if (!is_dir($path['path'])) {
179
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
180
-					. ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path']));
181
-			}
182
-		}
183
-
184
-		// set the right include path
185
-		set_include_path(
186
-			implode(PATH_SEPARATOR, $paths)
187
-		);
188
-	}
189
-
190
-	public static function checkConfig(): void {
191
-		$l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
192
-
193
-		// Create config if it does not already exist
194
-		$configFilePath = self::$configDir . '/config.php';
195
-		if (!file_exists($configFilePath)) {
196
-			@touch($configFilePath);
197
-		}
198
-
199
-		// Check if config is writable
200
-		$configFileWritable = is_writable($configFilePath);
201
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
202
-			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
203
-			$urlGenerator = Server::get(IURLGenerator::class);
204
-
205
-			if (self::$CLI) {
206
-				echo $l->t('Cannot write into "config" directory!') . "\n";
207
-				echo $l->t('This can usually be fixed by giving the web server write access to the config directory.') . "\n";
208
-				echo "\n";
209
-				echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . "\n";
210
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]) . "\n";
211
-				exit;
212
-			} else {
213
-				Server::get(ITemplateManager::class)->printErrorPage(
214
-					$l->t('Cannot write into "config" directory!'),
215
-					$l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' '
216
-					. $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' '
217
-					. $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]),
218
-					503
219
-				);
220
-			}
221
-		}
222
-	}
223
-
224
-	public static function checkInstalled(\OC\SystemConfig $systemConfig): void {
225
-		if (defined('OC_CONSOLE')) {
226
-			return;
227
-		}
228
-		// Redirect to installer if not installed
229
-		if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
230
-			if (OC::$CLI) {
231
-				throw new Exception('Not installed');
232
-			} else {
233
-				$url = OC::$WEBROOT . '/index.php';
234
-				header('Location: ' . $url);
235
-			}
236
-			exit();
237
-		}
238
-	}
239
-
240
-	public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void {
241
-		// Allow ajax update script to execute without being stopped
242
-		if (((bool)$systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
243
-			// send http status 503
244
-			http_response_code(503);
245
-			header('X-Nextcloud-Maintenance-Mode: 1');
246
-			header('Retry-After: 120');
247
-
248
-			// render error page
249
-			$template = Server::get(ITemplateManager::class)->getTemplate('', 'update.user', 'guest');
250
-			\OCP\Util::addScript('core', 'maintenance');
251
-			\OCP\Util::addStyle('core', 'guest');
252
-			$template->printPage();
253
-			die();
254
-		}
255
-	}
256
-
257
-	/**
258
-	 * Prints the upgrade page
259
-	 */
260
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig): void {
261
-		$cliUpgradeLink = $systemConfig->getValue('upgrade.cli-upgrade-link', '');
262
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
263
-		$tooBig = false;
264
-		if (!$disableWebUpdater) {
265
-			$apps = Server::get(\OCP\App\IAppManager::class);
266
-			if ($apps->isEnabledForAnyone('user_ldap')) {
267
-				$qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
268
-
269
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
270
-					->from('ldap_user_mapping')
271
-					->executeQuery();
272
-				$row = $result->fetch();
273
-				$result->closeCursor();
274
-
275
-				$tooBig = ($row['user_count'] > 50);
276
-			}
277
-			if (!$tooBig && $apps->isEnabledForAnyone('user_saml')) {
278
-				$qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
279
-
280
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
281
-					->from('user_saml_users')
282
-					->executeQuery();
283
-				$row = $result->fetch();
284
-				$result->closeCursor();
285
-
286
-				$tooBig = ($row['user_count'] > 50);
287
-			}
288
-			if (!$tooBig) {
289
-				// count users
290
-				$totalUsers = Server::get(\OCP\IUserManager::class)->countUsersTotal(51);
291
-				$tooBig = ($totalUsers > 50);
292
-			}
293
-		}
294
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
295
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
296
-
297
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
298
-			// send http status 503
299
-			http_response_code(503);
300
-			header('Retry-After: 120');
301
-
302
-			$serverVersion = \OCP\Server::get(\OCP\ServerVersion::class);
303
-
304
-			// render error page
305
-			$template = Server::get(ITemplateManager::class)->getTemplate('', 'update.use-cli', 'guest');
306
-			$template->assign('productName', 'nextcloud'); // for now
307
-			$template->assign('version', $serverVersion->getVersionString());
308
-			$template->assign('tooBig', $tooBig);
309
-			$template->assign('cliUpgradeLink', $cliUpgradeLink);
310
-
311
-			$template->printPage();
312
-			die();
313
-		}
314
-
315
-		// check whether this is a core update or apps update
316
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
317
-		$currentVersion = implode('.', \OCP\Util::getVersion());
318
-
319
-		// if not a core upgrade, then it's apps upgrade
320
-		$isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
321
-
322
-		$oldTheme = $systemConfig->getValue('theme');
323
-		$systemConfig->setValue('theme', '');
324
-		\OCP\Util::addScript('core', 'common');
325
-		\OCP\Util::addScript('core', 'main');
326
-		\OCP\Util::addTranslations('core');
327
-		\OCP\Util::addScript('core', 'update');
328
-
329
-		/** @var \OC\App\AppManager $appManager */
330
-		$appManager = Server::get(\OCP\App\IAppManager::class);
331
-
332
-		$tmpl = Server::get(ITemplateManager::class)->getTemplate('', 'update.admin', 'guest');
333
-		$tmpl->assign('version', \OCP\Server::get(\OCP\ServerVersion::class)->getVersionString());
334
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
335
-
336
-		// get third party apps
337
-		$ocVersion = \OCP\Util::getVersion();
338
-		$ocVersion = implode('.', $ocVersion);
339
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
340
-		$incompatibleOverwrites = $systemConfig->getValue('app_install_overwrite', []);
341
-		$incompatibleShippedApps = [];
342
-		$incompatibleDisabledApps = [];
343
-		foreach ($incompatibleApps as $appInfo) {
344
-			if ($appManager->isShipped($appInfo['id'])) {
345
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
346
-			}
347
-			if (!in_array($appInfo['id'], $incompatibleOverwrites)) {
348
-				$incompatibleDisabledApps[] = $appInfo;
349
-			}
350
-		}
351
-
352
-		if (!empty($incompatibleShippedApps)) {
353
-			$l = Server::get(\OCP\L10N\IFactory::class)->get('core');
354
-			$hint = $l->t('Application %1$s is not present or has a non-compatible version with this server. Please check the apps directory.', [implode(', ', $incompatibleShippedApps)]);
355
-			throw new \OCP\HintException('Application ' . implode(', ', $incompatibleShippedApps) . ' is not present or has a non-compatible version with this server. Please check the apps directory.', $hint);
356
-		}
357
-
358
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
359
-		$tmpl->assign('incompatibleAppsList', $incompatibleDisabledApps);
360
-		try {
361
-			$defaults = new \OC_Defaults();
362
-			$tmpl->assign('productName', $defaults->getName());
363
-		} catch (Throwable $error) {
364
-			$tmpl->assign('productName', 'Nextcloud');
365
-		}
366
-		$tmpl->assign('oldTheme', $oldTheme);
367
-		$tmpl->printPage();
368
-	}
369
-
370
-	public static function initSession(): void {
371
-		$request = Server::get(IRequest::class);
372
-
373
-		// TODO: Temporary disabled again to solve issues with CalDAV/CardDAV clients like DAVx5 that use cookies
374
-		// TODO: See https://github.com/nextcloud/server/issues/37277#issuecomment-1476366147 and the other comments
375
-		// TODO: for further information.
376
-		// $isDavRequest = strpos($request->getRequestUri(), '/remote.php/dav') === 0 || strpos($request->getRequestUri(), '/remote.php/webdav') === 0;
377
-		// if ($request->getHeader('Authorization') !== '' && is_null($request->getCookie('cookie_test')) && $isDavRequest && !isset($_COOKIE['nc_session_id'])) {
378
-		// setcookie('cookie_test', 'test', time() + 3600);
379
-		// // Do not initialize the session if a request is authenticated directly
380
-		// // unless there is a session cookie already sent along
381
-		// return;
382
-		// }
383
-
384
-		if ($request->getServerProtocol() === 'https') {
385
-			ini_set('session.cookie_secure', 'true');
386
-		}
387
-
388
-		// prevents javascript from accessing php session cookies
389
-		ini_set('session.cookie_httponly', 'true');
390
-
391
-		// Do not initialize sessions for 'status.php' requests
392
-		// Monitoring endpoints can quickly flood session handlers
393
-		// and 'status.php' doesn't require sessions anyway
394
-		if (str_ends_with($request->getScriptName(), '/status.php')) {
395
-			return;
396
-		}
397
-
398
-		// set the cookie path to the Nextcloud directory
399
-		$cookie_path = OC::$WEBROOT ? : '/';
400
-		ini_set('session.cookie_path', $cookie_path);
401
-
402
-		// Let the session name be changed in the initSession Hook
403
-		$sessionName = OC_Util::getInstanceId();
404
-
405
-		try {
406
-			$logger = null;
407
-			if (Server::get(\OC\SystemConfig::class)->getValue('installed', false)) {
408
-				$logger = logger('core');
409
-			}
410
-
411
-			// set the session name to the instance id - which is unique
412
-			$session = new \OC\Session\Internal(
413
-				$sessionName,
414
-				$logger,
415
-			);
416
-
417
-			$cryptoWrapper = Server::get(\OC\Session\CryptoWrapper::class);
418
-			$session = $cryptoWrapper->wrapSession($session);
419
-			self::$server->setSession($session);
420
-
421
-			// if session can't be started break with http 500 error
422
-		} catch (Exception $e) {
423
-			Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]);
424
-			//show the user a detailed error page
425
-			Server::get(ITemplateManager::class)->printExceptionErrorPage($e, 500);
426
-			die();
427
-		}
428
-
429
-		//try to set the session lifetime
430
-		$sessionLifeTime = self::getSessionLifeTime();
431
-
432
-		// session timeout
433
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
434
-			if (isset($_COOKIE[session_name()])) {
435
-				setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
436
-			}
437
-			Server::get(IUserSession::class)->logout();
438
-		}
439
-
440
-		if (!self::hasSessionRelaxedExpiry()) {
441
-			$session->set('LAST_ACTIVITY', time());
442
-		}
443
-		$session->close();
444
-	}
445
-
446
-	private static function getSessionLifeTime(): int {
447
-		return Server::get(\OC\AllConfig::class)->getSystemValueInt('session_lifetime', 60 * 60 * 24);
448
-	}
449
-
450
-	/**
451
-	 * @return bool true if the session expiry should only be done by gc instead of an explicit timeout
452
-	 */
453
-	public static function hasSessionRelaxedExpiry(): bool {
454
-		return Server::get(\OC\AllConfig::class)->getSystemValueBool('session_relaxed_expiry', false);
455
-	}
456
-
457
-	/**
458
-	 * Try to set some values to the required Nextcloud default
459
-	 */
460
-	public static function setRequiredIniValues(): void {
461
-		// Don't display errors and log them
462
-		@ini_set('display_errors', '0');
463
-		@ini_set('log_errors', '1');
464
-
465
-		// Try to configure php to enable big file uploads.
466
-		// This doesn't work always depending on the webserver and php configuration.
467
-		// Let's try to overwrite some defaults if they are smaller than 1 hour
468
-
469
-		if (intval(@ini_get('max_execution_time') ?: 0) < 3600) {
470
-			@ini_set('max_execution_time', strval(3600));
471
-		}
472
-
473
-		if (intval(@ini_get('max_input_time') ?: 0) < 3600) {
474
-			@ini_set('max_input_time', strval(3600));
475
-		}
476
-
477
-		// Try to set the maximum execution time to the largest time limit we have
478
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
479
-			@set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time'))));
480
-		}
481
-
482
-		@ini_set('default_charset', 'UTF-8');
483
-		@ini_set('gd.jpeg_ignore_warning', '1');
484
-	}
485
-
486
-	/**
487
-	 * Send the same site cookies
488
-	 */
489
-	private static function sendSameSiteCookies(): void {
490
-		$cookieParams = session_get_cookie_params();
491
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
492
-		$policies = [
493
-			'lax',
494
-			'strict',
495
-		];
496
-
497
-		// Append __Host to the cookie if it meets the requirements
498
-		$cookiePrefix = '';
499
-		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
500
-			$cookiePrefix = '__Host-';
501
-		}
502
-
503
-		foreach ($policies as $policy) {
504
-			header(
505
-				sprintf(
506
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
507
-					$cookiePrefix,
508
-					$policy,
509
-					$cookieParams['path'],
510
-					$policy
511
-				),
512
-				false
513
-			);
514
-		}
515
-	}
516
-
517
-	/**
518
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
519
-	 * be set in every request if cookies are sent to add a second level of
520
-	 * defense against CSRF.
521
-	 *
522
-	 * If the cookie is not sent this will set the cookie and reload the page.
523
-	 * We use an additional cookie since we want to protect logout CSRF and
524
-	 * also we can't directly interfere with PHP's session mechanism.
525
-	 */
526
-	private static function performSameSiteCookieProtection(IConfig $config): void {
527
-		$request = Server::get(IRequest::class);
528
-
529
-		// Some user agents are notorious and don't really properly follow HTTP
530
-		// specifications. For those, have an automated opt-out. Since the protection
531
-		// for remote.php is applied in base.php as starting point we need to opt out
532
-		// here.
533
-		$incompatibleUserAgents = $config->getSystemValue('csrf.optout');
534
-
535
-		// Fallback, if csrf.optout is unset
536
-		if (!is_array($incompatibleUserAgents)) {
537
-			$incompatibleUserAgents = [
538
-				// OS X Finder
539
-				'/^WebDAVFS/',
540
-				// Windows webdav drive
541
-				'/^Microsoft-WebDAV-MiniRedir/',
542
-			];
543
-		}
544
-
545
-		if ($request->isUserAgent($incompatibleUserAgents)) {
546
-			return;
547
-		}
548
-
549
-		if (count($_COOKIE) > 0) {
550
-			$requestUri = $request->getScriptName();
551
-			$processingScript = explode('/', $requestUri);
552
-			$processingScript = $processingScript[count($processingScript) - 1];
553
-
554
-			// index.php routes are handled in the middleware
555
-			// and cron.php does not need any authentication at all
556
-			if ($processingScript === 'index.php'
557
-				|| $processingScript === 'cron.php') {
558
-				return;
559
-			}
560
-
561
-			// All other endpoints require the lax and the strict cookie
562
-			if (!$request->passesStrictCookieCheck()) {
563
-				logger('core')->warning('Request does not pass strict cookie check');
564
-				self::sendSameSiteCookies();
565
-				// Debug mode gets access to the resources without strict cookie
566
-				// due to the fact that the SabreDAV browser also lives there.
567
-				if (!$config->getSystemValueBool('debug', false)) {
568
-					http_response_code(\OCP\AppFramework\Http::STATUS_PRECONDITION_FAILED);
569
-					header('Content-Type: application/json');
570
-					echo json_encode(['error' => 'Strict Cookie has not been found in request']);
571
-					exit();
572
-				}
573
-			}
574
-		} elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
575
-			self::sendSameSiteCookies();
576
-		}
577
-	}
578
-
579
-	public static function init(): void {
580
-		// First handle PHP configuration and copy auth headers to the expected
581
-		// $_SERVER variable before doing anything Server object related
582
-		self::setRequiredIniValues();
583
-		self::handleAuthHeaders();
584
-
585
-		// prevent any XML processing from loading external entities
586
-		libxml_set_external_entity_loader(static function () {
587
-			return null;
588
-		});
589
-
590
-		// Set default timezone before the Server object is booted
591
-		if (!date_default_timezone_set('UTC')) {
592
-			throw new \RuntimeException('Could not set timezone to UTC');
593
-		}
594
-
595
-		// calculate the root directories
596
-		OC::$SERVERROOT = str_replace('\\', '/', substr(__DIR__, 0, -4));
597
-
598
-		// register autoloader
599
-		$loaderStart = microtime(true);
600
-		require_once __DIR__ . '/autoloader.php';
601
-		self::$loader = new \OC\Autoloader([
602
-			OC::$SERVERROOT . '/lib/private/legacy',
603
-		]);
604
-		if (defined('PHPUNIT_RUN')) {
605
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
606
-		}
607
-		spl_autoload_register([self::$loader, 'load']);
608
-		$loaderEnd = microtime(true);
609
-
610
-		self::$CLI = (php_sapi_name() == 'cli');
611
-
612
-		// Add default composer PSR-4 autoloader, ensure apcu to be disabled
613
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
614
-		self::$composerAutoloader->setApcuPrefix(null);
615
-
616
-
617
-		try {
618
-			self::initPaths();
619
-			// setup 3rdparty autoloader
620
-			$vendorAutoLoad = OC::$SERVERROOT . '/3rdparty/autoload.php';
621
-			if (!file_exists($vendorAutoLoad)) {
622
-				throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
623
-			}
624
-			require_once $vendorAutoLoad;
625
-		} catch (\RuntimeException $e) {
626
-			if (!self::$CLI) {
627
-				http_response_code(503);
628
-			}
629
-			// we can't use the template error page here, because this needs the
630
-			// DI container which isn't available yet
631
-			print($e->getMessage());
632
-			exit();
633
-		}
634
-
635
-		// setup the basic server
636
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
637
-		self::$server->boot();
638
-
639
-		try {
640
-			$profiler = new BuiltInProfiler(
641
-				Server::get(IConfig::class),
642
-				Server::get(IRequest::class),
643
-			);
644
-			$profiler->start();
645
-		} catch (\Throwable $e) {
646
-			logger('core')->error('Failed to start profiler: ' . $e->getMessage(), ['app' => 'base']);
647
-		}
648
-
649
-		if (self::$CLI && in_array('--' . \OCP\Console\ReservedOptions::DEBUG_LOG, $_SERVER['argv'])) {
650
-			\OC\Core\Listener\BeforeMessageLoggedEventListener::setup();
651
-		}
652
-
653
-		$eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class);
654
-		$eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
655
-		$eventLogger->start('boot', 'Initialize');
656
-
657
-		// Override php.ini and log everything if we're troubleshooting
658
-		if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
659
-			error_reporting(E_ALL);
660
-		}
661
-
662
-		$systemConfig = Server::get(\OC\SystemConfig::class);
663
-		self::registerAutoloaderCache($systemConfig);
664
-
665
-		// initialize intl fallback if necessary
666
-		OC_Util::isSetLocaleWorking();
667
-
668
-		$config = Server::get(IConfig::class);
669
-		if (!defined('PHPUNIT_RUN')) {
670
-			$errorHandler = new OC\Log\ErrorHandler(
671
-				\OCP\Server::get(\Psr\Log\LoggerInterface::class),
672
-			);
673
-			$exceptionHandler = [$errorHandler, 'onException'];
674
-			if ($config->getSystemValueBool('debug', false)) {
675
-				set_error_handler([$errorHandler, 'onAll'], E_ALL);
676
-				if (\OC::$CLI) {
677
-					$exceptionHandler = [Server::get(ITemplateManager::class), 'printExceptionErrorPage'];
678
-				}
679
-			} else {
680
-				set_error_handler([$errorHandler, 'onError']);
681
-			}
682
-			register_shutdown_function([$errorHandler, 'onShutdown']);
683
-			set_exception_handler($exceptionHandler);
684
-		}
685
-
686
-		/** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
687
-		$bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class);
688
-		$bootstrapCoordinator->runInitialRegistration();
689
-
690
-		$eventLogger->start('init_session', 'Initialize session');
691
-
692
-		// Check for PHP SimpleXML extension earlier since we need it before our other checks and want to provide a useful hint for web users
693
-		// see https://github.com/nextcloud/server/pull/2619
694
-		if (!function_exists('simplexml_load_file')) {
695
-			throw new \OCP\HintException('The PHP SimpleXML/PHP-XML extension is not installed.', 'Install the extension or make sure it is enabled.');
696
-		}
697
-
698
-		$appManager = Server::get(\OCP\App\IAppManager::class);
699
-		if ($systemConfig->getValue('installed', false)) {
700
-			$appManager->loadApps(['session']);
701
-		}
702
-		if (!self::$CLI) {
703
-			self::initSession();
704
-		}
705
-		$eventLogger->end('init_session');
706
-		self::checkConfig();
707
-		self::checkInstalled($systemConfig);
708
-
709
-		OC_Response::addSecurityHeaders();
710
-
711
-		self::performSameSiteCookieProtection($config);
712
-
713
-		if (!defined('OC_CONSOLE')) {
714
-			$errors = OC_Util::checkServer($systemConfig);
715
-			if (count($errors) > 0) {
716
-				if (!self::$CLI) {
717
-					http_response_code(503);
718
-					Util::addStyle('guest');
719
-					try {
720
-						Server::get(ITemplateManager::class)->printGuestPage('', 'error', ['errors' => $errors]);
721
-						exit;
722
-					} catch (\Exception $e) {
723
-						// In case any error happens when showing the error page, we simply fall back to posting the text.
724
-						// This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
725
-					}
726
-				}
727
-
728
-				// Convert l10n string into regular string for usage in database
729
-				$staticErrors = [];
730
-				foreach ($errors as $error) {
731
-					echo $error['error'] . "\n";
732
-					echo $error['hint'] . "\n\n";
733
-					$staticErrors[] = [
734
-						'error' => (string)$error['error'],
735
-						'hint' => (string)$error['hint'],
736
-					];
737
-				}
738
-
739
-				try {
740
-					$config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
741
-				} catch (\Exception $e) {
742
-					echo('Writing to database failed');
743
-				}
744
-				exit(1);
745
-			} elseif (self::$CLI && $config->getSystemValueBool('installed', false)) {
746
-				$config->deleteAppValue('core', 'cronErrors');
747
-			}
748
-		}
749
-
750
-		// User and Groups
751
-		if (!$systemConfig->getValue('installed', false)) {
752
-			self::$server->getSession()->set('user_id', '');
753
-		}
754
-
755
-		Server::get(\OCP\IUserManager::class)->registerBackend(new \OC\User\Database());
756
-		Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database());
757
-
758
-		// Subscribe to the hook
759
-		\OCP\Util::connectHook(
760
-			'\OCA\Files_Sharing\API\Server2Server',
761
-			'preLoginNameUsedAsUserName',
762
-			'\OC\User\Database',
763
-			'preLoginNameUsedAsUserName'
764
-		);
765
-
766
-		//setup extra user backends
767
-		if (!\OCP\Util::needUpgrade()) {
768
-			OC_User::setupBackends();
769
-		} else {
770
-			// Run upgrades in incognito mode
771
-			OC_User::setIncognitoMode(true);
772
-		}
773
-
774
-		self::registerCleanupHooks($systemConfig);
775
-		self::registerShareHooks($systemConfig);
776
-		self::registerEncryptionWrapperAndHooks();
777
-		self::registerAccountHooks();
778
-		self::registerResourceCollectionHooks();
779
-		self::registerFileReferenceEventListener();
780
-		self::registerRenderReferenceEventListener();
781
-		self::registerAppRestrictionsHooks();
782
-
783
-		// Make sure that the application class is not loaded before the database is setup
784
-		if ($systemConfig->getValue('installed', false)) {
785
-			$appManager->loadApp('settings');
786
-			/* Build core application to make sure that listeners are registered */
787
-			Server::get(\OC\Core\Application::class);
788
-		}
789
-
790
-		//make sure temporary files are cleaned up
791
-		$tmpManager = Server::get(\OCP\ITempManager::class);
792
-		register_shutdown_function([$tmpManager, 'clean']);
793
-		$lockProvider = Server::get(\OCP\Lock\ILockingProvider::class);
794
-		register_shutdown_function([$lockProvider, 'releaseAll']);
795
-
796
-		// Check whether the sample configuration has been copied
797
-		if ($systemConfig->getValue('copied_sample_config', false)) {
798
-			$l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
799
-			Server::get(ITemplateManager::class)->printErrorPage(
800
-				$l->t('Sample configuration detected'),
801
-				$l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php'),
802
-				503
803
-			);
804
-			return;
805
-		}
806
-
807
-		$request = Server::get(IRequest::class);
808
-		$host = $request->getInsecureServerHost();
809
-		/**
810
-		 * if the host passed in headers isn't trusted
811
-		 * FIXME: Should not be in here at all :see_no_evil:
812
-		 */
813
-		if (!OC::$CLI
814
-			&& !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host)
815
-			&& $config->getSystemValueBool('installed', false)
816
-		) {
817
-			// Allow access to CSS resources
818
-			$isScssRequest = false;
819
-			if (strpos($request->getPathInfo() ?: '', '/css/') === 0) {
820
-				$isScssRequest = true;
821
-			}
822
-
823
-			if (substr($request->getRequestUri(), -11) === '/status.php') {
824
-				http_response_code(400);
825
-				header('Content-Type: application/json');
826
-				echo '{"error": "Trusted domain error.", "code": 15}';
827
-				exit();
828
-			}
829
-
830
-			if (!$isScssRequest) {
831
-				http_response_code(400);
832
-				Server::get(LoggerInterface::class)->info(
833
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
834
-					[
835
-						'app' => 'core',
836
-						'remoteAddress' => $request->getRemoteAddress(),
837
-						'host' => $host,
838
-					]
839
-				);
840
-
841
-				$tmpl = Server::get(ITemplateManager::class)->getTemplate('core', 'untrustedDomain', 'guest');
842
-				$tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains'));
843
-				$tmpl->printPage();
844
-
845
-				exit();
846
-			}
847
-		}
848
-		$eventLogger->end('boot');
849
-		$eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
850
-		$eventLogger->start('runtime', 'Runtime');
851
-		$eventLogger->start('request', 'Full request after boot');
852
-		register_shutdown_function(function () use ($eventLogger) {
853
-			$eventLogger->end('request');
854
-		});
855
-
856
-		register_shutdown_function(function () {
857
-			$memoryPeak = memory_get_peak_usage();
858
-			$logLevel = match (true) {
859
-				$memoryPeak > 500_000_000 => ILogger::FATAL,
860
-				$memoryPeak > 400_000_000 => ILogger::ERROR,
861
-				$memoryPeak > 300_000_000 => ILogger::WARN,
862
-				default => null,
863
-			};
864
-			if ($logLevel !== null) {
865
-				$message = 'Request used more than 300 MB of RAM: ' . Util::humanFileSize($memoryPeak);
866
-				$logger = Server::get(LoggerInterface::class);
867
-				$logger->log($logLevel, $message, ['app' => 'core']);
868
-			}
869
-		});
870
-	}
871
-
872
-	/**
873
-	 * register hooks for the cleanup of cache and bruteforce protection
874
-	 */
875
-	public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void {
876
-		//don't try to do this before we are properly setup
877
-		if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
878
-			// NOTE: This will be replaced to use OCP
879
-			$userSession = Server::get(\OC\User\Session::class);
880
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
881
-				if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
882
-					// reset brute force delay for this IP address and username
883
-					$uid = $userSession->getUser()->getUID();
884
-					$request = Server::get(IRequest::class);
885
-					$throttler = Server::get(IThrottler::class);
886
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
887
-				}
888
-
889
-				try {
890
-					$cache = new \OC\Cache\File();
891
-					$cache->gc();
892
-				} catch (\OC\ServerNotAvailableException $e) {
893
-					// not a GC exception, pass it on
894
-					throw $e;
895
-				} catch (\OC\ForbiddenException $e) {
896
-					// filesystem blocked for this request, ignore
897
-				} catch (\Exception $e) {
898
-					// a GC exception should not prevent users from using OC,
899
-					// so log the exception
900
-					Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [
901
-						'app' => 'core',
902
-						'exception' => $e,
903
-					]);
904
-				}
905
-			});
906
-		}
907
-	}
908
-
909
-	private static function registerEncryptionWrapperAndHooks(): void {
910
-		/** @var \OC\Encryption\Manager */
911
-		$manager = Server::get(\OCP\Encryption\IManager::class);
912
-		Server::get(IEventDispatcher::class)->addListener(
913
-			BeforeFileSystemSetupEvent::class,
914
-			$manager->setupStorage(...),
915
-		);
916
-
917
-		$enabled = $manager->isEnabled();
918
-		if ($enabled) {
919
-			\OC\Encryption\EncryptionEventListener::register(Server::get(IEventDispatcher::class));
920
-		}
921
-	}
922
-
923
-	private static function registerAccountHooks(): void {
924
-		/** @var IEventDispatcher $dispatcher */
925
-		$dispatcher = Server::get(IEventDispatcher::class);
926
-		$dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
927
-	}
928
-
929
-	private static function registerAppRestrictionsHooks(): void {
930
-		/** @var \OC\Group\Manager $groupManager */
931
-		$groupManager = Server::get(\OCP\IGroupManager::class);
932
-		$groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
933
-			$appManager = Server::get(\OCP\App\IAppManager::class);
934
-			$apps = $appManager->getEnabledAppsForGroup($group);
935
-			foreach ($apps as $appId) {
936
-				$restrictions = $appManager->getAppRestriction($appId);
937
-				if (empty($restrictions)) {
938
-					continue;
939
-				}
940
-				$key = array_search($group->getGID(), $restrictions);
941
-				unset($restrictions[$key]);
942
-				$restrictions = array_values($restrictions);
943
-				if (empty($restrictions)) {
944
-					$appManager->disableApp($appId);
945
-				} else {
946
-					$appManager->enableAppForGroups($appId, $restrictions);
947
-				}
948
-			}
949
-		});
950
-	}
951
-
952
-	private static function registerResourceCollectionHooks(): void {
953
-		\OC\Collaboration\Resources\Listener::register(Server::get(IEventDispatcher::class));
954
-	}
955
-
956
-	private static function registerFileReferenceEventListener(): void {
957
-		\OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class));
958
-	}
959
-
960
-	private static function registerRenderReferenceEventListener() {
961
-		\OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class));
962
-	}
963
-
964
-	/**
965
-	 * register hooks for sharing
966
-	 */
967
-	public static function registerShareHooks(\OC\SystemConfig $systemConfig): void {
968
-		if ($systemConfig->getValue('installed')) {
969
-
970
-			$dispatcher = Server::get(IEventDispatcher::class);
971
-			$dispatcher->addServiceListener(UserRemovedEvent::class, UserRemovedListener::class);
972
-			$dispatcher->addServiceListener(GroupDeletedEvent::class, GroupDeletedListener::class);
973
-			$dispatcher->addServiceListener(UserDeletedEvent::class, UserDeletedListener::class);
974
-		}
975
-	}
976
-
977
-	protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig): void {
978
-		// The class loader takes an optional low-latency cache, which MUST be
979
-		// namespaced. The instanceid is used for namespacing, but might be
980
-		// unavailable at this point. Furthermore, it might not be possible to
981
-		// generate an instanceid via \OC_Util::getInstanceId() because the
982
-		// config file may not be writable. As such, we only register a class
983
-		// loader cache if instanceid is available without trying to create one.
984
-		$instanceId = $systemConfig->getValue('instanceid', null);
985
-		if ($instanceId) {
986
-			try {
987
-				$memcacheFactory = Server::get(\OCP\ICacheFactory::class);
988
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
989
-			} catch (\Exception $ex) {
990
-			}
991
-		}
992
-	}
993
-
994
-	/**
995
-	 * Handle the request
996
-	 */
997
-	public static function handleRequest(): void {
998
-		Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request');
999
-		$systemConfig = Server::get(\OC\SystemConfig::class);
1000
-
1001
-		// Check if Nextcloud is installed or in maintenance (update) mode
1002
-		if (!$systemConfig->getValue('installed', false)) {
1003
-			\OC::$server->getSession()->clear();
1004
-			$controller = Server::get(\OC\Core\Controller\SetupController::class);
1005
-			$controller->run($_POST);
1006
-			exit();
1007
-		}
1008
-
1009
-		$request = Server::get(IRequest::class);
1010
-		$requestPath = $request->getRawPathInfo();
1011
-		if ($requestPath === '/heartbeat') {
1012
-			return;
1013
-		}
1014
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
1015
-			self::checkMaintenanceMode($systemConfig);
1016
-
1017
-			if (\OCP\Util::needUpgrade()) {
1018
-				if (function_exists('opcache_reset')) {
1019
-					opcache_reset();
1020
-				}
1021
-				if (!((bool)$systemConfig->getValue('maintenance', false))) {
1022
-					self::printUpgradePage($systemConfig);
1023
-					exit();
1024
-				}
1025
-			}
1026
-		}
1027
-
1028
-		$appManager = Server::get(\OCP\App\IAppManager::class);
1029
-
1030
-		// Always load authentication apps
1031
-		$appManager->loadApps(['authentication']);
1032
-		$appManager->loadApps(['extended_authentication']);
1033
-
1034
-		// Load minimum set of apps
1035
-		if (!\OCP\Util::needUpgrade()
1036
-			&& !((bool)$systemConfig->getValue('maintenance', false))) {
1037
-			// For logged-in users: Load everything
1038
-			if (Server::get(IUserSession::class)->isLoggedIn()) {
1039
-				$appManager->loadApps();
1040
-			} else {
1041
-				// For guests: Load only filesystem and logging
1042
-				$appManager->loadApps(['filesystem', 'logging']);
1043
-
1044
-				// Don't try to login when a client is trying to get a OAuth token.
1045
-				// OAuth needs to support basic auth too, so the login is not valid
1046
-				// inside Nextcloud and the Login exception would ruin it.
1047
-				if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') {
1048
-					self::handleLogin($request);
1049
-				}
1050
-			}
1051
-		}
1052
-
1053
-		if (!self::$CLI) {
1054
-			try {
1055
-				if (!\OCP\Util::needUpgrade()) {
1056
-					$appManager->loadApps(['filesystem', 'logging']);
1057
-					$appManager->loadApps();
1058
-				}
1059
-				Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo());
1060
-				return;
1061
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1062
-				//header('HTTP/1.0 404 Not Found');
1063
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1064
-				http_response_code(405);
1065
-				return;
1066
-			}
1067
-		}
1068
-
1069
-		// Handle WebDAV
1070
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1071
-			// not allowed any more to prevent people
1072
-			// mounting this root directly.
1073
-			// Users need to mount remote.php/webdav instead.
1074
-			http_response_code(405);
1075
-			return;
1076
-		}
1077
-
1078
-		// Handle requests for JSON or XML
1079
-		$acceptHeader = $request->getHeader('Accept');
1080
-		if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) {
1081
-			http_response_code(404);
1082
-			return;
1083
-		}
1084
-
1085
-		// Handle resources that can't be found
1086
-		// This prevents browsers from redirecting to the default page and then
1087
-		// attempting to parse HTML as CSS and similar.
1088
-		$destinationHeader = $request->getHeader('Sec-Fetch-Dest');
1089
-		if (in_array($destinationHeader, ['font', 'script', 'style'])) {
1090
-			http_response_code(404);
1091
-			return;
1092
-		}
1093
-
1094
-		// Redirect to the default app or login only as an entry point
1095
-		if ($requestPath === '') {
1096
-			// Someone is logged in
1097
-			if (Server::get(IUserSession::class)->isLoggedIn()) {
1098
-				header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl());
1099
-			} else {
1100
-				// Not handled and not logged in
1101
-				header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm'));
1102
-			}
1103
-			return;
1104
-		}
1105
-
1106
-		try {
1107
-			Server::get(\OC\Route\Router::class)->match('/error/404');
1108
-		} catch (\Exception $e) {
1109
-			if (!$e instanceof MethodNotAllowedException) {
1110
-				logger('core')->emergency($e->getMessage(), ['exception' => $e]);
1111
-			}
1112
-			$l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
1113
-			Server::get(ITemplateManager::class)->printErrorPage(
1114
-				'404',
1115
-				$l->t('The page could not be found on the server.'),
1116
-				404
1117
-			);
1118
-		}
1119
-	}
1120
-
1121
-	/**
1122
-	 * Check login: apache auth, auth token, basic auth
1123
-	 */
1124
-	public static function handleLogin(OCP\IRequest $request): bool {
1125
-		if ($request->getHeader('X-Nextcloud-Federation')) {
1126
-			return false;
1127
-		}
1128
-		$userSession = Server::get(\OC\User\Session::class);
1129
-		if (OC_User::handleApacheAuth()) {
1130
-			return true;
1131
-		}
1132
-		if (self::tryAppAPILogin($request)) {
1133
-			return true;
1134
-		}
1135
-		if ($userSession->tryTokenLogin($request)) {
1136
-			return true;
1137
-		}
1138
-		if (isset($_COOKIE['nc_username'])
1139
-			&& isset($_COOKIE['nc_token'])
1140
-			&& isset($_COOKIE['nc_session_id'])
1141
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1142
-			return true;
1143
-		}
1144
-		if ($userSession->tryBasicAuthLogin($request, Server::get(IThrottler::class))) {
1145
-			return true;
1146
-		}
1147
-		return false;
1148
-	}
1149
-
1150
-	protected static function handleAuthHeaders(): void {
1151
-		//copy http auth headers for apache+php-fcgid work around
1152
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1153
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1154
-		}
1155
-
1156
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1157
-		$vars = [
1158
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1159
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1160
-		];
1161
-		foreach ($vars as $var) {
1162
-			if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1163
-				$credentials = explode(':', base64_decode($matches[1]), 2);
1164
-				if (count($credentials) === 2) {
1165
-					$_SERVER['PHP_AUTH_USER'] = $credentials[0];
1166
-					$_SERVER['PHP_AUTH_PW'] = $credentials[1];
1167
-					break;
1168
-				}
1169
-			}
1170
-		}
1171
-	}
1172
-
1173
-	protected static function tryAppAPILogin(OCP\IRequest $request): bool {
1174
-		if (!$request->getHeader('AUTHORIZATION-APP-API')) {
1175
-			return false;
1176
-		}
1177
-		$appManager = Server::get(OCP\App\IAppManager::class);
1178
-		if (!$appManager->isEnabledForAnyone('app_api')) {
1179
-			return false;
1180
-		}
1181
-		try {
1182
-			$appAPIService = Server::get(OCA\AppAPI\Service\AppAPIService::class);
1183
-			return $appAPIService->validateExAppRequestToNC($request);
1184
-		} catch (\Psr\Container\NotFoundExceptionInterface|\Psr\Container\ContainerExceptionInterface $e) {
1185
-			return false;
1186
-		}
1187
-	}
42
+    /**
43
+     * Associative array for autoloading. classname => filename
44
+     */
45
+    public static array $CLASSPATH = [];
46
+    /**
47
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
48
+     */
49
+    public static string $SERVERROOT = '';
50
+    /**
51
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
52
+     */
53
+    private static string $SUBURI = '';
54
+    /**
55
+     * the Nextcloud root path for http requests (e.g. /nextcloud)
56
+     */
57
+    public static string $WEBROOT = '';
58
+    /**
59
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
60
+     * web path in 'url'
61
+     */
62
+    public static array $APPSROOTS = [];
63
+
64
+    public static string $configDir;
65
+
66
+    /**
67
+     * requested app
68
+     */
69
+    public static string $REQUESTEDAPP = '';
70
+
71
+    /**
72
+     * check if Nextcloud runs in cli mode
73
+     */
74
+    public static bool $CLI = false;
75
+
76
+    public static \OC\Autoloader $loader;
77
+
78
+    public static \Composer\Autoload\ClassLoader $composerAutoloader;
79
+
80
+    public static \OC\Server $server;
81
+
82
+    private static \OC\Config $config;
83
+
84
+    /**
85
+     * @throws \RuntimeException when the 3rdparty directory is missing or
86
+     *                           the app path list is empty or contains an invalid path
87
+     */
88
+    public static function initPaths(): void {
89
+        if (defined('PHPUNIT_CONFIG_DIR')) {
90
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
91
+        } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
92
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
93
+        } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
94
+            self::$configDir = rtrim($dir, '/') . '/';
95
+        } else {
96
+            self::$configDir = OC::$SERVERROOT . '/config/';
97
+        }
98
+        self::$config = new \OC\Config(self::$configDir);
99
+
100
+        OC::$SUBURI = str_replace('\\', '/', substr(realpath($_SERVER['SCRIPT_FILENAME'] ?? ''), strlen(OC::$SERVERROOT)));
101
+        /**
102
+         * FIXME: The following lines are required because we can't yet instantiate
103
+         *        Server::get(\OCP\IRequest::class) since \OC::$server does not yet exist.
104
+         */
105
+        $params = [
106
+            'server' => [
107
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'] ?? null,
108
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'] ?? null,
109
+            ],
110
+        ];
111
+        if (isset($_SERVER['REMOTE_ADDR'])) {
112
+            $params['server']['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR'];
113
+        }
114
+        $fakeRequest = new \OC\AppFramework\Http\Request(
115
+            $params,
116
+            new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()),
117
+            new \OC\AllConfig(new \OC\SystemConfig(self::$config))
118
+        );
119
+        $scriptName = $fakeRequest->getScriptName();
120
+        if (substr($scriptName, -1) == '/') {
121
+            $scriptName .= 'index.php';
122
+            //make sure suburi follows the same rules as scriptName
123
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
124
+                if (substr(OC::$SUBURI, -1) != '/') {
125
+                    OC::$SUBURI = OC::$SUBURI . '/';
126
+                }
127
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
128
+            }
129
+        }
130
+
131
+        if (OC::$CLI) {
132
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
133
+        } else {
134
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
135
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
136
+
137
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
138
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
139
+                }
140
+            } else {
141
+                // The scriptName is not ending with OC::$SUBURI
142
+                // This most likely means that we are calling from CLI.
143
+                // However some cron jobs still need to generate
144
+                // a web URL, so we use overwritewebroot as a fallback.
145
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
146
+            }
147
+
148
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
149
+            // slash which is required by URL generation.
150
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
151
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
152
+                header('Location: ' . \OC::$WEBROOT . '/');
153
+                exit();
154
+            }
155
+        }
156
+
157
+        // search the apps folder
158
+        $config_paths = self::$config->getValue('apps_paths', []);
159
+        if (!empty($config_paths)) {
160
+            foreach ($config_paths as $paths) {
161
+                if (isset($paths['url']) && isset($paths['path'])) {
162
+                    $paths['url'] = rtrim($paths['url'], '/');
163
+                    $paths['path'] = rtrim($paths['path'], '/');
164
+                    OC::$APPSROOTS[] = $paths;
165
+                }
166
+            }
167
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
168
+            OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
169
+        }
170
+
171
+        if (empty(OC::$APPSROOTS)) {
172
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
173
+                . '. You can also configure the location in the config.php file.');
174
+        }
175
+        $paths = [];
176
+        foreach (OC::$APPSROOTS as $path) {
177
+            $paths[] = $path['path'];
178
+            if (!is_dir($path['path'])) {
179
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
180
+                    . ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path']));
181
+            }
182
+        }
183
+
184
+        // set the right include path
185
+        set_include_path(
186
+            implode(PATH_SEPARATOR, $paths)
187
+        );
188
+    }
189
+
190
+    public static function checkConfig(): void {
191
+        $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
192
+
193
+        // Create config if it does not already exist
194
+        $configFilePath = self::$configDir . '/config.php';
195
+        if (!file_exists($configFilePath)) {
196
+            @touch($configFilePath);
197
+        }
198
+
199
+        // Check if config is writable
200
+        $configFileWritable = is_writable($configFilePath);
201
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
202
+            || !$configFileWritable && \OCP\Util::needUpgrade()) {
203
+            $urlGenerator = Server::get(IURLGenerator::class);
204
+
205
+            if (self::$CLI) {
206
+                echo $l->t('Cannot write into "config" directory!') . "\n";
207
+                echo $l->t('This can usually be fixed by giving the web server write access to the config directory.') . "\n";
208
+                echo "\n";
209
+                echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . "\n";
210
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]) . "\n";
211
+                exit;
212
+            } else {
213
+                Server::get(ITemplateManager::class)->printErrorPage(
214
+                    $l->t('Cannot write into "config" directory!'),
215
+                    $l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' '
216
+                    . $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' '
217
+                    . $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]),
218
+                    503
219
+                );
220
+            }
221
+        }
222
+    }
223
+
224
+    public static function checkInstalled(\OC\SystemConfig $systemConfig): void {
225
+        if (defined('OC_CONSOLE')) {
226
+            return;
227
+        }
228
+        // Redirect to installer if not installed
229
+        if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
230
+            if (OC::$CLI) {
231
+                throw new Exception('Not installed');
232
+            } else {
233
+                $url = OC::$WEBROOT . '/index.php';
234
+                header('Location: ' . $url);
235
+            }
236
+            exit();
237
+        }
238
+    }
239
+
240
+    public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void {
241
+        // Allow ajax update script to execute without being stopped
242
+        if (((bool)$systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
243
+            // send http status 503
244
+            http_response_code(503);
245
+            header('X-Nextcloud-Maintenance-Mode: 1');
246
+            header('Retry-After: 120');
247
+
248
+            // render error page
249
+            $template = Server::get(ITemplateManager::class)->getTemplate('', 'update.user', 'guest');
250
+            \OCP\Util::addScript('core', 'maintenance');
251
+            \OCP\Util::addStyle('core', 'guest');
252
+            $template->printPage();
253
+            die();
254
+        }
255
+    }
256
+
257
+    /**
258
+     * Prints the upgrade page
259
+     */
260
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig): void {
261
+        $cliUpgradeLink = $systemConfig->getValue('upgrade.cli-upgrade-link', '');
262
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
263
+        $tooBig = false;
264
+        if (!$disableWebUpdater) {
265
+            $apps = Server::get(\OCP\App\IAppManager::class);
266
+            if ($apps->isEnabledForAnyone('user_ldap')) {
267
+                $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
268
+
269
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
270
+                    ->from('ldap_user_mapping')
271
+                    ->executeQuery();
272
+                $row = $result->fetch();
273
+                $result->closeCursor();
274
+
275
+                $tooBig = ($row['user_count'] > 50);
276
+            }
277
+            if (!$tooBig && $apps->isEnabledForAnyone('user_saml')) {
278
+                $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
279
+
280
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
281
+                    ->from('user_saml_users')
282
+                    ->executeQuery();
283
+                $row = $result->fetch();
284
+                $result->closeCursor();
285
+
286
+                $tooBig = ($row['user_count'] > 50);
287
+            }
288
+            if (!$tooBig) {
289
+                // count users
290
+                $totalUsers = Server::get(\OCP\IUserManager::class)->countUsersTotal(51);
291
+                $tooBig = ($totalUsers > 50);
292
+            }
293
+        }
294
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
295
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
296
+
297
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
298
+            // send http status 503
299
+            http_response_code(503);
300
+            header('Retry-After: 120');
301
+
302
+            $serverVersion = \OCP\Server::get(\OCP\ServerVersion::class);
303
+
304
+            // render error page
305
+            $template = Server::get(ITemplateManager::class)->getTemplate('', 'update.use-cli', 'guest');
306
+            $template->assign('productName', 'nextcloud'); // for now
307
+            $template->assign('version', $serverVersion->getVersionString());
308
+            $template->assign('tooBig', $tooBig);
309
+            $template->assign('cliUpgradeLink', $cliUpgradeLink);
310
+
311
+            $template->printPage();
312
+            die();
313
+        }
314
+
315
+        // check whether this is a core update or apps update
316
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
317
+        $currentVersion = implode('.', \OCP\Util::getVersion());
318
+
319
+        // if not a core upgrade, then it's apps upgrade
320
+        $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
321
+
322
+        $oldTheme = $systemConfig->getValue('theme');
323
+        $systemConfig->setValue('theme', '');
324
+        \OCP\Util::addScript('core', 'common');
325
+        \OCP\Util::addScript('core', 'main');
326
+        \OCP\Util::addTranslations('core');
327
+        \OCP\Util::addScript('core', 'update');
328
+
329
+        /** @var \OC\App\AppManager $appManager */
330
+        $appManager = Server::get(\OCP\App\IAppManager::class);
331
+
332
+        $tmpl = Server::get(ITemplateManager::class)->getTemplate('', 'update.admin', 'guest');
333
+        $tmpl->assign('version', \OCP\Server::get(\OCP\ServerVersion::class)->getVersionString());
334
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
335
+
336
+        // get third party apps
337
+        $ocVersion = \OCP\Util::getVersion();
338
+        $ocVersion = implode('.', $ocVersion);
339
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
340
+        $incompatibleOverwrites = $systemConfig->getValue('app_install_overwrite', []);
341
+        $incompatibleShippedApps = [];
342
+        $incompatibleDisabledApps = [];
343
+        foreach ($incompatibleApps as $appInfo) {
344
+            if ($appManager->isShipped($appInfo['id'])) {
345
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
346
+            }
347
+            if (!in_array($appInfo['id'], $incompatibleOverwrites)) {
348
+                $incompatibleDisabledApps[] = $appInfo;
349
+            }
350
+        }
351
+
352
+        if (!empty($incompatibleShippedApps)) {
353
+            $l = Server::get(\OCP\L10N\IFactory::class)->get('core');
354
+            $hint = $l->t('Application %1$s is not present or has a non-compatible version with this server. Please check the apps directory.', [implode(', ', $incompatibleShippedApps)]);
355
+            throw new \OCP\HintException('Application ' . implode(', ', $incompatibleShippedApps) . ' is not present or has a non-compatible version with this server. Please check the apps directory.', $hint);
356
+        }
357
+
358
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
359
+        $tmpl->assign('incompatibleAppsList', $incompatibleDisabledApps);
360
+        try {
361
+            $defaults = new \OC_Defaults();
362
+            $tmpl->assign('productName', $defaults->getName());
363
+        } catch (Throwable $error) {
364
+            $tmpl->assign('productName', 'Nextcloud');
365
+        }
366
+        $tmpl->assign('oldTheme', $oldTheme);
367
+        $tmpl->printPage();
368
+    }
369
+
370
+    public static function initSession(): void {
371
+        $request = Server::get(IRequest::class);
372
+
373
+        // TODO: Temporary disabled again to solve issues with CalDAV/CardDAV clients like DAVx5 that use cookies
374
+        // TODO: See https://github.com/nextcloud/server/issues/37277#issuecomment-1476366147 and the other comments
375
+        // TODO: for further information.
376
+        // $isDavRequest = strpos($request->getRequestUri(), '/remote.php/dav') === 0 || strpos($request->getRequestUri(), '/remote.php/webdav') === 0;
377
+        // if ($request->getHeader('Authorization') !== '' && is_null($request->getCookie('cookie_test')) && $isDavRequest && !isset($_COOKIE['nc_session_id'])) {
378
+        // setcookie('cookie_test', 'test', time() + 3600);
379
+        // // Do not initialize the session if a request is authenticated directly
380
+        // // unless there is a session cookie already sent along
381
+        // return;
382
+        // }
383
+
384
+        if ($request->getServerProtocol() === 'https') {
385
+            ini_set('session.cookie_secure', 'true');
386
+        }
387
+
388
+        // prevents javascript from accessing php session cookies
389
+        ini_set('session.cookie_httponly', 'true');
390
+
391
+        // Do not initialize sessions for 'status.php' requests
392
+        // Monitoring endpoints can quickly flood session handlers
393
+        // and 'status.php' doesn't require sessions anyway
394
+        if (str_ends_with($request->getScriptName(), '/status.php')) {
395
+            return;
396
+        }
397
+
398
+        // set the cookie path to the Nextcloud directory
399
+        $cookie_path = OC::$WEBROOT ? : '/';
400
+        ini_set('session.cookie_path', $cookie_path);
401
+
402
+        // Let the session name be changed in the initSession Hook
403
+        $sessionName = OC_Util::getInstanceId();
404
+
405
+        try {
406
+            $logger = null;
407
+            if (Server::get(\OC\SystemConfig::class)->getValue('installed', false)) {
408
+                $logger = logger('core');
409
+            }
410
+
411
+            // set the session name to the instance id - which is unique
412
+            $session = new \OC\Session\Internal(
413
+                $sessionName,
414
+                $logger,
415
+            );
416
+
417
+            $cryptoWrapper = Server::get(\OC\Session\CryptoWrapper::class);
418
+            $session = $cryptoWrapper->wrapSession($session);
419
+            self::$server->setSession($session);
420
+
421
+            // if session can't be started break with http 500 error
422
+        } catch (Exception $e) {
423
+            Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]);
424
+            //show the user a detailed error page
425
+            Server::get(ITemplateManager::class)->printExceptionErrorPage($e, 500);
426
+            die();
427
+        }
428
+
429
+        //try to set the session lifetime
430
+        $sessionLifeTime = self::getSessionLifeTime();
431
+
432
+        // session timeout
433
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
434
+            if (isset($_COOKIE[session_name()])) {
435
+                setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
436
+            }
437
+            Server::get(IUserSession::class)->logout();
438
+        }
439
+
440
+        if (!self::hasSessionRelaxedExpiry()) {
441
+            $session->set('LAST_ACTIVITY', time());
442
+        }
443
+        $session->close();
444
+    }
445
+
446
+    private static function getSessionLifeTime(): int {
447
+        return Server::get(\OC\AllConfig::class)->getSystemValueInt('session_lifetime', 60 * 60 * 24);
448
+    }
449
+
450
+    /**
451
+     * @return bool true if the session expiry should only be done by gc instead of an explicit timeout
452
+     */
453
+    public static function hasSessionRelaxedExpiry(): bool {
454
+        return Server::get(\OC\AllConfig::class)->getSystemValueBool('session_relaxed_expiry', false);
455
+    }
456
+
457
+    /**
458
+     * Try to set some values to the required Nextcloud default
459
+     */
460
+    public static function setRequiredIniValues(): void {
461
+        // Don't display errors and log them
462
+        @ini_set('display_errors', '0');
463
+        @ini_set('log_errors', '1');
464
+
465
+        // Try to configure php to enable big file uploads.
466
+        // This doesn't work always depending on the webserver and php configuration.
467
+        // Let's try to overwrite some defaults if they are smaller than 1 hour
468
+
469
+        if (intval(@ini_get('max_execution_time') ?: 0) < 3600) {
470
+            @ini_set('max_execution_time', strval(3600));
471
+        }
472
+
473
+        if (intval(@ini_get('max_input_time') ?: 0) < 3600) {
474
+            @ini_set('max_input_time', strval(3600));
475
+        }
476
+
477
+        // Try to set the maximum execution time to the largest time limit we have
478
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
479
+            @set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time'))));
480
+        }
481
+
482
+        @ini_set('default_charset', 'UTF-8');
483
+        @ini_set('gd.jpeg_ignore_warning', '1');
484
+    }
485
+
486
+    /**
487
+     * Send the same site cookies
488
+     */
489
+    private static function sendSameSiteCookies(): void {
490
+        $cookieParams = session_get_cookie_params();
491
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
492
+        $policies = [
493
+            'lax',
494
+            'strict',
495
+        ];
496
+
497
+        // Append __Host to the cookie if it meets the requirements
498
+        $cookiePrefix = '';
499
+        if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
500
+            $cookiePrefix = '__Host-';
501
+        }
502
+
503
+        foreach ($policies as $policy) {
504
+            header(
505
+                sprintf(
506
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
507
+                    $cookiePrefix,
508
+                    $policy,
509
+                    $cookieParams['path'],
510
+                    $policy
511
+                ),
512
+                false
513
+            );
514
+        }
515
+    }
516
+
517
+    /**
518
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
519
+     * be set in every request if cookies are sent to add a second level of
520
+     * defense against CSRF.
521
+     *
522
+     * If the cookie is not sent this will set the cookie and reload the page.
523
+     * We use an additional cookie since we want to protect logout CSRF and
524
+     * also we can't directly interfere with PHP's session mechanism.
525
+     */
526
+    private static function performSameSiteCookieProtection(IConfig $config): void {
527
+        $request = Server::get(IRequest::class);
528
+
529
+        // Some user agents are notorious and don't really properly follow HTTP
530
+        // specifications. For those, have an automated opt-out. Since the protection
531
+        // for remote.php is applied in base.php as starting point we need to opt out
532
+        // here.
533
+        $incompatibleUserAgents = $config->getSystemValue('csrf.optout');
534
+
535
+        // Fallback, if csrf.optout is unset
536
+        if (!is_array($incompatibleUserAgents)) {
537
+            $incompatibleUserAgents = [
538
+                // OS X Finder
539
+                '/^WebDAVFS/',
540
+                // Windows webdav drive
541
+                '/^Microsoft-WebDAV-MiniRedir/',
542
+            ];
543
+        }
544
+
545
+        if ($request->isUserAgent($incompatibleUserAgents)) {
546
+            return;
547
+        }
548
+
549
+        if (count($_COOKIE) > 0) {
550
+            $requestUri = $request->getScriptName();
551
+            $processingScript = explode('/', $requestUri);
552
+            $processingScript = $processingScript[count($processingScript) - 1];
553
+
554
+            // index.php routes are handled in the middleware
555
+            // and cron.php does not need any authentication at all
556
+            if ($processingScript === 'index.php'
557
+                || $processingScript === 'cron.php') {
558
+                return;
559
+            }
560
+
561
+            // All other endpoints require the lax and the strict cookie
562
+            if (!$request->passesStrictCookieCheck()) {
563
+                logger('core')->warning('Request does not pass strict cookie check');
564
+                self::sendSameSiteCookies();
565
+                // Debug mode gets access to the resources without strict cookie
566
+                // due to the fact that the SabreDAV browser also lives there.
567
+                if (!$config->getSystemValueBool('debug', false)) {
568
+                    http_response_code(\OCP\AppFramework\Http::STATUS_PRECONDITION_FAILED);
569
+                    header('Content-Type: application/json');
570
+                    echo json_encode(['error' => 'Strict Cookie has not been found in request']);
571
+                    exit();
572
+                }
573
+            }
574
+        } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
575
+            self::sendSameSiteCookies();
576
+        }
577
+    }
578
+
579
+    public static function init(): void {
580
+        // First handle PHP configuration and copy auth headers to the expected
581
+        // $_SERVER variable before doing anything Server object related
582
+        self::setRequiredIniValues();
583
+        self::handleAuthHeaders();
584
+
585
+        // prevent any XML processing from loading external entities
586
+        libxml_set_external_entity_loader(static function () {
587
+            return null;
588
+        });
589
+
590
+        // Set default timezone before the Server object is booted
591
+        if (!date_default_timezone_set('UTC')) {
592
+            throw new \RuntimeException('Could not set timezone to UTC');
593
+        }
594
+
595
+        // calculate the root directories
596
+        OC::$SERVERROOT = str_replace('\\', '/', substr(__DIR__, 0, -4));
597
+
598
+        // register autoloader
599
+        $loaderStart = microtime(true);
600
+        require_once __DIR__ . '/autoloader.php';
601
+        self::$loader = new \OC\Autoloader([
602
+            OC::$SERVERROOT . '/lib/private/legacy',
603
+        ]);
604
+        if (defined('PHPUNIT_RUN')) {
605
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
606
+        }
607
+        spl_autoload_register([self::$loader, 'load']);
608
+        $loaderEnd = microtime(true);
609
+
610
+        self::$CLI = (php_sapi_name() == 'cli');
611
+
612
+        // Add default composer PSR-4 autoloader, ensure apcu to be disabled
613
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
614
+        self::$composerAutoloader->setApcuPrefix(null);
615
+
616
+
617
+        try {
618
+            self::initPaths();
619
+            // setup 3rdparty autoloader
620
+            $vendorAutoLoad = OC::$SERVERROOT . '/3rdparty/autoload.php';
621
+            if (!file_exists($vendorAutoLoad)) {
622
+                throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
623
+            }
624
+            require_once $vendorAutoLoad;
625
+        } catch (\RuntimeException $e) {
626
+            if (!self::$CLI) {
627
+                http_response_code(503);
628
+            }
629
+            // we can't use the template error page here, because this needs the
630
+            // DI container which isn't available yet
631
+            print($e->getMessage());
632
+            exit();
633
+        }
634
+
635
+        // setup the basic server
636
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
637
+        self::$server->boot();
638
+
639
+        try {
640
+            $profiler = new BuiltInProfiler(
641
+                Server::get(IConfig::class),
642
+                Server::get(IRequest::class),
643
+            );
644
+            $profiler->start();
645
+        } catch (\Throwable $e) {
646
+            logger('core')->error('Failed to start profiler: ' . $e->getMessage(), ['app' => 'base']);
647
+        }
648
+
649
+        if (self::$CLI && in_array('--' . \OCP\Console\ReservedOptions::DEBUG_LOG, $_SERVER['argv'])) {
650
+            \OC\Core\Listener\BeforeMessageLoggedEventListener::setup();
651
+        }
652
+
653
+        $eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class);
654
+        $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
655
+        $eventLogger->start('boot', 'Initialize');
656
+
657
+        // Override php.ini and log everything if we're troubleshooting
658
+        if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
659
+            error_reporting(E_ALL);
660
+        }
661
+
662
+        $systemConfig = Server::get(\OC\SystemConfig::class);
663
+        self::registerAutoloaderCache($systemConfig);
664
+
665
+        // initialize intl fallback if necessary
666
+        OC_Util::isSetLocaleWorking();
667
+
668
+        $config = Server::get(IConfig::class);
669
+        if (!defined('PHPUNIT_RUN')) {
670
+            $errorHandler = new OC\Log\ErrorHandler(
671
+                \OCP\Server::get(\Psr\Log\LoggerInterface::class),
672
+            );
673
+            $exceptionHandler = [$errorHandler, 'onException'];
674
+            if ($config->getSystemValueBool('debug', false)) {
675
+                set_error_handler([$errorHandler, 'onAll'], E_ALL);
676
+                if (\OC::$CLI) {
677
+                    $exceptionHandler = [Server::get(ITemplateManager::class), 'printExceptionErrorPage'];
678
+                }
679
+            } else {
680
+                set_error_handler([$errorHandler, 'onError']);
681
+            }
682
+            register_shutdown_function([$errorHandler, 'onShutdown']);
683
+            set_exception_handler($exceptionHandler);
684
+        }
685
+
686
+        /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
687
+        $bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class);
688
+        $bootstrapCoordinator->runInitialRegistration();
689
+
690
+        $eventLogger->start('init_session', 'Initialize session');
691
+
692
+        // Check for PHP SimpleXML extension earlier since we need it before our other checks and want to provide a useful hint for web users
693
+        // see https://github.com/nextcloud/server/pull/2619
694
+        if (!function_exists('simplexml_load_file')) {
695
+            throw new \OCP\HintException('The PHP SimpleXML/PHP-XML extension is not installed.', 'Install the extension or make sure it is enabled.');
696
+        }
697
+
698
+        $appManager = Server::get(\OCP\App\IAppManager::class);
699
+        if ($systemConfig->getValue('installed', false)) {
700
+            $appManager->loadApps(['session']);
701
+        }
702
+        if (!self::$CLI) {
703
+            self::initSession();
704
+        }
705
+        $eventLogger->end('init_session');
706
+        self::checkConfig();
707
+        self::checkInstalled($systemConfig);
708
+
709
+        OC_Response::addSecurityHeaders();
710
+
711
+        self::performSameSiteCookieProtection($config);
712
+
713
+        if (!defined('OC_CONSOLE')) {
714
+            $errors = OC_Util::checkServer($systemConfig);
715
+            if (count($errors) > 0) {
716
+                if (!self::$CLI) {
717
+                    http_response_code(503);
718
+                    Util::addStyle('guest');
719
+                    try {
720
+                        Server::get(ITemplateManager::class)->printGuestPage('', 'error', ['errors' => $errors]);
721
+                        exit;
722
+                    } catch (\Exception $e) {
723
+                        // In case any error happens when showing the error page, we simply fall back to posting the text.
724
+                        // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
725
+                    }
726
+                }
727
+
728
+                // Convert l10n string into regular string for usage in database
729
+                $staticErrors = [];
730
+                foreach ($errors as $error) {
731
+                    echo $error['error'] . "\n";
732
+                    echo $error['hint'] . "\n\n";
733
+                    $staticErrors[] = [
734
+                        'error' => (string)$error['error'],
735
+                        'hint' => (string)$error['hint'],
736
+                    ];
737
+                }
738
+
739
+                try {
740
+                    $config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
741
+                } catch (\Exception $e) {
742
+                    echo('Writing to database failed');
743
+                }
744
+                exit(1);
745
+            } elseif (self::$CLI && $config->getSystemValueBool('installed', false)) {
746
+                $config->deleteAppValue('core', 'cronErrors');
747
+            }
748
+        }
749
+
750
+        // User and Groups
751
+        if (!$systemConfig->getValue('installed', false)) {
752
+            self::$server->getSession()->set('user_id', '');
753
+        }
754
+
755
+        Server::get(\OCP\IUserManager::class)->registerBackend(new \OC\User\Database());
756
+        Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database());
757
+
758
+        // Subscribe to the hook
759
+        \OCP\Util::connectHook(
760
+            '\OCA\Files_Sharing\API\Server2Server',
761
+            'preLoginNameUsedAsUserName',
762
+            '\OC\User\Database',
763
+            'preLoginNameUsedAsUserName'
764
+        );
765
+
766
+        //setup extra user backends
767
+        if (!\OCP\Util::needUpgrade()) {
768
+            OC_User::setupBackends();
769
+        } else {
770
+            // Run upgrades in incognito mode
771
+            OC_User::setIncognitoMode(true);
772
+        }
773
+
774
+        self::registerCleanupHooks($systemConfig);
775
+        self::registerShareHooks($systemConfig);
776
+        self::registerEncryptionWrapperAndHooks();
777
+        self::registerAccountHooks();
778
+        self::registerResourceCollectionHooks();
779
+        self::registerFileReferenceEventListener();
780
+        self::registerRenderReferenceEventListener();
781
+        self::registerAppRestrictionsHooks();
782
+
783
+        // Make sure that the application class is not loaded before the database is setup
784
+        if ($systemConfig->getValue('installed', false)) {
785
+            $appManager->loadApp('settings');
786
+            /* Build core application to make sure that listeners are registered */
787
+            Server::get(\OC\Core\Application::class);
788
+        }
789
+
790
+        //make sure temporary files are cleaned up
791
+        $tmpManager = Server::get(\OCP\ITempManager::class);
792
+        register_shutdown_function([$tmpManager, 'clean']);
793
+        $lockProvider = Server::get(\OCP\Lock\ILockingProvider::class);
794
+        register_shutdown_function([$lockProvider, 'releaseAll']);
795
+
796
+        // Check whether the sample configuration has been copied
797
+        if ($systemConfig->getValue('copied_sample_config', false)) {
798
+            $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
799
+            Server::get(ITemplateManager::class)->printErrorPage(
800
+                $l->t('Sample configuration detected'),
801
+                $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php'),
802
+                503
803
+            );
804
+            return;
805
+        }
806
+
807
+        $request = Server::get(IRequest::class);
808
+        $host = $request->getInsecureServerHost();
809
+        /**
810
+         * if the host passed in headers isn't trusted
811
+         * FIXME: Should not be in here at all :see_no_evil:
812
+         */
813
+        if (!OC::$CLI
814
+            && !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host)
815
+            && $config->getSystemValueBool('installed', false)
816
+        ) {
817
+            // Allow access to CSS resources
818
+            $isScssRequest = false;
819
+            if (strpos($request->getPathInfo() ?: '', '/css/') === 0) {
820
+                $isScssRequest = true;
821
+            }
822
+
823
+            if (substr($request->getRequestUri(), -11) === '/status.php') {
824
+                http_response_code(400);
825
+                header('Content-Type: application/json');
826
+                echo '{"error": "Trusted domain error.", "code": 15}';
827
+                exit();
828
+            }
829
+
830
+            if (!$isScssRequest) {
831
+                http_response_code(400);
832
+                Server::get(LoggerInterface::class)->info(
833
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
834
+                    [
835
+                        'app' => 'core',
836
+                        'remoteAddress' => $request->getRemoteAddress(),
837
+                        'host' => $host,
838
+                    ]
839
+                );
840
+
841
+                $tmpl = Server::get(ITemplateManager::class)->getTemplate('core', 'untrustedDomain', 'guest');
842
+                $tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains'));
843
+                $tmpl->printPage();
844
+
845
+                exit();
846
+            }
847
+        }
848
+        $eventLogger->end('boot');
849
+        $eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
850
+        $eventLogger->start('runtime', 'Runtime');
851
+        $eventLogger->start('request', 'Full request after boot');
852
+        register_shutdown_function(function () use ($eventLogger) {
853
+            $eventLogger->end('request');
854
+        });
855
+
856
+        register_shutdown_function(function () {
857
+            $memoryPeak = memory_get_peak_usage();
858
+            $logLevel = match (true) {
859
+                $memoryPeak > 500_000_000 => ILogger::FATAL,
860
+                $memoryPeak > 400_000_000 => ILogger::ERROR,
861
+                $memoryPeak > 300_000_000 => ILogger::WARN,
862
+                default => null,
863
+            };
864
+            if ($logLevel !== null) {
865
+                $message = 'Request used more than 300 MB of RAM: ' . Util::humanFileSize($memoryPeak);
866
+                $logger = Server::get(LoggerInterface::class);
867
+                $logger->log($logLevel, $message, ['app' => 'core']);
868
+            }
869
+        });
870
+    }
871
+
872
+    /**
873
+     * register hooks for the cleanup of cache and bruteforce protection
874
+     */
875
+    public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void {
876
+        //don't try to do this before we are properly setup
877
+        if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
878
+            // NOTE: This will be replaced to use OCP
879
+            $userSession = Server::get(\OC\User\Session::class);
880
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
881
+                if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
882
+                    // reset brute force delay for this IP address and username
883
+                    $uid = $userSession->getUser()->getUID();
884
+                    $request = Server::get(IRequest::class);
885
+                    $throttler = Server::get(IThrottler::class);
886
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
887
+                }
888
+
889
+                try {
890
+                    $cache = new \OC\Cache\File();
891
+                    $cache->gc();
892
+                } catch (\OC\ServerNotAvailableException $e) {
893
+                    // not a GC exception, pass it on
894
+                    throw $e;
895
+                } catch (\OC\ForbiddenException $e) {
896
+                    // filesystem blocked for this request, ignore
897
+                } catch (\Exception $e) {
898
+                    // a GC exception should not prevent users from using OC,
899
+                    // so log the exception
900
+                    Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [
901
+                        'app' => 'core',
902
+                        'exception' => $e,
903
+                    ]);
904
+                }
905
+            });
906
+        }
907
+    }
908
+
909
+    private static function registerEncryptionWrapperAndHooks(): void {
910
+        /** @var \OC\Encryption\Manager */
911
+        $manager = Server::get(\OCP\Encryption\IManager::class);
912
+        Server::get(IEventDispatcher::class)->addListener(
913
+            BeforeFileSystemSetupEvent::class,
914
+            $manager->setupStorage(...),
915
+        );
916
+
917
+        $enabled = $manager->isEnabled();
918
+        if ($enabled) {
919
+            \OC\Encryption\EncryptionEventListener::register(Server::get(IEventDispatcher::class));
920
+        }
921
+    }
922
+
923
+    private static function registerAccountHooks(): void {
924
+        /** @var IEventDispatcher $dispatcher */
925
+        $dispatcher = Server::get(IEventDispatcher::class);
926
+        $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
927
+    }
928
+
929
+    private static function registerAppRestrictionsHooks(): void {
930
+        /** @var \OC\Group\Manager $groupManager */
931
+        $groupManager = Server::get(\OCP\IGroupManager::class);
932
+        $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
933
+            $appManager = Server::get(\OCP\App\IAppManager::class);
934
+            $apps = $appManager->getEnabledAppsForGroup($group);
935
+            foreach ($apps as $appId) {
936
+                $restrictions = $appManager->getAppRestriction($appId);
937
+                if (empty($restrictions)) {
938
+                    continue;
939
+                }
940
+                $key = array_search($group->getGID(), $restrictions);
941
+                unset($restrictions[$key]);
942
+                $restrictions = array_values($restrictions);
943
+                if (empty($restrictions)) {
944
+                    $appManager->disableApp($appId);
945
+                } else {
946
+                    $appManager->enableAppForGroups($appId, $restrictions);
947
+                }
948
+            }
949
+        });
950
+    }
951
+
952
+    private static function registerResourceCollectionHooks(): void {
953
+        \OC\Collaboration\Resources\Listener::register(Server::get(IEventDispatcher::class));
954
+    }
955
+
956
+    private static function registerFileReferenceEventListener(): void {
957
+        \OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class));
958
+    }
959
+
960
+    private static function registerRenderReferenceEventListener() {
961
+        \OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class));
962
+    }
963
+
964
+    /**
965
+     * register hooks for sharing
966
+     */
967
+    public static function registerShareHooks(\OC\SystemConfig $systemConfig): void {
968
+        if ($systemConfig->getValue('installed')) {
969
+
970
+            $dispatcher = Server::get(IEventDispatcher::class);
971
+            $dispatcher->addServiceListener(UserRemovedEvent::class, UserRemovedListener::class);
972
+            $dispatcher->addServiceListener(GroupDeletedEvent::class, GroupDeletedListener::class);
973
+            $dispatcher->addServiceListener(UserDeletedEvent::class, UserDeletedListener::class);
974
+        }
975
+    }
976
+
977
+    protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig): void {
978
+        // The class loader takes an optional low-latency cache, which MUST be
979
+        // namespaced. The instanceid is used for namespacing, but might be
980
+        // unavailable at this point. Furthermore, it might not be possible to
981
+        // generate an instanceid via \OC_Util::getInstanceId() because the
982
+        // config file may not be writable. As such, we only register a class
983
+        // loader cache if instanceid is available without trying to create one.
984
+        $instanceId = $systemConfig->getValue('instanceid', null);
985
+        if ($instanceId) {
986
+            try {
987
+                $memcacheFactory = Server::get(\OCP\ICacheFactory::class);
988
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
989
+            } catch (\Exception $ex) {
990
+            }
991
+        }
992
+    }
993
+
994
+    /**
995
+     * Handle the request
996
+     */
997
+    public static function handleRequest(): void {
998
+        Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request');
999
+        $systemConfig = Server::get(\OC\SystemConfig::class);
1000
+
1001
+        // Check if Nextcloud is installed or in maintenance (update) mode
1002
+        if (!$systemConfig->getValue('installed', false)) {
1003
+            \OC::$server->getSession()->clear();
1004
+            $controller = Server::get(\OC\Core\Controller\SetupController::class);
1005
+            $controller->run($_POST);
1006
+            exit();
1007
+        }
1008
+
1009
+        $request = Server::get(IRequest::class);
1010
+        $requestPath = $request->getRawPathInfo();
1011
+        if ($requestPath === '/heartbeat') {
1012
+            return;
1013
+        }
1014
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
1015
+            self::checkMaintenanceMode($systemConfig);
1016
+
1017
+            if (\OCP\Util::needUpgrade()) {
1018
+                if (function_exists('opcache_reset')) {
1019
+                    opcache_reset();
1020
+                }
1021
+                if (!((bool)$systemConfig->getValue('maintenance', false))) {
1022
+                    self::printUpgradePage($systemConfig);
1023
+                    exit();
1024
+                }
1025
+            }
1026
+        }
1027
+
1028
+        $appManager = Server::get(\OCP\App\IAppManager::class);
1029
+
1030
+        // Always load authentication apps
1031
+        $appManager->loadApps(['authentication']);
1032
+        $appManager->loadApps(['extended_authentication']);
1033
+
1034
+        // Load minimum set of apps
1035
+        if (!\OCP\Util::needUpgrade()
1036
+            && !((bool)$systemConfig->getValue('maintenance', false))) {
1037
+            // For logged-in users: Load everything
1038
+            if (Server::get(IUserSession::class)->isLoggedIn()) {
1039
+                $appManager->loadApps();
1040
+            } else {
1041
+                // For guests: Load only filesystem and logging
1042
+                $appManager->loadApps(['filesystem', 'logging']);
1043
+
1044
+                // Don't try to login when a client is trying to get a OAuth token.
1045
+                // OAuth needs to support basic auth too, so the login is not valid
1046
+                // inside Nextcloud and the Login exception would ruin it.
1047
+                if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') {
1048
+                    self::handleLogin($request);
1049
+                }
1050
+            }
1051
+        }
1052
+
1053
+        if (!self::$CLI) {
1054
+            try {
1055
+                if (!\OCP\Util::needUpgrade()) {
1056
+                    $appManager->loadApps(['filesystem', 'logging']);
1057
+                    $appManager->loadApps();
1058
+                }
1059
+                Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo());
1060
+                return;
1061
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1062
+                //header('HTTP/1.0 404 Not Found');
1063
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1064
+                http_response_code(405);
1065
+                return;
1066
+            }
1067
+        }
1068
+
1069
+        // Handle WebDAV
1070
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1071
+            // not allowed any more to prevent people
1072
+            // mounting this root directly.
1073
+            // Users need to mount remote.php/webdav instead.
1074
+            http_response_code(405);
1075
+            return;
1076
+        }
1077
+
1078
+        // Handle requests for JSON or XML
1079
+        $acceptHeader = $request->getHeader('Accept');
1080
+        if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) {
1081
+            http_response_code(404);
1082
+            return;
1083
+        }
1084
+
1085
+        // Handle resources that can't be found
1086
+        // This prevents browsers from redirecting to the default page and then
1087
+        // attempting to parse HTML as CSS and similar.
1088
+        $destinationHeader = $request->getHeader('Sec-Fetch-Dest');
1089
+        if (in_array($destinationHeader, ['font', 'script', 'style'])) {
1090
+            http_response_code(404);
1091
+            return;
1092
+        }
1093
+
1094
+        // Redirect to the default app or login only as an entry point
1095
+        if ($requestPath === '') {
1096
+            // Someone is logged in
1097
+            if (Server::get(IUserSession::class)->isLoggedIn()) {
1098
+                header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl());
1099
+            } else {
1100
+                // Not handled and not logged in
1101
+                header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm'));
1102
+            }
1103
+            return;
1104
+        }
1105
+
1106
+        try {
1107
+            Server::get(\OC\Route\Router::class)->match('/error/404');
1108
+        } catch (\Exception $e) {
1109
+            if (!$e instanceof MethodNotAllowedException) {
1110
+                logger('core')->emergency($e->getMessage(), ['exception' => $e]);
1111
+            }
1112
+            $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
1113
+            Server::get(ITemplateManager::class)->printErrorPage(
1114
+                '404',
1115
+                $l->t('The page could not be found on the server.'),
1116
+                404
1117
+            );
1118
+        }
1119
+    }
1120
+
1121
+    /**
1122
+     * Check login: apache auth, auth token, basic auth
1123
+     */
1124
+    public static function handleLogin(OCP\IRequest $request): bool {
1125
+        if ($request->getHeader('X-Nextcloud-Federation')) {
1126
+            return false;
1127
+        }
1128
+        $userSession = Server::get(\OC\User\Session::class);
1129
+        if (OC_User::handleApacheAuth()) {
1130
+            return true;
1131
+        }
1132
+        if (self::tryAppAPILogin($request)) {
1133
+            return true;
1134
+        }
1135
+        if ($userSession->tryTokenLogin($request)) {
1136
+            return true;
1137
+        }
1138
+        if (isset($_COOKIE['nc_username'])
1139
+            && isset($_COOKIE['nc_token'])
1140
+            && isset($_COOKIE['nc_session_id'])
1141
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1142
+            return true;
1143
+        }
1144
+        if ($userSession->tryBasicAuthLogin($request, Server::get(IThrottler::class))) {
1145
+            return true;
1146
+        }
1147
+        return false;
1148
+    }
1149
+
1150
+    protected static function handleAuthHeaders(): void {
1151
+        //copy http auth headers for apache+php-fcgid work around
1152
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1153
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1154
+        }
1155
+
1156
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1157
+        $vars = [
1158
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1159
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1160
+        ];
1161
+        foreach ($vars as $var) {
1162
+            if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1163
+                $credentials = explode(':', base64_decode($matches[1]), 2);
1164
+                if (count($credentials) === 2) {
1165
+                    $_SERVER['PHP_AUTH_USER'] = $credentials[0];
1166
+                    $_SERVER['PHP_AUTH_PW'] = $credentials[1];
1167
+                    break;
1168
+                }
1169
+            }
1170
+        }
1171
+    }
1172
+
1173
+    protected static function tryAppAPILogin(OCP\IRequest $request): bool {
1174
+        if (!$request->getHeader('AUTHORIZATION-APP-API')) {
1175
+            return false;
1176
+        }
1177
+        $appManager = Server::get(OCP\App\IAppManager::class);
1178
+        if (!$appManager->isEnabledForAnyone('app_api')) {
1179
+            return false;
1180
+        }
1181
+        try {
1182
+            $appAPIService = Server::get(OCA\AppAPI\Service\AppAPIService::class);
1183
+            return $appAPIService->validateExAppRequestToNC($request);
1184
+        } catch (\Psr\Container\NotFoundExceptionInterface|\Psr\Container\ContainerExceptionInterface $e) {
1185
+            return false;
1186
+        }
1187
+    }
1188 1188
 }
1189 1189
 
1190 1190
 OC::init();
Please login to merge, or discard this patch.