server.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. <?php
  2. namespace KD2\WebDAV
  3. {
  4. //__KD2\WebDAV\Server__
  5. //__KD2\WebDAV\AbstractStorage__
  6. }
  7. namespace PicoDAV
  8. {
  9. use KD2\WebDAV\AbstractStorage;
  10. use KD2\WebDAV\Exception as WebDAV_Exception;
  11. class Storage extends AbstractStorage
  12. {
  13. /**
  14. * These file names will be ignored when doing a PUT
  15. * as they are garbage, coming from some OS
  16. */
  17. const PUT_IGNORE_PATTERN = '!^~(?:lock\.|^\._)|^(?:\.DS_Store|Thumbs\.db|desktop\.ini)$!';
  18. protected string $path;
  19. protected ?string $user = null;
  20. public array $users = [];
  21. public function __construct(string $path)
  22. {
  23. $this->path = $path . '/';
  24. }
  25. public function auth(): bool
  26. {
  27. if (ANONYMOUS_WRITE && ANONYMOUS_READ) {
  28. return true;
  29. }
  30. if ($this->user) {
  31. return true;
  32. }
  33. $user = $_SERVER['PHP_AUTH_USER'] ?? null;
  34. $password = $_SERVER['PHP_AUTH_PW'] ?? null;
  35. if (!array_key_exists($user, $this->users)) {
  36. return false;
  37. }
  38. $hash = $this->users[$user]['password'] ?? null;
  39. // If no password is set, we accept any password as we consider that a .htaccess/.htpasswd
  40. // access has been granted
  41. if (null !== $hash && !password_verify($password, $hash)) {
  42. return false;
  43. }
  44. $this->user = $user;
  45. return true;
  46. }
  47. static protected function glob(string $path, string $pattern = '', int $flags = 0): array
  48. {
  49. $path = preg_replace('/[\*\?\[\]]/', '\\\\$0', $path);
  50. return glob($path . $pattern, $flags);
  51. }
  52. public function canRead(string $uri): bool
  53. {
  54. if (in_array($uri, INTERNAL_FILES)) {
  55. return false;
  56. }
  57. if (preg_match('/\.(?:php\d?|phtml|phps)$|^\./i', $uri)) {
  58. return false;
  59. }
  60. if (ANONYMOUS_READ) {
  61. return true;
  62. }
  63. if (!$this->auth()) {
  64. return false;
  65. }
  66. $restrict = $this->users[$this->user]['restrict'] ?? [];
  67. if (!is_array($restrict) || empty($restrict)) {
  68. return true;
  69. }
  70. foreach ($restrict as $match) {
  71. if (0 === strpos($uri, $match)) {
  72. return true;
  73. }
  74. }
  75. return false;
  76. }
  77. public function canWrite(string $uri): bool
  78. {
  79. if (!$this->auth() && !ANONYMOUS_WRITE) {
  80. return false;
  81. }
  82. if (!$this->canRead($uri)) {
  83. return false;
  84. }
  85. if (ANONYMOUS_WRITE) {
  86. return true;
  87. }
  88. if (!$this->auth() || empty($this->users[$this->user]['write'])) {
  89. return false;
  90. }
  91. $restrict = $this->users[$this->user]['restrict_write'] ?? [];
  92. if (!is_array($restrict) || empty($restrict)) {
  93. return true;
  94. }
  95. foreach ($restrict as $match) {
  96. if (0 === strpos($uri, $match)) {
  97. return true;
  98. }
  99. }
  100. return false;
  101. }
  102. public function canOnlyCreate(string $uri): bool
  103. {
  104. $restrict = $this->users[$this->user]['restrict_write'] ?? [];
  105. if (in_array($uri, $restrict, true)) {
  106. return true;
  107. }
  108. $restrict = $this->users[$this->user]['restrict'] ?? [];
  109. if (in_array($uri, $restrict, true)) {
  110. return true;
  111. }
  112. return false;
  113. }
  114. public function list(string $uri, ?array $properties): iterable
  115. {
  116. if (!$this->canRead($uri . '/')) {
  117. //throw new WebDAV_Exception('Access forbidden', 403);
  118. }
  119. $dirs = self::glob($this->path . $uri, '/*', \GLOB_ONLYDIR);
  120. $dirs = array_map('basename', $dirs);
  121. $dirs = array_filter($dirs, fn($a) => $this->canRead(ltrim($uri . '/' . $a, '/') . '/'));
  122. natcasesort($dirs);
  123. $files = self::glob($this->path . $uri, '/*');
  124. $files = array_map('basename', $files);
  125. $files = array_diff($files, $dirs);
  126. // Remove PHP files and dot-files from listings
  127. $files = array_filter($files, fn($a) => $this->canRead(ltrim($uri . '/' . $a, '/')));
  128. natcasesort($files);
  129. $files = array_flip(array_merge($dirs, $files));
  130. $files = array_map(fn($a) => null, $files);
  131. return $files;
  132. }
  133. public function get(string $uri): ?array
  134. {
  135. if (!$this->canRead($uri)) {
  136. throw new WebDAV_Exception('Access forbidden', 403);
  137. }
  138. $path = $this->path . $uri;
  139. if (!file_exists($path)) {
  140. return null;
  141. }
  142. return ['path' => $path];
  143. }
  144. public function exists(string $uri): bool
  145. {
  146. return file_exists($this->path . $uri);
  147. }
  148. public function get_file_property(string $uri, string $name, int $depth)
  149. {
  150. $target = $this->path . $uri;
  151. switch ($name) {
  152. case 'DAV::displayname':
  153. return basename($uri);
  154. case 'DAV::getcontentlength':
  155. return is_dir($target) ? null : filesize($target);
  156. case 'DAV::getcontenttype':
  157. // ownCloud app crashes if mimetype is provided for a directory
  158. // https://github.com/owncloud/android/issues/3768
  159. return is_dir($target) ? null : mime_content_type($target);
  160. case 'DAV::resourcetype':
  161. return is_dir($target) ? 'collection' : '';
  162. case 'DAV::getlastmodified':
  163. $mtime = filemtime($target);
  164. if (!$mtime) {
  165. return null;
  166. }
  167. return new \DateTime('@' . $mtime);
  168. case 'DAV::ishidden':
  169. return basename($target)[0] == '.';
  170. case 'DAV::getetag':
  171. $hash = filemtime($target) . filesize($target);
  172. return md5($hash . $target);
  173. case 'DAV::lastaccessed':
  174. return new \DateTime('@' . fileatime($target));
  175. case 'DAV::creationdate':
  176. return new \DateTime('@' . filectime($target));
  177. case 'http://owncloud.org/ns:permissions':
  178. $permissions = 'G';
  179. if (is_dir($target)) {
  180. $uri .= '/';
  181. }
  182. if (is_writeable($target) && $this->canWrite($uri)) {
  183. // If the directory is one of the restricted paths,
  184. // then we can only do stuff INSIDE, and not delete/rename the directory itself
  185. if ($this->canOnlyCreate($uri)) {
  186. $permissions .= 'CK';
  187. }
  188. else {
  189. $permissions .= 'DNVWCK';
  190. }
  191. }
  192. return $permissions;
  193. case Server::PROP_DIGEST_MD5:
  194. if (!is_file($target) || is_dir($target) || !is_readable($target)) {
  195. return null;
  196. }
  197. return md5_file($target);
  198. default:
  199. break;
  200. }
  201. return null;
  202. }
  203. public function propfind(string $uri, ?array $properties, int $depth): ?array
  204. {
  205. $target = $this->path . $uri;
  206. if (!file_exists($target)) {
  207. return null;
  208. }
  209. if (null === $properties) {
  210. $properties = Server::BASIC_PROPERTIES;
  211. }
  212. $out = [];
  213. foreach ($properties as $name) {
  214. $v = $this->get_file_property($uri, $name, $depth);
  215. if (null !== $v) {
  216. $out[$name] = $v;
  217. }
  218. }
  219. return $out;
  220. }
  221. public function put(string $uri, $pointer, ?string $hash_algo, ?string $hash): bool
  222. {
  223. if (preg_match(self::PUT_IGNORE_PATTERN, basename($uri))) {
  224. return false;
  225. }
  226. if (!$this->canWrite($uri)) {
  227. throw new WebDAV_Exception('Access forbidden', 403);
  228. }
  229. $target = $this->path . $uri;
  230. $parent = dirname($target);
  231. if (is_dir($target)) {
  232. throw new WebDAV_Exception('Target is a directory', 409);
  233. }
  234. if (!file_exists($parent)) {
  235. mkdir($parent, 0770, true);
  236. }
  237. $new = !file_exists($target);
  238. $delete = false;
  239. $size = 0;
  240. $quota = disk_free_space($this->path);
  241. $tmp_file = $this->path . '.tmp.' . sha1($target);
  242. $out = fopen($tmp_file, 'w');
  243. while (!feof($pointer)) {
  244. $bytes = fread($pointer, 8192);
  245. $size += strlen($bytes);
  246. if ($size > $quota) {
  247. $delete = true;
  248. break;
  249. }
  250. fwrite($out, $bytes);
  251. }
  252. fclose($out);
  253. fclose($pointer);
  254. if ($delete) {
  255. @unlink($tmp_file);
  256. throw new WebDAV_Exception('Your quota is exhausted', 507);
  257. }
  258. elseif ($hash && $hash_algo == 'MD5' && md5_file($tmp_file) != $hash) {
  259. @unlink($tmp_file);
  260. throw new WebDAV_Exception('The data sent does not match the supplied MD5 hash', 400);
  261. }
  262. elseif ($hash && $hash_algo == 'SHA1' && sha1_file($tmp_file) != $hash) {
  263. @unlink($tmp_file);
  264. throw new WebDAV_Exception('The data sent does not match the supplied SHA1 hash', 400);
  265. }
  266. else {
  267. rename($tmp_file, $target);
  268. }
  269. return $new;
  270. }
  271. public function delete(string $uri): void
  272. {
  273. if (!$this->canWrite($uri)) {
  274. throw new WebDAV_Exception('Access forbidden', 403);
  275. }
  276. if ($this->canOnlyCreate($uri)) {
  277. throw new WebDAV_Exception('Access forbidden', 403);
  278. }
  279. $target = $this->path . $uri;
  280. if (!file_exists($target)) {
  281. throw new WebDAV_Exception('Target does not exist', 404);
  282. }
  283. if (!is_writeable($target)) {
  284. throw new WebDAV_Exception('File permissions says that you cannot delete this, sorry.', 403);
  285. }
  286. if (is_dir($target)) {
  287. foreach (self::glob($target, '/*') as $file) {
  288. $this->delete(substr($file, strlen($this->path)));
  289. }
  290. rmdir($target);
  291. }
  292. else {
  293. unlink($target);
  294. }
  295. }
  296. public function copymove(bool $move, string $uri, string $destination): bool
  297. {
  298. if (!$this->canWrite($uri)
  299. || !$this->canWrite($destination)
  300. || $this->canOnlyCreate($uri)) {
  301. throw new WebDAV_Exception('Access forbidden', 403);
  302. }
  303. $source = $this->path . $uri;
  304. $target = $this->path . $destination;
  305. $parent = dirname($target);
  306. if (!file_exists($source)) {
  307. throw new WebDAV_Exception('File not found', 404);
  308. }
  309. $overwritten = file_exists($target);
  310. if (!is_dir($parent)) {
  311. throw new WebDAV_Exception('Target parent directory does not exist', 409);
  312. }
  313. if (false === $move) {
  314. $quota = disk_free_space($this->path);
  315. if (filesize($source) > $quota) {
  316. throw new WebDAV_Exception('Your quota is exhausted', 507);
  317. }
  318. }
  319. if ($overwritten) {
  320. $this->delete($destination);
  321. }
  322. $method = $move ? 'rename' : 'copy';
  323. if ($method == 'copy' && is_dir($source)) {
  324. @mkdir($target, 0770, true);
  325. foreach ($iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source), \RecursiveIteratorIterator::SELF_FIRST) as $item)
  326. {
  327. if ($item->isDir()) {
  328. @mkdir($target . DIRECTORY_SEPARATOR . $iterator->getSubPathname());
  329. } else {
  330. copy($item, $target . DIRECTORY_SEPARATOR . $iterator->getSubPathname());
  331. }
  332. }
  333. }
  334. else {
  335. $method($source, $target);
  336. $this->getResourceProperties($uri)->move($destination);
  337. }
  338. return $overwritten;
  339. }
  340. public function copy(string $uri, string $destination): bool
  341. {
  342. return $this->copymove(false, $uri, $destination);
  343. }
  344. public function move(string $uri, string $destination): bool
  345. {
  346. return $this->copymove(true, $uri, $destination);
  347. }
  348. public function mkcol(string $uri): void
  349. {
  350. if (!$this->canWrite($uri)) {
  351. throw new WebDAV_Exception('Access forbidden', 403);
  352. }
  353. if (!disk_free_space($this->path)) {
  354. throw new WebDAV_Exception('Your quota is exhausted', 507);
  355. }
  356. $target = $this->path . $uri;
  357. $parent = dirname($target);
  358. if (file_exists($target)) {
  359. throw new WebDAV_Exception('There is already a file with that name', 405);
  360. }
  361. if (!file_exists($parent)) {
  362. throw new WebDAV_Exception('The parent directory does not exist', 409);
  363. }
  364. mkdir($target, 0770);
  365. }
  366. public function touch(string $uri, \DateTimeInterface $datetime): bool
  367. {
  368. $target = $this->path . $uri;
  369. return @touch($target, $datetime->getTimestamp());
  370. }
  371. }
  372. class Server extends \KD2\WebDAV\Server
  373. {
  374. protected function html_directory(string $uri, iterable $list): ?string
  375. {
  376. $out = parent::html_directory($uri, $list);
  377. if (null !== $out) {
  378. $out = str_replace('<body>', sprintf('<body style="opacity: 0"><script type="text/javascript" src="%s/.webdav/webdav.js"></script>', rtrim($this->base_uri, '/')), $out);
  379. }
  380. return $out;
  381. }
  382. public function route(?string $uri = null): bool
  383. {
  384. if (!ANONYMOUS_WRITE && !ANONYMOUS_READ && !$this->storage->auth()) {
  385. $this->requireAuth();
  386. return true;
  387. }
  388. return parent::route($uri);
  389. }
  390. protected function requireAuth(): void
  391. {
  392. http_response_code(401);
  393. header('WWW-Authenticate: Basic realm="Please login"');
  394. echo '<h2>Error 401</h2><h1>You need to login to access this.</h1>';
  395. }
  396. public function error(WebDAV_Exception $e)
  397. {
  398. if ($e->getCode() == 403 && !$this->storage->auth() && count($this->storage->users)) {
  399. return;
  400. }
  401. parent::error($e);
  402. }
  403. protected string $_log = '';
  404. public function log(string $message, ...$params): void
  405. {
  406. if (!HTTP_LOG_FILE) {
  407. return;
  408. }
  409. $this->_log .= vsprintf($message, $params) . "\n";
  410. }
  411. public function __destruct()
  412. {
  413. if (!$this->_log) {
  414. return;
  415. }
  416. file_put_contents(HTTP_LOG_FILE, $this->_log, \FILE_APPEND);
  417. }
  418. }
  419. }
  420. namespace {
  421. use PicoDAV\Server;
  422. use PicoDAV\Storage;
  423. $uri = strtok($_SERVER['REQUEST_URI'], '?');
  424. $self = $_SERVER['SCRIPT_FILENAME'];
  425. $self_dir = dirname($self);
  426. $root = substr(dirname($_SERVER['SCRIPT_FILENAME']), strlen($_SERVER['DOCUMENT_ROOT']));
  427. $root = '/' . ltrim($root, '/');
  428. if (false !== strpos($uri, '..')) {
  429. http_response_code(404);
  430. die('Invalid URL');
  431. }
  432. $relative_uri = ltrim(substr($uri, strlen($root)), '/');
  433. if (!empty($_SERVER['SERVER_SOFTWARE']) && stristr($_SERVER['SERVER_SOFTWARE'], 'apache') && !file_exists($self_dir . '/.htaccess')) {
  434. file_put_contents($self_dir . '/.htaccess', str_replace('index.php', basename($self), /*__HTACCESS__*/));
  435. }
  436. if ($relative_uri == '.webdav/webdav.js' || $relative_uri == '.webdav/webdav.css') {
  437. http_response_code(200);
  438. if ($relative_uri == '.webdav/webdav.js') {
  439. header('Content-Type: text/javascript', true);
  440. }
  441. else {
  442. header('Content-Type: text/css', true);
  443. }
  444. $seconds_to_cache = 3600 * 24 * 5;
  445. $ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
  446. header("Expires: " . $ts);
  447. header("Pragma: cache");
  448. header("Cache-Control: max-age=" . $seconds_to_cache);
  449. $fp = fopen(__FILE__, 'r');
  450. if ($relative_uri == '.webdav/webdav.js') {
  451. fseek($fp, __PHP_SIZE__, SEEK_SET);
  452. echo fread($fp, __JS_SIZE__);
  453. }
  454. else {
  455. fseek($fp, __PHP_SIZE__ + __JS_SIZE__, SEEK_SET);
  456. echo fread($fp, __CSS_SIZE__);
  457. }
  458. fclose($fp);
  459. exit;
  460. }
  461. $config_file = $self_dir . '/.picodav.ini';
  462. define('PicoDAV\INTERNAL_FILES', ['.picodav.ini', $self_dir, '.webdav/webdav.js', '.webdav/webdav.css']);
  463. const DEFAULT_CONFIG = [
  464. 'ANONYMOUS_READ' => true,
  465. 'ANONYMOUS_WRITE' => false,
  466. 'HTTP_LOG_FILE' => null,
  467. ];
  468. $config = [];
  469. $storage = new Storage($self_dir);
  470. if (file_exists($config_file)) {
  471. $config = parse_ini_file($config_file, true);
  472. $users = array_filter($config, 'is_array');
  473. $config = array_diff_key($config, $users);
  474. $config = array_change_key_case($config, \CASE_UPPER);
  475. $replace = [];
  476. // Encrypt plaintext passwords
  477. foreach ($users as $name => $properties) {
  478. if (isset($properties['password']) && substr($properties['password'], 0, 1) != '$') {
  479. $users[$name]['password'] = $replace[$name] = password_hash($properties['password'], null);
  480. }
  481. }
  482. if (count($replace)) {
  483. $lines = file($config_file);
  484. $current = null;
  485. foreach ($lines as &$line) {
  486. if (preg_match('/^\s*\[(\w+)\]\s*$/', $line, $match)) {
  487. $current = $match[1];
  488. continue;
  489. }
  490. if ($current && isset($replace[$current]) && preg_match('/^\s*password\s*=/', $line)) {
  491. $line = sprintf("password = %s\n", var_export($replace[$current], true));
  492. }
  493. }
  494. unset($line, $current);
  495. file_put_contents($config_file, implode('', $lines));
  496. }
  497. $storage->users = $users;
  498. }
  499. foreach (DEFAULT_CONFIG as $key => $value) {
  500. if (array_key_exists($key, $config)) {
  501. $value = $config[$key];
  502. }
  503. if (is_bool(DEFAULT_CONFIG[$key])) {
  504. $value = boolval($value);
  505. }
  506. define('PicoDAV\\' . $key, $value);
  507. }
  508. $dav = new Server();
  509. $dav->setStorage($storage);
  510. $dav->setBaseURI($root);
  511. if (!$dav->route($uri)) {
  512. http_response_code(404);
  513. die('Unknown URL, sorry.');
  514. }
  515. exit;
  516. }