<commit_before><?php
/**
 * ownCloud
 *
 * @author <NAME>
 * @copyright 2012 <NAME> <<EMAIL>>, 2011 <NAME>
 * <<EMAIL>>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/**
 * transparently encrypted filestream
 *
 * you can use it as wrapper around an existing stream by setting CryptStream::$sourceStreams['foo']=array('path'=>$path,'stream'=>$stream)
 * and then fopen('crypt://streams/foo');
 */

namespace OCA\Encryption;

/**
 * @brief Provides 'crypt://' stream wrapper protocol.
 * @note We use a stream wrapper because it is the most secure way to handle
 * decrypted content transfers. There is no safe way to decrypt the entire file
 * somewhere on the server, so we have to encrypt and decrypt blocks on the fly.
 * @note Paths used with this protocol MUST BE RELATIVE. Use URLs like:
 * crypt://filename, or crypt://subdirectory/filename, NOT
 * crypt:///home/user/owncloud/data. Otherwise keyfiles will be put in
 * [owncloud]/data/user/files_encryption/keyfiles/home/user/owncloud/data and
 * will not be accessible to other methods.
 * @note Data read and written must always be 8192 bytes long, as this is the
 * buffer size used internally by PHP. The encryption process makes the input
 * data longer, and input is chunked into smaller pieces in order to result in
 * a 8192 encrypted block size.
 * @note When files are deleted via webdav, or when they are updated and the
 * previous version deleted, this is handled by OC\Files\View, and thus the
 * encryption proxies are used and keyfiles deleted.
 */
class Stream {
	private $plainKey;
	private $encKeyfiles;

	private $rawPath; // The raw path relative to the data dir
	private $relPath; // rel path to users file dir
	private $userId;
	private $keyId;
	private $handle; // Resource returned by fopen
	private $meta = array(); // Header / meta for source stream
	private $writeCache;
	private $size;
	private $unencryptedSize;
	private $publicKey;
	private $encKeyfile;
	private $newFile; // helper var, we only need to write the keyfile for new files
	/**
	 * @var \OC\Files\View
	 */
	private $rootView; // a fsview object set to '/'

	/**
	 * @var \OCA\Encryption\Session
	 */
	private $session;
	private $privateKey;

	/**
	 * @param $path raw path relative to data/
	 * @param $mode
	 * @param $options
	 * @param $opened_path
	 * @return bool
	 */
	public function stream_open($path, $mode, $options, &$opened_path) {

		// assume that the file already exist before we decide it finally in getKey()
		$this->newFile = false;

		if (!isset($this->rootView)) {
			$this->rootView = new \OC_FilesystemView('/');
		}


		$this->session = new \OCA\Encryption\Session($this->rootView);

		$this->privateKey = $this->session->getPrivateKey();

		// rawPath is relative to the data directory
		$this->rawPath = \OC\Files\Filesystem::normalizePath(str_replace('crypt://', '', $path));

		$this->userId = Helper::getUser($this->rawPath);

		$util = new Util($this->rootView, $this->userId);

		// get the key ID which we want to use, can be the users key or the
		// public share key
		$this->keyId = $util->getKeyId();

		// Strip identifier text from path, this gives us the path relative to data/<user>/files
		$this->relPath = Helper::stripUserFilesPath($this->rawPath);
		// if raw path doesn't point to a real file, check if it is a version or a file in the trash bin
		if ($this->relPath === false) {
			$this->relPath = Helper::getPathToRealFile($this->rawPath);
		}

		if($this->relPath === false) {
			\OCP\Util::writeLog('Encryption library', 'failed to open file "' . $this->rawPath . '" expecting a path to "files", "files_versions" or "cache"', \OCP\Util::ERROR);
			return false;
		}

		// Disable fileproxies so we can get the file size and open the source file without recursive encryption
		$proxyStatus = \OC_FileProxy::$enabled;
		\OC_FileProxy::$enabled = false;

		if (
			$mode === 'w'
			or $mode === 'w+'
			or $mode === 'wb'
			or $mode === 'wb+'
		) {

			// We're writing a new file so start write counter with 0 bytes
			$this->size = 0;
			$this->unencryptedSize = 0;

		} else {

			if($this->privateKey === false) {
				// if private key is not valid redirect user to a error page
				\OCA\Encryption\Helper::redirectToErrorPage($this->session);
			}

			$this->size = $this->rootView->filesize($this->rawPath, $mode);
		}

		$this->handle = $this->rootView->fopen($this->rawPath, $mode);

		\OC_FileProxy::$enabled = $proxyStatus;

		if (!is_resource($this->handle)) {

			\OCP\Util::writeLog('Encryption library', 'failed to open file "' . $this->rawPath . '"', \OCP\Util::ERROR);

		} else {

			$this->meta = stream_get_meta_data($this->handle);

		}


		return is_resource($this->handle);

	}

	/**
	 * @param $offset
	 * @param int $whence
	 */
	public function stream_seek($offset, $whence = SEEK_SET) {

		$this->flush();

		fseek($this->handle, $offset, $whence);

	}

	/**
	 * @param $count
	 * @return bool|string
	 * @throws \Exception
	 */
	public function stream_read($count) {

		$this->writeCache = '';

		if ($count !== 8192) {

			// $count will always be 8192 https://bugs.php.net/bug.php?id=21641
			// This makes this function a lot simpler, but will break this class if the above 'bug' gets 'fixed'
			\OCP\Util::writeLog('Encryption library', 'PHP "bug" 21641 no longer holds, decryption system requires refactoring', \OCP\Util::FATAL);

			die();<commit_msg>implement ftell stream wrapper and fix return value from fseek stream wrapper<commit_after><?php
/**
 * ownCloud
 *
 * @author <NAME>
 * @copyright 2012 <NAME> <<EMAIL>>, 2011 <NAME>
 * <<EMAIL>>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/**
 * transparently encrypted filestream
 *
 * you can use it as wrapper around an existing stream by setting CryptStream::$sourceStreams['foo']=array('path'=>$path,'stream'=>$stream)
 * and then fopen('crypt://streams/foo');
 */

namespace OCA\Encryption;

/**
 * @brief Provides 'crypt://' stream wrapper protocol.
 * @note We use a stream wrapper because it is the most secure way to handle
 * decrypted content transfers. There is no safe way to decrypt the entire file
 * somewhere on the server, so we have to encrypt and decrypt blocks on the fly.
 * @note Paths used with this protocol MUST BE RELATIVE. Use URLs like:
 * crypt://filename, or crypt://subdirectory/filename, NOT
 * crypt:///home/user/owncloud/data. Otherwise keyfiles will be put in
 * [owncloud]/data/user/files_encryption/keyfiles/home/user/owncloud/data and
 * will not be accessible to other methods.
 * @note Data read and written must always be 8192 bytes long, as this is the
 * buffer size used internally by PHP. The encryption process makes the input
 * data longer, and input is chunked into smaller pieces in order to result in
 * a 8192 encrypted block size.
 * @note When files are deleted via webdav, or when they are updated and the
 * previous version deleted, this is handled by OC\Files\View, and thus the
 * encryption proxies are used and keyfiles deleted.
 */
class Stream {
	private $plainKey;
	private $encKeyfiles;

	private $rawPath; // The raw path relative to the data dir
	private $relPath; // rel path to users file dir
	private $userId;
	private $keyId;
	private $handle; // Resource returned by fopen
	private $meta = array(); // Header / meta for source stream
	private $writeCache;
	private $size;
	private $unencryptedSize;
	private $publicKey;
	private $encKeyfile;
	private $newFile; // helper var, we only need to write the keyfile for new files
	/**
	 * @var \OC\Files\View
	 */
	private $rootView; // a fsview object set to '/'

	/**
	 * @var \OCA\Encryption\Session
	 */
	private $session;
	private $privateKey;

	/**
	 * @param $path raw path relative to data/
	 * @param $mode
	 * @param $options
	 * @param $opened_path
	 * @return bool
	 */
	public function stream_open($path, $mode, $options, &$opened_path) {

		// assume that the file already exist before we decide it finally in getKey()
		$this->newFile = false;

		if (!isset($this->rootView)) {
			$this->rootView = new \OC_FilesystemView('/');
		}


		$this->session = new \OCA\Encryption\Session($this->rootView);

		$this->privateKey = $this->session->getPrivateKey();

		// rawPath is relative to the data directory
		$this->rawPath = \OC\Files\Filesystem::normalizePath(str_replace('crypt://', '', $path));

		$this->userId = Helper::getUser($this->rawPath);

		$util = new Util($this->rootView, $this->userId);

		// get the key ID which we want to use, can be the users key or the
		// public share key
		$this->keyId = $util->getKeyId();

		// Strip identifier text from path, this gives us the path relative to data/<user>/files
		$this->relPath = Helper::stripUserFilesPath($this->rawPath);
		// if raw path doesn't point to a real file, check if it is a version or a file in the trash bin
		if ($this->relPath === false) {
			$this->relPath = Helper::getPathToRealFile($this->rawPath);
		}

		if($this->relPath === false) {
			\OCP\Util::writeLog('Encryption library', 'failed to open file "' . $this->rawPath . '" expecting a path to "files", "files_versions" or "cache"', \OCP\Util::ERROR);
			return false;
		}

		// Disable fileproxies so we can get the file size and open the source file without recursive encryption
		$proxyStatus = \OC_FileProxy::$enabled;
		\OC_FileProxy::$enabled = false;

		if (
			$mode === 'w'
			or $mode === 'w+'
			or $mode === 'wb'
			or $mode === 'wb+'
		) {

			// We're writing a new file so start write counter with 0 bytes
			$this->size = 0;
			$this->unencryptedSize = 0;

		} else {

			if($this->privateKey === false) {
				// if private key is not valid redirect user to a error page
				\OCA\Encryption\Helper::redirectToErrorPage($this->session);
			}

			$this->size = $this->rootView->filesize($this->rawPath, $mode);
		}

		$this->handle = $this->rootView->fopen($this->rawPath, $mode);

		\OC_FileProxy::$enabled = $proxyStatus;

		if (!is_resource($this->handle)) {

			\OCP\Util::writeLog('Encryption library', 'failed to open file "' . $this->rawPath . '"', \OCP\Util::ERROR);

		} else {

			$this->meta = stream_get_meta_data($this->handle);

		}


		return is_resource($this->handle);

	}

	/**
	 * @brief Returns the current position of the file pointer
	 * @return int  position of the file pointer
	 */
	public function stream_tell() {
		return ftell($this->handle);
	}

	/**
	 * @param $offset
	 * @param int $whence
	 * @return bool true if fseek was successful, otherwise false
	 */
	public function stream_seek($offset, $whence = SEEK_SET) {

		$this->flush();

		// this wrapper needs to return "true" for success.
		// the fseek call itself returns 0 on succeess
		return !fseek($this->handle, $offset, $whence);

	}

	/**
	 * @param $count
	 * @return bool|string
	 * @throws \Exception
	 */
	public function stream_read($count) {

		$this->writeCache = '';

		if ($count !== 8192) {

			// $count will always be 8192 https://bugs.php.net/bug.php?id=21641
			// This makes this function a lot simpler, but will break this class if the above 'bug' gets 'fixed'
			\OCP\Util::writeLog('Encryption library', 'PHP "bug" 21641 no longer holds, decryption system requires refactoring', \OCP\Util::FATAL);

			die();
{'fraction_non_alphanumeric': 0.12884027666076886, 'fraction_numerical': 0.006192697442496381, 'mean_word_length': 3.620958751393534, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 110, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1867309', 'n_tokens_mistral': 4108, 'n_tokens_neox': 3722, 'n_words': 1397}