FileTest.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
  7. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Robin Appelman <robin@icewind.nl>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. * @author Vincent Petry <vincent@nextcloud.com>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OCA\DAV\Tests\unit\Connector\Sabre;
  31. use OC\AppFramework\Http\Request;
  32. use OC\Files\Filesystem;
  33. use OC\Files\Storage\Local;
  34. use OC\Files\Storage\Temporary;
  35. use OC\Files\Storage\Wrapper\PermissionsMask;
  36. use OC\Files\View;
  37. use OCA\DAV\Connector\Sabre\File;
  38. use OCP\Constants;
  39. use OCP\Files\FileInfo;
  40. use OCP\Files\ForbiddenException;
  41. use OCP\Files\Storage;
  42. use OCP\IConfig;
  43. use OCP\IRequestId;
  44. use OCP\Lock\ILockingProvider;
  45. use PHPUnit\Framework\MockObject\MockObject;
  46. use Test\HookHelper;
  47. use Test\TestCase;
  48. use Test\Traits\MountProviderTrait;
  49. use Test\Traits\UserTrait;
  50. /**
  51. * Class File
  52. *
  53. * @group DB
  54. *
  55. * @package OCA\DAV\Tests\unit\Connector\Sabre
  56. */
  57. class FileTest extends TestCase {
  58. use MountProviderTrait;
  59. use UserTrait;
  60. /**
  61. * @var string
  62. */
  63. private $user;
  64. /** @var IConfig|MockObject */
  65. protected $config;
  66. /** @var IRequestId|MockObject */
  67. protected $requestId;
  68. protected function setUp(): void {
  69. parent::setUp();
  70. unset($_SERVER['HTTP_OC_CHUNKED']);
  71. unset($_SERVER['CONTENT_LENGTH']);
  72. unset($_SERVER['REQUEST_METHOD']);
  73. \OC_Hook::clear();
  74. $this->user = 'test_user';
  75. $this->createUser($this->user, 'pass');
  76. $this->loginAsUser($this->user);
  77. $this->config = $this->createMock(IConfig::class);
  78. $this->requestId = $this->createMock(IRequestId::class);
  79. }
  80. protected function tearDown(): void {
  81. $userManager = \OC::$server->getUserManager();
  82. $userManager->get($this->user)->delete();
  83. unset($_SERVER['HTTP_OC_CHUNKED']);
  84. parent::tearDown();
  85. }
  86. /**
  87. * @return MockObject|Storage
  88. */
  89. private function getMockStorage() {
  90. $storage = $this->getMockBuilder(Storage::class)
  91. ->disableOriginalConstructor()
  92. ->getMock();
  93. $storage->method('getId')
  94. ->willReturn('home::someuser');
  95. return $storage;
  96. }
  97. /**
  98. * @param string $string
  99. */
  100. private function getStream($string) {
  101. $stream = fopen('php://temp', 'r+');
  102. fwrite($stream, $string);
  103. fseek($stream, 0);
  104. return $stream;
  105. }
  106. public function fopenFailuresProvider() {
  107. return [
  108. [
  109. // return false
  110. null,
  111. '\Sabre\Dav\Exception',
  112. false
  113. ],
  114. [
  115. new \OCP\Files\NotPermittedException(),
  116. 'Sabre\DAV\Exception\Forbidden'
  117. ],
  118. [
  119. new \OCP\Files\EntityTooLargeException(),
  120. 'OCA\DAV\Connector\Sabre\Exception\EntityTooLarge'
  121. ],
  122. [
  123. new \OCP\Files\InvalidContentException(),
  124. 'OCA\DAV\Connector\Sabre\Exception\UnsupportedMediaType'
  125. ],
  126. [
  127. new \OCP\Files\InvalidPathException(),
  128. 'Sabre\DAV\Exception\Forbidden'
  129. ],
  130. [
  131. new \OCP\Files\ForbiddenException('', true),
  132. 'OCA\DAV\Connector\Sabre\Exception\Forbidden'
  133. ],
  134. [
  135. new \OCP\Files\LockNotAcquiredException('/test.txt', 1),
  136. 'OCA\DAV\Connector\Sabre\Exception\FileLocked'
  137. ],
  138. [
  139. new \OCP\Lock\LockedException('/test.txt'),
  140. 'OCA\DAV\Connector\Sabre\Exception\FileLocked'
  141. ],
  142. [
  143. new \OCP\Encryption\Exceptions\GenericEncryptionException(),
  144. 'Sabre\DAV\Exception\ServiceUnavailable'
  145. ],
  146. [
  147. new \OCP\Files\StorageNotAvailableException(),
  148. 'Sabre\DAV\Exception\ServiceUnavailable'
  149. ],
  150. [
  151. new \Sabre\DAV\Exception('Generic sabre exception'),
  152. 'Sabre\DAV\Exception',
  153. false
  154. ],
  155. [
  156. new \Exception('Generic exception'),
  157. 'Sabre\DAV\Exception'
  158. ],
  159. ];
  160. }
  161. /**
  162. * @dataProvider fopenFailuresProvider
  163. */
  164. public function testSimplePutFails($thrownException, $expectedException, $checkPreviousClass = true): void {
  165. // setup
  166. $storage = $this->getMockBuilder(Local::class)
  167. ->setMethods(['writeStream'])
  168. ->setConstructorArgs([['datadir' => \OC::$server->getTempManager()->getTemporaryFolder()]])
  169. ->getMock();
  170. \OC\Files\Filesystem::mount($storage, [], $this->user . '/');
  171. /** @var View | MockObject $view */
  172. $view = $this->getMockBuilder(View::class)
  173. ->setMethods(['getRelativePath', 'resolvePath'])
  174. ->getMock();
  175. $view->expects($this->atLeastOnce())
  176. ->method('resolvePath')
  177. ->willReturnCallback(
  178. function ($path) use ($storage) {
  179. return [$storage, $path];
  180. }
  181. );
  182. if ($thrownException !== null) {
  183. $storage->expects($this->once())
  184. ->method('writeStream')
  185. ->will($this->throwException($thrownException));
  186. } else {
  187. $storage->expects($this->once())
  188. ->method('writeStream')
  189. ->willReturn(0);
  190. }
  191. $view->expects($this->any())
  192. ->method('getRelativePath')
  193. ->willReturnArgument(0);
  194. $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [
  195. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  196. 'type' => FileInfo::TYPE_FOLDER,
  197. ], null);
  198. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  199. // action
  200. $caughtException = null;
  201. try {
  202. $file->put('test data');
  203. } catch (\Exception $e) {
  204. $caughtException = $e;
  205. }
  206. $this->assertInstanceOf($expectedException, $caughtException);
  207. if ($checkPreviousClass) {
  208. $this->assertInstanceOf(get_class($thrownException), $caughtException->getPrevious());
  209. }
  210. $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files');
  211. }
  212. /**
  213. * Test putting a file using chunking
  214. *
  215. * @dataProvider fopenFailuresProvider
  216. */
  217. public function testChunkedPutFails($thrownException, $expectedException, $checkPreviousClass = false): void {
  218. // setup
  219. $storage = $this->getMockBuilder(Local::class)
  220. ->setMethods(['fopen'])
  221. ->setConstructorArgs([['datadir' => \OC::$server->getTempManager()->getTemporaryFolder()]])
  222. ->getMock();
  223. \OC\Files\Filesystem::mount($storage, [], $this->user . '/');
  224. $view = $this->getMockBuilder(View::class)
  225. ->setMethods(['getRelativePath', 'resolvePath'])
  226. ->getMock();
  227. $view->expects($this->atLeastOnce())
  228. ->method('resolvePath')
  229. ->willReturnCallback(
  230. function ($path) use ($storage) {
  231. return [$storage, $path];
  232. }
  233. );
  234. if ($thrownException !== null) {
  235. $storage->expects($this->once())
  236. ->method('fopen')
  237. ->will($this->throwException($thrownException));
  238. } else {
  239. $storage->expects($this->once())
  240. ->method('fopen')
  241. ->willReturn(false);
  242. }
  243. $view->expects($this->any())
  244. ->method('getRelativePath')
  245. ->willReturnArgument(0);
  246. $_SERVER['HTTP_OC_CHUNKED'] = true;
  247. $info = new \OC\Files\FileInfo('/test.txt-chunking-12345-2-0', $this->getMockStorage(), null, [
  248. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  249. 'type' => FileInfo::TYPE_FOLDER,
  250. ], null);
  251. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  252. // put first chunk
  253. $file->acquireLock(ILockingProvider::LOCK_SHARED);
  254. $this->assertNull($file->put('test data one'));
  255. $file->releaseLock(ILockingProvider::LOCK_SHARED);
  256. $info = new \OC\Files\FileInfo('/test.txt-chunking-12345-2-1', $this->getMockStorage(), null, [
  257. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  258. 'type' => FileInfo::TYPE_FOLDER,
  259. ], null);
  260. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  261. // action
  262. $caughtException = null;
  263. try {
  264. // last chunk
  265. $file->acquireLock(ILockingProvider::LOCK_SHARED);
  266. $file->put('test data two');
  267. $file->releaseLock(ILockingProvider::LOCK_SHARED);
  268. } catch (\Exception $e) {
  269. $caughtException = $e;
  270. }
  271. $this->assertInstanceOf($expectedException, $caughtException);
  272. if ($checkPreviousClass) {
  273. $this->assertInstanceOf(get_class($thrownException), $caughtException->getPrevious());
  274. }
  275. $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files');
  276. }
  277. /**
  278. * Simulate putting a file to the given path.
  279. *
  280. * @param string $path path to put the file into
  281. * @param string $viewRoot root to use for the view
  282. * @param null|Request $request the HTTP request
  283. *
  284. * @return null|string of the PUT operation which is usually the etag
  285. */
  286. private function doPut($path, $viewRoot = null, Request $request = null) {
  287. $view = \OC\Files\Filesystem::getView();
  288. if (!is_null($viewRoot)) {
  289. $view = new \OC\Files\View($viewRoot);
  290. } else {
  291. $viewRoot = '/' . $this->user . '/files';
  292. }
  293. $info = new \OC\Files\FileInfo(
  294. $viewRoot . '/' . ltrim($path, '/'),
  295. $this->getMockStorage(),
  296. null,
  297. [
  298. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  299. 'type' => FileInfo::TYPE_FOLDER,
  300. ],
  301. null
  302. );
  303. /** @var \OCA\DAV\Connector\Sabre\File | MockObject $file */
  304. $file = $this->getMockBuilder(\OCA\DAV\Connector\Sabre\File::class)
  305. ->setConstructorArgs([$view, $info, null, $request])
  306. ->setMethods(['header'])
  307. ->getMock();
  308. // beforeMethod locks
  309. $view->lockFile($path, ILockingProvider::LOCK_SHARED);
  310. $result = $file->put($this->getStream('test data'));
  311. // afterMethod unlocks
  312. $view->unlockFile($path, ILockingProvider::LOCK_SHARED);
  313. return $result;
  314. }
  315. /**
  316. * Test putting a single file
  317. */
  318. public function testPutSingleFile(): void {
  319. $this->assertNotEmpty($this->doPut('/foo.txt'));
  320. }
  321. public function legalMtimeProvider() {
  322. return [
  323. "string" => [
  324. 'HTTP_X_OC_MTIME' => "string",
  325. 'expected result' => null
  326. ],
  327. "castable string (int)" => [
  328. 'HTTP_X_OC_MTIME' => "987654321",
  329. 'expected result' => 987654321
  330. ],
  331. "castable string (float)" => [
  332. 'HTTP_X_OC_MTIME' => "123456789.56",
  333. 'expected result' => 123456789
  334. ],
  335. "float" => [
  336. 'HTTP_X_OC_MTIME' => 123456789.56,
  337. 'expected result' => 123456789
  338. ],
  339. "zero" => [
  340. 'HTTP_X_OC_MTIME' => 0,
  341. 'expected result' => null
  342. ],
  343. "zero string" => [
  344. 'HTTP_X_OC_MTIME' => "0",
  345. 'expected result' => null
  346. ],
  347. "negative zero string" => [
  348. 'HTTP_X_OC_MTIME' => "-0",
  349. 'expected result' => null
  350. ],
  351. "string starting with number following by char" => [
  352. 'HTTP_X_OC_MTIME' => "2345asdf",
  353. 'expected result' => null
  354. ],
  355. "string castable hex int" => [
  356. 'HTTP_X_OC_MTIME' => "0x45adf",
  357. 'expected result' => null
  358. ],
  359. "string that looks like invalid hex int" => [
  360. 'HTTP_X_OC_MTIME' => "0x123g",
  361. 'expected result' => null
  362. ],
  363. "negative int" => [
  364. 'HTTP_X_OC_MTIME' => -34,
  365. 'expected result' => null
  366. ],
  367. "negative float" => [
  368. 'HTTP_X_OC_MTIME' => -34.43,
  369. 'expected result' => null
  370. ],
  371. ];
  372. }
  373. /**
  374. * Test putting a file with string Mtime
  375. * @dataProvider legalMtimeProvider
  376. */
  377. public function testPutSingleFileLegalMtime($requestMtime, $resultMtime): void {
  378. $request = new Request([
  379. 'server' => [
  380. 'HTTP_X_OC_MTIME' => $requestMtime,
  381. ]
  382. ], $this->requestId, $this->config, null);
  383. $file = 'foo.txt';
  384. if ($resultMtime === null) {
  385. $this->expectException(\InvalidArgumentException::class);
  386. }
  387. $this->doPut($file, null, $request);
  388. if ($resultMtime !== null) {
  389. $this->assertEquals($resultMtime, $this->getFileInfos($file)['mtime']);
  390. }
  391. }
  392. /**
  393. * Test putting a file with string Mtime using chunking
  394. * @dataProvider legalMtimeProvider
  395. */
  396. public function testChunkedPutLegalMtime($requestMtime, $resultMtime): void {
  397. $request = new Request([
  398. 'server' => [
  399. 'HTTP_X_OC_MTIME' => $requestMtime,
  400. ]
  401. ], $this->requestId, $this->config, null);
  402. $_SERVER['HTTP_OC_CHUNKED'] = true;
  403. $file = 'foo.txt';
  404. if ($resultMtime === null) {
  405. $this->expectException(\Sabre\DAV\Exception::class);
  406. }
  407. $this->doPut($file.'-chunking-12345-2-0', null, $request);
  408. $this->doPut($file.'-chunking-12345-2-1', null, $request);
  409. if ($resultMtime !== null) {
  410. $this->assertEquals($resultMtime, $this->getFileInfos($file)['mtime']);
  411. }
  412. }
  413. /**
  414. * Test putting a file using chunking
  415. */
  416. public function testChunkedPut(): void {
  417. $_SERVER['HTTP_OC_CHUNKED'] = true;
  418. $this->assertNull($this->doPut('/test.txt-chunking-12345-2-0'));
  419. $this->assertNotEmpty($this->doPut('/test.txt-chunking-12345-2-1'));
  420. }
  421. /**
  422. * Test that putting a file triggers create hooks
  423. */
  424. public function testPutSingleFileTriggersHooks(): void {
  425. HookHelper::setUpHooks();
  426. $this->assertNotEmpty($this->doPut('/foo.txt'));
  427. $this->assertCount(4, HookHelper::$hookCalls);
  428. $this->assertHookCall(
  429. HookHelper::$hookCalls[0],
  430. Filesystem::signal_create,
  431. '/foo.txt'
  432. );
  433. $this->assertHookCall(
  434. HookHelper::$hookCalls[1],
  435. Filesystem::signal_write,
  436. '/foo.txt'
  437. );
  438. $this->assertHookCall(
  439. HookHelper::$hookCalls[2],
  440. Filesystem::signal_post_create,
  441. '/foo.txt'
  442. );
  443. $this->assertHookCall(
  444. HookHelper::$hookCalls[3],
  445. Filesystem::signal_post_write,
  446. '/foo.txt'
  447. );
  448. }
  449. /**
  450. * Test that putting a file triggers update hooks
  451. */
  452. public function testPutOverwriteFileTriggersHooks(): void {
  453. $view = \OC\Files\Filesystem::getView();
  454. $view->file_put_contents('/foo.txt', 'some content that will be replaced');
  455. HookHelper::setUpHooks();
  456. $this->assertNotEmpty($this->doPut('/foo.txt'));
  457. $this->assertCount(4, HookHelper::$hookCalls);
  458. $this->assertHookCall(
  459. HookHelper::$hookCalls[0],
  460. Filesystem::signal_update,
  461. '/foo.txt'
  462. );
  463. $this->assertHookCall(
  464. HookHelper::$hookCalls[1],
  465. Filesystem::signal_write,
  466. '/foo.txt'
  467. );
  468. $this->assertHookCall(
  469. HookHelper::$hookCalls[2],
  470. Filesystem::signal_post_update,
  471. '/foo.txt'
  472. );
  473. $this->assertHookCall(
  474. HookHelper::$hookCalls[3],
  475. Filesystem::signal_post_write,
  476. '/foo.txt'
  477. );
  478. }
  479. /**
  480. * Test that putting a file triggers hooks with the correct path
  481. * if the passed view was chrooted (can happen with public webdav
  482. * where the root is the share root)
  483. */
  484. public function testPutSingleFileTriggersHooksDifferentRoot(): void {
  485. $view = \OC\Files\Filesystem::getView();
  486. $view->mkdir('noderoot');
  487. HookHelper::setUpHooks();
  488. // happens with public webdav where the view root is the share root
  489. $this->assertNotEmpty($this->doPut('/foo.txt', '/' . $this->user . '/files/noderoot'));
  490. $this->assertCount(4, HookHelper::$hookCalls);
  491. $this->assertHookCall(
  492. HookHelper::$hookCalls[0],
  493. Filesystem::signal_create,
  494. '/noderoot/foo.txt'
  495. );
  496. $this->assertHookCall(
  497. HookHelper::$hookCalls[1],
  498. Filesystem::signal_write,
  499. '/noderoot/foo.txt'
  500. );
  501. $this->assertHookCall(
  502. HookHelper::$hookCalls[2],
  503. Filesystem::signal_post_create,
  504. '/noderoot/foo.txt'
  505. );
  506. $this->assertHookCall(
  507. HookHelper::$hookCalls[3],
  508. Filesystem::signal_post_write,
  509. '/noderoot/foo.txt'
  510. );
  511. }
  512. /**
  513. * Test that putting a file with chunks triggers create hooks
  514. */
  515. public function testPutChunkedFileTriggersHooks(): void {
  516. HookHelper::setUpHooks();
  517. $_SERVER['HTTP_OC_CHUNKED'] = true;
  518. $this->assertNull($this->doPut('/foo.txt-chunking-12345-2-0'));
  519. $this->assertNotEmpty($this->doPut('/foo.txt-chunking-12345-2-1'));
  520. $this->assertCount(4, HookHelper::$hookCalls);
  521. $this->assertHookCall(
  522. HookHelper::$hookCalls[0],
  523. Filesystem::signal_create,
  524. '/foo.txt'
  525. );
  526. $this->assertHookCall(
  527. HookHelper::$hookCalls[1],
  528. Filesystem::signal_write,
  529. '/foo.txt'
  530. );
  531. $this->assertHookCall(
  532. HookHelper::$hookCalls[2],
  533. Filesystem::signal_post_create,
  534. '/foo.txt'
  535. );
  536. $this->assertHookCall(
  537. HookHelper::$hookCalls[3],
  538. Filesystem::signal_post_write,
  539. '/foo.txt'
  540. );
  541. }
  542. /**
  543. * Test that putting a chunked file triggers update hooks
  544. */
  545. public function testPutOverwriteChunkedFileTriggersHooks(): void {
  546. $view = \OC\Files\Filesystem::getView();
  547. $view->file_put_contents('/foo.txt', 'some content that will be replaced');
  548. HookHelper::setUpHooks();
  549. $_SERVER['HTTP_OC_CHUNKED'] = true;
  550. $this->assertNull($this->doPut('/foo.txt-chunking-12345-2-0'));
  551. $this->assertNotEmpty($this->doPut('/foo.txt-chunking-12345-2-1'));
  552. $this->assertCount(4, HookHelper::$hookCalls);
  553. $this->assertHookCall(
  554. HookHelper::$hookCalls[0],
  555. Filesystem::signal_update,
  556. '/foo.txt'
  557. );
  558. $this->assertHookCall(
  559. HookHelper::$hookCalls[1],
  560. Filesystem::signal_write,
  561. '/foo.txt'
  562. );
  563. $this->assertHookCall(
  564. HookHelper::$hookCalls[2],
  565. Filesystem::signal_post_update,
  566. '/foo.txt'
  567. );
  568. $this->assertHookCall(
  569. HookHelper::$hookCalls[3],
  570. Filesystem::signal_post_write,
  571. '/foo.txt'
  572. );
  573. }
  574. public static function cancellingHook($params): void {
  575. self::$hookCalls[] = [
  576. 'signal' => Filesystem::signal_post_create,
  577. 'params' => $params
  578. ];
  579. }
  580. /**
  581. * Test put file with cancelled hook
  582. */
  583. public function testPutSingleFileCancelPreHook(): void {
  584. \OCP\Util::connectHook(
  585. Filesystem::CLASSNAME,
  586. Filesystem::signal_create,
  587. '\Test\HookHelper',
  588. 'cancellingCallback'
  589. );
  590. // action
  591. $thrown = false;
  592. try {
  593. $this->doPut('/foo.txt');
  594. } catch (\Sabre\DAV\Exception $e) {
  595. $thrown = true;
  596. }
  597. $this->assertTrue($thrown);
  598. $this->assertEmpty($this->listPartFiles(), 'No stray part files');
  599. }
  600. /**
  601. * Test exception when the uploaded size did not match
  602. */
  603. public function testSimplePutFailsSizeCheck(): void {
  604. // setup
  605. $view = $this->getMockBuilder(View::class)
  606. ->setMethods(['rename', 'getRelativePath', 'filesize'])
  607. ->getMock();
  608. $view->expects($this->any())
  609. ->method('rename')
  610. ->withAnyParameters()
  611. ->willReturn(false);
  612. $view->expects($this->any())
  613. ->method('getRelativePath')
  614. ->willReturnArgument(0);
  615. $view->expects($this->any())
  616. ->method('filesize')
  617. ->willReturn(123456);
  618. $_SERVER['CONTENT_LENGTH'] = 123456;
  619. $_SERVER['REQUEST_METHOD'] = 'PUT';
  620. $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [
  621. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  622. 'type' => FileInfo::TYPE_FOLDER,
  623. ], null);
  624. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  625. // action
  626. $thrown = false;
  627. try {
  628. // beforeMethod locks
  629. $file->acquireLock(ILockingProvider::LOCK_SHARED);
  630. $file->put($this->getStream('test data'));
  631. // afterMethod unlocks
  632. $file->releaseLock(ILockingProvider::LOCK_SHARED);
  633. } catch (\Sabre\DAV\Exception\BadRequest $e) {
  634. $thrown = true;
  635. }
  636. $this->assertTrue($thrown);
  637. $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files');
  638. }
  639. /**
  640. * Test exception during final rename in simple upload mode
  641. */
  642. public function testSimplePutFailsMoveFromStorage(): void {
  643. $view = new \OC\Files\View('/' . $this->user . '/files');
  644. // simulate situation where the target file is locked
  645. $view->lockFile('/test.txt', ILockingProvider::LOCK_EXCLUSIVE);
  646. $info = new \OC\Files\FileInfo('/' . $this->user . '/files/test.txt', $this->getMockStorage(), null, [
  647. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  648. 'type' => FileInfo::TYPE_FOLDER,
  649. ], null);
  650. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  651. // action
  652. $thrown = false;
  653. try {
  654. // beforeMethod locks
  655. $view->lockFile($info->getPath(), ILockingProvider::LOCK_SHARED);
  656. $file->put($this->getStream('test data'));
  657. // afterMethod unlocks
  658. $view->unlockFile($info->getPath(), ILockingProvider::LOCK_SHARED);
  659. } catch (\OCA\DAV\Connector\Sabre\Exception\FileLocked $e) {
  660. $thrown = true;
  661. }
  662. $this->assertTrue($thrown);
  663. $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files');
  664. }
  665. /**
  666. * Test exception during final rename in chunk upload mode
  667. */
  668. public function testChunkedPutFailsFinalRename(): void {
  669. $view = new \OC\Files\View('/' . $this->user . '/files');
  670. // simulate situation where the target file is locked
  671. $view->lockFile('/test.txt', ILockingProvider::LOCK_EXCLUSIVE);
  672. $_SERVER['HTTP_OC_CHUNKED'] = true;
  673. $info = new \OC\Files\FileInfo('/' . $this->user . '/files/test.txt-chunking-12345-2-0', $this->getMockStorage(), null, [
  674. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  675. 'type' => FileInfo::TYPE_FOLDER,
  676. ], null);
  677. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  678. $file->acquireLock(ILockingProvider::LOCK_SHARED);
  679. $this->assertNull($file->put('test data one'));
  680. $file->releaseLock(ILockingProvider::LOCK_SHARED);
  681. $info = new \OC\Files\FileInfo('/' . $this->user . '/files/test.txt-chunking-12345-2-1', $this->getMockStorage(), null, [
  682. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  683. 'type' => FileInfo::TYPE_FOLDER,
  684. ], null);
  685. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  686. // action
  687. $thrown = false;
  688. try {
  689. $file->acquireLock(ILockingProvider::LOCK_SHARED);
  690. $file->put($this->getStream('test data'));
  691. $file->releaseLock(ILockingProvider::LOCK_SHARED);
  692. } catch (\OCA\DAV\Connector\Sabre\Exception\FileLocked $e) {
  693. $thrown = true;
  694. }
  695. $this->assertTrue($thrown);
  696. $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files');
  697. }
  698. /**
  699. * Test put file with invalid chars
  700. */
  701. public function testSimplePutInvalidChars(): void {
  702. // setup
  703. $view = $this->getMockBuilder(View::class)
  704. ->setMethods(['getRelativePath'])
  705. ->getMock();
  706. $view->expects($this->any())
  707. ->method('getRelativePath')
  708. ->willReturnArgument(0);
  709. $info = new \OC\Files\FileInfo('/*', $this->getMockStorage(), null, [
  710. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  711. 'type' => FileInfo::TYPE_FOLDER,
  712. ], null);
  713. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  714. // action
  715. $thrown = false;
  716. try {
  717. // beforeMethod locks
  718. $view->lockFile($info->getPath(), ILockingProvider::LOCK_SHARED);
  719. $file->put($this->getStream('test data'));
  720. // afterMethod unlocks
  721. $view->unlockFile($info->getPath(), ILockingProvider::LOCK_SHARED);
  722. } catch (\OCA\DAV\Connector\Sabre\Exception\InvalidPath $e) {
  723. $thrown = true;
  724. }
  725. $this->assertTrue($thrown);
  726. $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files');
  727. }
  728. /**
  729. * Test setting name with setName() with invalid chars
  730. *
  731. */
  732. public function testSetNameInvalidChars(): void {
  733. $this->expectException(\OCA\DAV\Connector\Sabre\Exception\InvalidPath::class);
  734. // setup
  735. $view = $this->getMockBuilder(View::class)
  736. ->setMethods(['getRelativePath'])
  737. ->getMock();
  738. $view->expects($this->any())
  739. ->method('getRelativePath')
  740. ->willReturnArgument(0);
  741. $info = new \OC\Files\FileInfo('/*', $this->getMockStorage(), null, [
  742. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  743. 'type' => FileInfo::TYPE_FOLDER,
  744. ], null);
  745. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  746. $file->setName('/super*star.txt');
  747. }
  748. public function testUploadAbort(): void {
  749. // setup
  750. $view = $this->getMockBuilder(View::class)
  751. ->setMethods(['rename', 'getRelativePath', 'filesize'])
  752. ->getMock();
  753. $view->expects($this->any())
  754. ->method('rename')
  755. ->withAnyParameters()
  756. ->willReturn(false);
  757. $view->expects($this->any())
  758. ->method('getRelativePath')
  759. ->willReturnArgument(0);
  760. $view->expects($this->any())
  761. ->method('filesize')
  762. ->willReturn(123456);
  763. $_SERVER['CONTENT_LENGTH'] = 12345;
  764. $_SERVER['REQUEST_METHOD'] = 'PUT';
  765. $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [
  766. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  767. 'type' => FileInfo::TYPE_FOLDER,
  768. ], null);
  769. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  770. // action
  771. $thrown = false;
  772. try {
  773. // beforeMethod locks
  774. $view->lockFile($info->getPath(), ILockingProvider::LOCK_SHARED);
  775. $file->put($this->getStream('test data'));
  776. // afterMethod unlocks
  777. $view->unlockFile($info->getPath(), ILockingProvider::LOCK_SHARED);
  778. } catch (\Sabre\DAV\Exception\BadRequest $e) {
  779. $thrown = true;
  780. }
  781. $this->assertTrue($thrown);
  782. $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files');
  783. }
  784. public function testDeleteWhenAllowed(): void {
  785. // setup
  786. $view = $this->getMockBuilder(View::class)
  787. ->getMock();
  788. $view->expects($this->once())
  789. ->method('unlink')
  790. ->willReturn(true);
  791. $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [
  792. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  793. 'type' => FileInfo::TYPE_FOLDER,
  794. ], null);
  795. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  796. // action
  797. $file->delete();
  798. }
  799. public function testDeleteThrowsWhenDeletionNotAllowed(): void {
  800. $this->expectException(\Sabre\DAV\Exception\Forbidden::class);
  801. // setup
  802. $view = $this->getMockBuilder(View::class)
  803. ->getMock();
  804. $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [
  805. 'permissions' => 0,
  806. 'type' => FileInfo::TYPE_FOLDER,
  807. ], null);
  808. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  809. // action
  810. $file->delete();
  811. }
  812. public function testDeleteThrowsWhenDeletionFailed(): void {
  813. $this->expectException(\Sabre\DAV\Exception\Forbidden::class);
  814. // setup
  815. $view = $this->getMockBuilder(View::class)
  816. ->getMock();
  817. // but fails
  818. $view->expects($this->once())
  819. ->method('unlink')
  820. ->willReturn(false);
  821. $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [
  822. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  823. 'type' => FileInfo::TYPE_FOLDER,
  824. ], null);
  825. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  826. // action
  827. $file->delete();
  828. }
  829. public function testDeleteThrowsWhenDeletionThrows(): void {
  830. $this->expectException(\OCA\DAV\Connector\Sabre\Exception\Forbidden::class);
  831. // setup
  832. $view = $this->getMockBuilder(View::class)
  833. ->getMock();
  834. // but fails
  835. $view->expects($this->once())
  836. ->method('unlink')
  837. ->willThrowException(new ForbiddenException('', true));
  838. $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [
  839. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  840. 'type' => FileInfo::TYPE_FOLDER,
  841. ], null);
  842. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  843. // action
  844. $file->delete();
  845. }
  846. /**
  847. * Asserts hook call
  848. *
  849. * @param array $callData hook call data to check
  850. * @param string $signal signal name
  851. * @param string $hookPath hook path
  852. */
  853. protected function assertHookCall($callData, $signal, $hookPath) {
  854. $this->assertEquals($signal, $callData['signal']);
  855. $params = $callData['params'];
  856. $this->assertEquals(
  857. $hookPath,
  858. $params[Filesystem::signal_param_path]
  859. );
  860. }
  861. /**
  862. * Test whether locks are set before and after the operation
  863. */
  864. public function testPutLocking(): void {
  865. $view = new \OC\Files\View('/' . $this->user . '/files/');
  866. $path = 'test-locking.txt';
  867. $info = new \OC\Files\FileInfo(
  868. '/' . $this->user . '/files/' . $path,
  869. $this->getMockStorage(),
  870. null,
  871. [
  872. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  873. 'type' => FileInfo::TYPE_FOLDER,
  874. ],
  875. null
  876. );
  877. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  878. $this->assertFalse(
  879. $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_SHARED),
  880. 'File unlocked before put'
  881. );
  882. $this->assertFalse(
  883. $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE),
  884. 'File unlocked before put'
  885. );
  886. $wasLockedPre = false;
  887. $wasLockedPost = false;
  888. $eventHandler = $this->getMockBuilder(\stdclass::class)
  889. ->setMethods(['writeCallback', 'postWriteCallback'])
  890. ->getMock();
  891. // both pre and post hooks might need access to the file,
  892. // so only shared lock is acceptable
  893. $eventHandler->expects($this->once())
  894. ->method('writeCallback')
  895. ->willReturnCallback(
  896. function () use ($view, $path, &$wasLockedPre): void {
  897. $wasLockedPre = $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_SHARED);
  898. $wasLockedPre = $wasLockedPre && !$this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE);
  899. }
  900. );
  901. $eventHandler->expects($this->once())
  902. ->method('postWriteCallback')
  903. ->willReturnCallback(
  904. function () use ($view, $path, &$wasLockedPost): void {
  905. $wasLockedPost = $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_SHARED);
  906. $wasLockedPost = $wasLockedPost && !$this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE);
  907. }
  908. );
  909. \OCP\Util::connectHook(
  910. Filesystem::CLASSNAME,
  911. Filesystem::signal_write,
  912. $eventHandler,
  913. 'writeCallback'
  914. );
  915. \OCP\Util::connectHook(
  916. Filesystem::CLASSNAME,
  917. Filesystem::signal_post_write,
  918. $eventHandler,
  919. 'postWriteCallback'
  920. );
  921. // beforeMethod locks
  922. $view->lockFile($path, ILockingProvider::LOCK_SHARED);
  923. $this->assertNotEmpty($file->put($this->getStream('test data')));
  924. // afterMethod unlocks
  925. $view->unlockFile($path, ILockingProvider::LOCK_SHARED);
  926. $this->assertTrue($wasLockedPre, 'File was locked during pre-hooks');
  927. $this->assertTrue($wasLockedPost, 'File was locked during post-hooks');
  928. $this->assertFalse(
  929. $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_SHARED),
  930. 'File unlocked after put'
  931. );
  932. $this->assertFalse(
  933. $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE),
  934. 'File unlocked after put'
  935. );
  936. }
  937. /**
  938. * Returns part files in the given path
  939. *
  940. * @param \OC\Files\View view which root is the current user's "files" folder
  941. * @param string $path path for which to list part files
  942. *
  943. * @return array list of part files
  944. */
  945. private function listPartFiles(\OC\Files\View $userView = null, $path = '') {
  946. if ($userView === null) {
  947. $userView = \OC\Files\Filesystem::getView();
  948. }
  949. $files = [];
  950. [$storage, $internalPath] = $userView->resolvePath($path);
  951. if ($storage instanceof Local) {
  952. $realPath = $storage->getSourcePath($internalPath);
  953. $dh = opendir($realPath);
  954. while (($file = readdir($dh)) !== false) {
  955. if (substr($file, strlen($file) - 5, 5) === '.part') {
  956. $files[] = $file;
  957. }
  958. }
  959. closedir($dh);
  960. }
  961. return $files;
  962. }
  963. /**
  964. * returns an array of file information filesize, mtime, filetype, mimetype
  965. *
  966. * @param string $path
  967. * @param View $userView
  968. * @return array
  969. */
  970. private function getFileInfos($path = '', View $userView = null) {
  971. if ($userView === null) {
  972. $userView = Filesystem::getView();
  973. }
  974. return [
  975. "filesize" => $userView->filesize($path),
  976. "mtime" => $userView->filemtime($path),
  977. "filetype" => $userView->filetype($path),
  978. "mimetype" => $userView->getMimeType($path)
  979. ];
  980. }
  981. public function testGetFopenFails(): void {
  982. $this->expectException(\Sabre\DAV\Exception\ServiceUnavailable::class);
  983. $view = $this->getMockBuilder(View::class)
  984. ->setMethods(['fopen'])
  985. ->getMock();
  986. $view->expects($this->atLeastOnce())
  987. ->method('fopen')
  988. ->willReturn(false);
  989. $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [
  990. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  991. 'type' => FileInfo::TYPE_FILE,
  992. ], null);
  993. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  994. $file->get();
  995. }
  996. public function testGetFopenThrows(): void {
  997. $this->expectException(\OCA\DAV\Connector\Sabre\Exception\Forbidden::class);
  998. $view = $this->getMockBuilder(View::class)
  999. ->setMethods(['fopen'])
  1000. ->getMock();
  1001. $view->expects($this->atLeastOnce())
  1002. ->method('fopen')
  1003. ->willThrowException(new ForbiddenException('', true));
  1004. $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [
  1005. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  1006. 'type' => FileInfo::TYPE_FILE,
  1007. ], null);
  1008. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  1009. $file->get();
  1010. }
  1011. public function testGetThrowsIfNoPermission(): void {
  1012. $this->expectException(\Sabre\DAV\Exception\NotFound::class);
  1013. $view = $this->getMockBuilder(View::class)
  1014. ->setMethods(['fopen'])
  1015. ->getMock();
  1016. $view->expects($this->never())
  1017. ->method('fopen');
  1018. $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [
  1019. 'permissions' => \OCP\Constants::PERMISSION_CREATE, // no read perm
  1020. 'type' => FileInfo::TYPE_FOLDER,
  1021. ], null);
  1022. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  1023. $file->get();
  1024. }
  1025. public function testSimplePutNoCreatePermissions(): void {
  1026. $this->logout();
  1027. $storage = new Temporary([]);
  1028. $storage->file_put_contents('file.txt', 'old content');
  1029. $noCreateStorage = new PermissionsMask([
  1030. 'storage' => $storage,
  1031. 'mask' => Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE
  1032. ]);
  1033. $this->registerMount($this->user, $noCreateStorage, '/' . $this->user . '/files/root');
  1034. $this->loginAsUser($this->user);
  1035. $view = new View('/' . $this->user . '/files');
  1036. $info = $view->getFileInfo('root/file.txt');
  1037. $file = new File($view, $info);
  1038. // beforeMethod locks
  1039. $view->lockFile('root/file.txt', ILockingProvider::LOCK_SHARED);
  1040. $file->put($this->getStream('new content'));
  1041. // afterMethod unlocks
  1042. $view->unlockFile('root/file.txt', ILockingProvider::LOCK_SHARED);
  1043. $this->assertEquals('new content', $view->file_get_contents('root/file.txt'));
  1044. }
  1045. public function testPutLockExpired(): void {
  1046. $view = new \OC\Files\View('/' . $this->user . '/files/');
  1047. $path = 'test-locking.txt';
  1048. $info = new \OC\Files\FileInfo(
  1049. '/' . $this->user . '/files/' . $path,
  1050. $this->getMockStorage(),
  1051. null,
  1052. [
  1053. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  1054. 'type' => FileInfo::TYPE_FOLDER,
  1055. ],
  1056. null
  1057. );
  1058. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  1059. // don't lock before the PUT to simulate an expired shared lock
  1060. $this->assertNotEmpty($file->put($this->getStream('test data')));
  1061. // afterMethod unlocks
  1062. $view->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1063. }
  1064. }