@@ -471,6 +471,7 @@ public function fopen($path, $mode) {
471471 $ handle = \OC \Files \Stream \Encryption::wrap ($ source , $ path , $ fullPath , $ header ,
472472 $ this ->uid , $ encryptionModule , $ this ->storage , $ this , $ this ->util , $ this ->fileHelper , $ mode ,
473473 $ size , $ unencryptedSize , $ headerSize , $ signed );
474+
474475 return $ handle ;
475476 }
476477 }
@@ -540,7 +541,7 @@ protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
540541
541542 // if a header exists we skip it
542543 if ($ headerSize > 0 ) {
543- fread ($ stream , $ headerSize );
544+ $ this -> fread_block ($ stream , $ headerSize );
544545 }
545546
546547 // fast path, else the calculation for $lastChunkNr is bogus
@@ -567,7 +568,7 @@ protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
567568 $ count = $ blockSize ;
568569
569570 while ($ count > 0 ) {
570- $ data = fread ($ stream , $ blockSize );
571+ $ data = $ this -> fread_block ($ stream , $ blockSize );
571572 $ count = strlen ($ data );
572573 $ lastChunkContentEncrypted .= $ data ;
573574 if (strlen ($ lastChunkContentEncrypted ) > $ blockSize ) {
@@ -598,6 +599,33 @@ protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
598599 return $ newUnencryptedSize ;
599600 }
600601
602+ /**
603+ * fread_block
604+ *
605+ * This function is a wrapper around the fread function. It is based on the
606+ * stream_read_block function from lib/private/Files/Streams/Encryption.php
607+ * It calls stream read until the requested $blockSize was received or no remaining data is present.
608+ * This is required as stream_read only returns smaller chunks of data when the stream fetches from a
609+ * remote storage over the internet and it does not care about the given $blockSize.
610+ *
611+ * @param handle the stream to read from
612+ * @param int $blockSize Length of requested data block in bytes
613+ * @return string Data fetched from stream.
614+ */
615+ private function fread_block ($ handle , int $ blockSize ): string {
616+ $ remaining = $ blockSize ;
617+ $ data = '' ;
618+
619+ do {
620+ $ chunk = fread ($ handle , $ remaining );
621+ $ chunk_len = strlen ($ chunk );
622+ $ data .= $ chunk ;
623+ $ remaining -= $ chunk_len ;
624+ } while (($ remaining > 0 ) && ($ chunk_len > 0 ));
625+
626+ return $ data ;
627+ }
628+
601629 /**
602630 * @param Storage\IStorage $sourceStorage
603631 * @param string $sourceInternalPath
0 commit comments