tempmanager.php 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. <?php
  2. /**
  3. * @author Lukas Reschke <lukas@owncloud.com>
  4. * @author Morris Jobke <hey@morrisjobke.de>
  5. * @author Olivier Paroz <github@oparoz.com>
  6. * @author Robin Appelman <icewind@owncloud.com>
  7. *
  8. * @copyright Copyright (c) 2015, ownCloud, Inc.
  9. * @license AGPL-3.0
  10. *
  11. * This code is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU Affero General Public License, version 3,
  13. * as published by the Free Software Foundation.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License, version 3,
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>
  22. *
  23. */
  24. namespace OC;
  25. use OCP\ILogger;
  26. use OCP\ITempManager;
  27. class TempManager implements ITempManager {
  28. /** @var string[] Current temporary files and folders, used for cleanup */
  29. protected $current = [];
  30. /** @var string i.e. /tmp on linux systems */
  31. protected $tmpBaseDir;
  32. /** @var ILogger */
  33. protected $log;
  34. /** Prefix */
  35. const TMP_PREFIX = 'oc_tmp_';
  36. /**
  37. * @param string $baseDir
  38. * @param \OCP\ILogger $logger
  39. */
  40. public function __construct($baseDir, ILogger $logger) {
  41. $this->tmpBaseDir = $baseDir;
  42. $this->log = $logger;
  43. }
  44. /**
  45. * Builds the filename with suffix and removes potential dangerous characters
  46. * such as directory separators.
  47. *
  48. * @param string $absolutePath Absolute path to the file / folder
  49. * @param string $postFix Postfix appended to the temporary file name, may be user controlled
  50. * @return string
  51. */
  52. private function buildFileNameWithSuffix($absolutePath, $postFix = '') {
  53. if($postFix !== '') {
  54. $postFix = '.' . ltrim($postFix, '.');
  55. $postFix = str_replace(['\\', '/'], '', $postFix);
  56. $absolutePath .= '-';
  57. }
  58. return $absolutePath . $postFix;
  59. }
  60. /**
  61. * Create a temporary file and return the path
  62. *
  63. * @param string $postFix Postfix appended to the temporary file name
  64. * @return string
  65. */
  66. public function getTemporaryFile($postFix = '') {
  67. if (is_writable($this->tmpBaseDir)) {
  68. // To create an unique file and prevent the risk of race conditions
  69. // or duplicated temporary files by other means such as collisions
  70. // we need to create the file using `tempnam` and append a possible
  71. // postfix to it later
  72. $file = tempnam($this->tmpBaseDir, self::TMP_PREFIX);
  73. $this->current[] = $file;
  74. // If a postfix got specified sanitize it and create a postfixed
  75. // temporary file
  76. if($postFix !== '') {
  77. $fileNameWithPostfix = $this->buildFileNameWithSuffix($file, $postFix);
  78. touch($fileNameWithPostfix);
  79. chmod($fileNameWithPostfix, 0600);
  80. $this->current[] = $fileNameWithPostfix;
  81. return $fileNameWithPostfix;
  82. }
  83. return $file;
  84. } else {
  85. $this->log->warning(
  86. 'Can not create a temporary file in directory {dir}. Check it exists and has correct permissions',
  87. [
  88. 'dir' => $this->tmpBaseDir,
  89. ]
  90. );
  91. return false;
  92. }
  93. }
  94. /**
  95. * Create a temporary folder and return the path
  96. *
  97. * @param string $postFix Postfix appended to the temporary folder name
  98. * @return string
  99. */
  100. public function getTemporaryFolder($postFix = '') {
  101. if (is_writable($this->tmpBaseDir)) {
  102. // To create an unique directory and prevent the risk of race conditions
  103. // or duplicated temporary files by other means such as collisions
  104. // we need to create the file using `tempnam` and append a possible
  105. // postfix to it later
  106. $uniqueFileName = tempnam($this->tmpBaseDir, self::TMP_PREFIX);
  107. $this->current[] = $uniqueFileName;
  108. // Build a name without postfix
  109. $path = $this->buildFileNameWithSuffix($uniqueFileName . '-folder', $postFix);
  110. mkdir($path, 0700);
  111. $this->current[] = $path;
  112. return $path . '/';
  113. } else {
  114. $this->log->warning(
  115. 'Can not create a temporary folder in directory {dir}. Check it exists and has correct permissions',
  116. [
  117. 'dir' => $this->tmpBaseDir,
  118. ]
  119. );
  120. return false;
  121. }
  122. }
  123. /**
  124. * Remove the temporary files and folders generated during this request
  125. */
  126. public function clean() {
  127. $this->cleanFiles($this->current);
  128. }
  129. /**
  130. * @param string[] $files
  131. */
  132. protected function cleanFiles($files) {
  133. foreach ($files as $file) {
  134. if (file_exists($file)) {
  135. try {
  136. \OC_Helper::rmdirr($file);
  137. } catch (\UnexpectedValueException $ex) {
  138. $this->log->warning(
  139. "Error deleting temporary file/folder: {file} - Reason: {error}",
  140. [
  141. 'file' => $file,
  142. 'error' => $ex->getMessage(),
  143. ]
  144. );
  145. }
  146. }
  147. }
  148. }
  149. /**
  150. * Remove old temporary files and folders that were failed to be cleaned
  151. */
  152. public function cleanOld() {
  153. $this->cleanFiles($this->getOldFiles());
  154. }
  155. /**
  156. * Get all temporary files and folders generated by oc older than an hour
  157. *
  158. * @return string[]
  159. */
  160. protected function getOldFiles() {
  161. $cutOfTime = time() - 3600;
  162. $files = [];
  163. $dh = opendir($this->tmpBaseDir);
  164. if ($dh) {
  165. while (($file = readdir($dh)) !== false) {
  166. if (substr($file, 0, 7) === self::TMP_PREFIX) {
  167. $path = $this->tmpBaseDir . '/' . $file;
  168. $mtime = filemtime($path);
  169. if ($mtime < $cutOfTime) {
  170. $files[] = $path;
  171. }
  172. }
  173. }
  174. }
  175. return $files;
  176. }
  177. }