file.php 11.6 KB
Newer Older
Jakob Sack's avatar
Jakob Sack committed
1
<?php
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * ownCloud
 *
 * @author Jakob Sack
 * @copyright 2011 Jakob Sack kde@jakobsack.de
 *
 * 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/>.
 *
 */

Vincent Petry's avatar
Vincent Petry committed
23
24
25
namespace OC\Connector\Sabre;

class File extends \OC\Connector\Sabre\Node implements \Sabre\DAV\IFile {
Jakob Sack's avatar
Jakob Sack committed
26
27
28
29

	/**
	 * Updates the data
	 *
30
31
	 * The data argument is a readable stream resource.
	 *
32
	 * After a successful put operation, you may choose to return an ETag. The
33
34
35
36
37
38
39
40
41
42
43
	 * etag must always be surrounded by double-quotes. These quotes must
	 * appear in the actual string you're returning.
	 *
	 * Clients may use the ETag from a PUT request to later on make sure that
	 * when they update the file, the contents haven't changed in the mean
	 * time.
	 *
	 * If you don't plan to store the file byte-by-byte, and you return a
	 * different object on a subsequent GET you are strongly recommended to not
	 * return an ETag, and just return null.
	 *
Jakob Sack's avatar
Jakob Sack committed
44
	 * @param resource $data
Vincent Petry's avatar
Vincent Petry committed
45
	 *
Thomas Müller's avatar
Thomas Müller committed
46
	 * @throws \Sabre\DAV\Exception\Forbidden
Vincent Petry's avatar
Vincent Petry committed
47
	 * @throws \OC\Connector\Sabre\Exception\UnsupportedMediaType
Thomas Müller's avatar
Thomas Müller committed
48
49
	 * @throws \Sabre\DAV\Exception\BadRequest
	 * @throws \Sabre\DAV\Exception
Vincent Petry's avatar
Vincent Petry committed
50
	 * @throws \OC\Connector\Sabre\Exception\EntityTooLarge
Thomas Müller's avatar
Thomas Müller committed
51
	 * @throws \Sabre\DAV\Exception\ServiceUnavailable
52
	 * @return string|null
Jakob Sack's avatar
Jakob Sack committed
53
54
	 */
	public function put($data) {
55
56
57
58
59
60
		try {
			if ($this->info && $this->fileView->file_exists($this->path) &&
				!$this->info->isUpdateable()) {
				throw new \Sabre\DAV\Exception\Forbidden();
			}
		} catch (\OCP\Files\StorageNotAvailableException $e) {
61
			throw new \Sabre\DAV\Exception\ServiceUnavailable("File is not updatable: ".$e->getMessage());
62
63
		}

64
65
		// throw an exception if encryption was disabled but the files are still encrypted
		if (\OC_Util::encryptedFiles()) {
66
			throw new \Sabre\DAV\Exception\ServiceUnavailable("Encryption is disabled");
67
		}
Thomas Müller's avatar
Thomas Müller committed
68

69
70
		// verify path of the target
		$this->verifyPath();
71

Thomas Müller's avatar
Thomas Müller committed
72
73
		// chunked handling
		if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
74
			return $this->createFileChunked($data);
Thomas Müller's avatar
Thomas Müller committed
75
76
		}

77
		list($storage) = $this->fileView->resolvePath($this->path);
78
		$needsPartFile = $this->needsPartFile($storage) && (strlen($this->path) > 1);
79
80
81
82
83
84
85
86

		if ($needsPartFile) {
			// mark file as partial while uploading (ignored by the scanner)
			$partFilePath = $this->path . '.ocTransferId' . rand() . '.part';
		} else {
			// upload file directly as the final path
			$partFilePath = $this->path;
		}
Bart Visscher's avatar
Bart Visscher committed
87

88
		try {
89
			$putOkay = $this->fileView->file_put_contents($partFilePath, $data);
90
91
			if ($putOkay === false) {
				\OC_Log::write('webdav', '\OC\Files\Filesystem::file_put_contents() failed', \OC_Log::ERROR);
92
				$this->fileView->unlink($partFilePath);
93
				// because we have no clue about the cause we can only throw back a 500/Internal Server Error
Thomas Müller's avatar
Thomas Müller committed
94
				throw new \Sabre\DAV\Exception('Could not write file contents');
95
96
			}
		} catch (\OCP\Files\NotPermittedException $e) {
97
			// a more general case - due to whatever reason the content could not be written
Thomas Müller's avatar
Thomas Müller committed
98
			throw new \Sabre\DAV\Exception\Forbidden($e->getMessage());
99

100
		} catch (\OCP\Files\EntityTooLargeException $e) {
101
			// the file is too big to be stored
Vincent Petry's avatar
Vincent Petry committed
102
			throw new \OC\Connector\Sabre\Exception\EntityTooLarge($e->getMessage());
103

104
		} catch (\OCP\Files\InvalidContentException $e) {
105
			// the file content is not permitted
Vincent Petry's avatar
Vincent Petry committed
106
			throw new \OC\Connector\Sabre\Exception\UnsupportedMediaType($e->getMessage());
107

108
		} catch (\OCP\Files\InvalidPathException $e) {
109
110
			// the path for the file was not valid
			// TODO: find proper http status code for this case
Thomas Müller's avatar
Thomas Müller committed
111
			throw new \Sabre\DAV\Exception\Forbidden($e->getMessage());
112
113
		} catch (\OCP\Files\LockNotAcquiredException $e) {
			// the file is currently being written to by another process
Vincent Petry's avatar
Vincent Petry committed
114
			throw new \OC\Connector\Sabre\Exception\FileLocked($e->getMessage(), $e->getCode(), $e);
115
		} catch (\OCA\Files_Encryption\Exception\EncryptionException $e) {
116
			throw new \Sabre\DAV\Exception\Forbidden($e->getMessage());
117
		} catch (\OCP\Files\StorageNotAvailableException $e) {
118
			throw new \Sabre\DAV\Exception\ServiceUnavailable("Failed to write file contents: ".$e->getMessage());
119
		}
Bart Visscher's avatar
Bart Visscher committed
120

121
122
123
124
125
126
127
128
129
130
131
		try {
			// if content length is sent by client:
			// double check if the file was fully received
			// compare expected and actual size
			if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['REQUEST_METHOD'] !== 'LOCK') {
				$expected = $_SERVER['CONTENT_LENGTH'];
				$actual = $this->fileView->filesize($partFilePath);
				if ($actual != $expected) {
					$this->fileView->unlink($partFilePath);
					throw new \Sabre\DAV\Exception\BadRequest('expected filesize ' . $expected . ' got ' . $actual);
				}
132
			}
133

134
135
136
137
138
139
140
141
142
143
144
145
146
			if ($needsPartFile) {
				// rename to correct path
				try {
					$renameOkay = $this->fileView->rename($partFilePath, $this->path);
					$fileExists = $this->fileView->file_exists($this->path);
					if ($renameOkay === false || $fileExists === false) {
						\OC_Log::write('webdav', '\OC\Files\Filesystem::rename() failed', \OC_Log::ERROR);
						$this->fileView->unlink($partFilePath);
						throw new \Sabre\DAV\Exception('Could not rename part file to final file');
					}
				}
				catch (\OCP\Files\LockNotAcquiredException $e) {
					// the file is currently being written to by another process
Vincent Petry's avatar
Vincent Petry committed
147
					throw new \OC\Connector\Sabre\Exception\FileLocked($e->getMessage(), $e->getCode(), $e);
148
				}
149
			}
Bart Visscher's avatar
Bart Visscher committed
150

151
			// allow sync clients to send the mtime along in a header
152
153
154
			$request = \OC::$server->getRequest();
			if (isset($request->server['HTTP_X_OC_MTIME'])) {
				if($this->fileView->touch($this->path, $request->server['HTTP_X_OC_MTIME'])) {
155
156
					header('X-OC-MTime: accepted');
				}
157
			}
158
159
			$this->refreshInfo();
		} catch (\OCP\Files\StorageNotAvailableException $e) {
160
			throw new \Sabre\DAV\Exception\ServiceUnavailable("Failed to check file size: ".$e->getMessage());
161
		}
Jakob Sack's avatar
Jakob Sack committed
162

163
		return '"' . $this->info->getEtag() . '"';
Jakob Sack's avatar
Jakob Sack committed
164
165
166
167
	}

	/**
	 * Returns the data
168
	 * @return string|resource
169
170
	 * @throws \Sabre\DAV\Exception\Forbidden
	 * @throws \Sabre\DAV\Exception\ServiceUnavailable
Jakob Sack's avatar
Jakob Sack committed
171
172
173
	 */
	public function get() {

Thomas Müller's avatar
Thomas Müller committed
174
		//throw exception if encryption is disabled but files are still encrypted
175
		if (\OC_Util::encryptedFiles()) {
176
			throw new \Sabre\DAV\Exception\ServiceUnavailable("Encryption is disabled");
177
		} else {
178
179
			try {
				return $this->fileView->fopen(ltrim($this->path, '/'), 'rb');
180
			} catch (\OCA\Files_Encryption\Exception\EncryptionException $e) {
181
				throw new \Sabre\DAV\Exception\Forbidden($e->getMessage());
182
			} catch (\OCP\Files\StorageNotAvailableException $e) {
183
				throw new \Sabre\DAV\Exception\ServiceUnavailable("Failed to open file: ".$e->getMessage());
184
			}
185
		}
Jakob Sack's avatar
Jakob Sack committed
186
187
188
189
190

	}

	/**
	 * Delete the current file
Thomas Müller's avatar
Thomas Müller committed
191
	 * @throws \Sabre\DAV\Exception\Forbidden
192
	 * @throws \Sabre\DAV\Exception\ServiceUnavailable
Jakob Sack's avatar
Jakob Sack committed
193
194
	 */
	public function delete() {
195
		if (!$this->info->isDeletable()) {
Thomas Müller's avatar
Thomas Müller committed
196
			throw new \Sabre\DAV\Exception\Forbidden();
197
		}
198

199
200
201
202
203
204
		try {
			if (!$this->fileView->unlink($this->path)) {
				// assume it wasn't possible to delete due to permissions
				throw new \Sabre\DAV\Exception\Forbidden();
			}
		} catch (\OCP\Files\StorageNotAvailableException $e) {
205
			throw new \Sabre\DAV\Exception\ServiceUnavailable("Failed to unlink: ".$e->getMessage());
206
		}
Vincent Petry's avatar
Vincent Petry committed
207
208
	}

Jakob Sack's avatar
Jakob Sack committed
209
210
211
212
213
214
215
216
	/**
	 * Returns the mime-type for a file
	 *
	 * If null is returned, we'll assume application/octet-stream
	 *
	 * @return mixed
	 */
	public function getContentType() {
217
		$mimeType = $this->info->getMimetype();
Jakob Sack's avatar
Jakob Sack committed
218

219
220
221
222
		// PROPFIND needs to return the correct mime type, for consistency with the web UI
		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND' ) {
			return $mimeType;
		}
223
		return \OC_Helper::getSecureMimeType($mimeType);
Jakob Sack's avatar
Jakob Sack committed
224
	}
225

226
227
228
	/**
	 * @return array|false
	 */
229
230
231
232
233
234
235
236
237
238
239
240
241
	public function getDirectDownload() {
		if (\OCP\App::isEnabled('encryption')) {
			return [];
		}
		/** @var \OCP\Files\Storage $storage */
		list($storage, $internalPath) = $this->fileView->resolvePath($this->path);
		if (is_null($storage)) {
			return [];
		}

		return $storage->getDirectDownload($internalPath);
	}

242
243
	/**
	 * @param resource $data
Thomas Müller's avatar
Thomas Müller committed
244
	 * @return null|string
245
246
247
248
	 * @throws \Sabre\DAV\Exception
	 * @throws \Sabre\DAV\Exception\BadRequest
	 * @throws \Sabre\DAV\Exception\NotImplemented
	 * @throws \Sabre\DAV\Exception\ServiceUnavailable
249
	 */
Vincent Petry's avatar
Vincent Petry committed
250
251
	private function createFileChunked($data)
	{
Vincent Petry's avatar
Vincent Petry committed
252
		list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($this->path);
253

Vincent Petry's avatar
Vincent Petry committed
254
		$info = \OC_FileChunking::decodeName($name);
255
		if (empty($info)) {
Thomas Müller's avatar
Thomas Müller committed
256
			throw new \Sabre\DAV\Exception\NotImplemented();
257
		}
Vincent Petry's avatar
Vincent Petry committed
258
		$chunk_handler = new \OC_FileChunking($info);
259
260
261
262
263
264
265
		$bytesWritten = $chunk_handler->store($info['index'], $data);

		//detect aborted upload
		if (isset ($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PUT' ) {
			if (isset($_SERVER['CONTENT_LENGTH'])) {
				$expected = $_SERVER['CONTENT_LENGTH'];
				if ($bytesWritten != $expected) {
Thomas Müller's avatar
Thomas Müller committed
266
					$chunk_handler->remove($info['index']);
Thomas Müller's avatar
Thomas Müller committed
267
					throw new \Sabre\DAV\Exception\BadRequest(
268
269
270
271
272
273
						'expected filesize ' . $expected . ' got ' . $bytesWritten);
				}
			}
		}

		if ($chunk_handler->isComplete()) {
274
			list($storage, ) = $this->fileView->resolvePath($path);
275
			$needsPartFile = $this->needsPartFile($storage);
276

277
			try {
278
				$targetPath = $path . '/' . $info['name'];
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
				if ($needsPartFile) {
					// we first assembly the target file as a part file
					$partFile = $path . '/' . $info['name'] . '.ocTransferId' . $info['transferid'] . '.part';
					$chunk_handler->file_assemble($partFile);

					// here is the final atomic rename
					$renameOkay = $this->fileView->rename($partFile, $targetPath);
					$fileExists = $this->fileView->file_exists($targetPath);
					if ($renameOkay === false || $fileExists === false) {
						\OC_Log::write('webdav', '\OC\Files\Filesystem::rename() failed', \OC_Log::ERROR);
						// only delete if an error occurred and the target file was already created
						if ($fileExists) {
							$this->fileView->unlink($targetPath);
						}
						throw new \Sabre\DAV\Exception('Could not rename part file assembled from chunks');
294
					}
295
296
				} else {
					// assemble directly into the final file
297
					$chunk_handler->file_assemble($targetPath);
298
				}
299

300
				// allow sync clients to send the mtime along in a header
301
302
303
				$request = \OC::$server->getRequest();
				if (isset($request->server['HTTP_X_OC_MTIME'])) {
					if($this->fileView->touch($targetPath, $request->server['HTTP_X_OC_MTIME'])) {
304
305
						header('X-OC-MTime: accepted');
					}
306
307
				}

308
309
310
				$info = $this->fileView->getFileInfo($targetPath);
				return $info->getEtag();
			} catch (\OCP\Files\StorageNotAvailableException $e) {
311
				throw new \Sabre\DAV\Exception\ServiceUnavailable("Failed to put file: ".$e->getMessage());
312
			}
313
314
315
316
		}

		return null;
	}
317
318
319
320
321

	/**
	 * Returns whether a part file is needed for the given storage
	 * or whether the file can be assembled/uploaded directly on the
	 * target storage.
322
323
	 * @param \OCP\Files\Storage $storage
	 * @return bool true if the storage needs part file handling
324
325
326
327
328
329
	 */
	private function needsPartFile($storage) {
		// TODO: in the future use ChunkHandler provided by storage
		// and/or add method on Storage called "needsPartFile()"
		return !$storage->instanceOfStorage('OCA\Files_Sharing\External\Storage') &&
			!$storage->instanceOfStorage('OC\Files\Storage\OwnCloud');
330
	}
Jakob Sack's avatar
Jakob Sack committed
331
}