server.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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()
  22. {
  23. $this->path = __DIR__ . '/';
  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. $hash = $this->users[$user]['password'] ?? null;
  36. if (!$hash) {
  37. return false;
  38. }
  39. if (!password_verify($password, $hash)) {
  40. return false;
  41. }
  42. $this->user = $user;
  43. return true;
  44. }
  45. static protected function glob(string $path, string $pattern = '', int $flags = 0): array
  46. {
  47. $path = preg_replace('/[\*\?\[\]]/', '\\\\$0', $path);
  48. return glob($path . $pattern, $flags);
  49. }
  50. public function canRead(string $uri): bool
  51. {
  52. if (in_array($uri, INTERNAL_FILES)) {
  53. return false;
  54. }
  55. if (preg_match('/\.(?:php\d?|phtml|phps)$|^\./i', $uri)) {
  56. return false;
  57. }
  58. if (ANONYMOUS_READ) {
  59. return true;
  60. }
  61. if (!$this->auth()) {
  62. return false;
  63. }
  64. $restrict = $this->users[$this->user]['restrict'] ?? [];
  65. if (!is_array($restrict) || empty($restrict)) {
  66. return true;
  67. }
  68. foreach ($restrict as $match) {
  69. if (0 === strpos($uri, $match)) {
  70. return true;
  71. }
  72. }
  73. return false;
  74. }
  75. public function canWrite(string $uri): bool
  76. {
  77. if (!$this->auth() && !ANONYMOUS_WRITE) {
  78. return false;
  79. }
  80. if (!$this->canRead($uri)) {
  81. return false;
  82. }
  83. if (ANONYMOUS_WRITE) {
  84. return true;
  85. }
  86. if (!$this->auth() || empty($this->users[$this->user]['write'])) {
  87. return false;
  88. }
  89. $restrict = $this->users[$this->user]['restrict_write'] ?? [];
  90. if (!is_array($restrict) || empty($restrict)) {
  91. return true;
  92. }
  93. foreach ($restrict as $match) {
  94. if (0 === strpos($uri, $match)) {
  95. return true;
  96. }
  97. }
  98. return false;
  99. }
  100. public function canOnlyCreate(string $uri): bool
  101. {
  102. $restrict = $this->users[$this->user]['restrict_write'] ?? [];
  103. if (in_array($uri, $restrict, true)) {
  104. return true;
  105. }
  106. $restrict = $this->users[$this->user]['restrict'] ?? [];
  107. if (in_array($uri, $restrict, true)) {
  108. return true;
  109. }
  110. return false;
  111. }
  112. public function list(string $uri, ?array $properties): iterable
  113. {
  114. if (!$this->canRead($uri . '/')) {
  115. //throw new WebDAV_Exception('Access forbidden', 403);
  116. }
  117. $dirs = self::glob($this->path . $uri, '/*', \GLOB_ONLYDIR);
  118. $dirs = array_map('basename', $dirs);
  119. $dirs = array_filter($dirs, fn($a) => $this->canRead(ltrim($uri . '/' . $a, '/') . '/'));
  120. natcasesort($dirs);
  121. $files = self::glob($this->path . $uri, '/*');
  122. $files = array_map('basename', $files);
  123. $files = array_diff($files, $dirs);
  124. // Remove PHP files and dot-files from listings
  125. $files = array_filter($files, fn($a) => $this->canRead(ltrim($uri . '/' . $a, '/')));
  126. natcasesort($files);
  127. $files = array_flip(array_merge($dirs, $files));
  128. $files = array_map(fn($a) => null, $files);
  129. return $files;
  130. }
  131. public function get(string $uri): ?array
  132. {
  133. if (!$this->canRead($uri)) {
  134. throw new WebDAV_Exception('Access forbidden', 403);
  135. }
  136. $path = $this->path . $uri;
  137. if (!file_exists($path)) {
  138. return null;
  139. }
  140. return ['path' => $path];
  141. }
  142. public function exists(string $uri): bool
  143. {
  144. return file_exists($this->path . $uri);
  145. }
  146. public function get_file_property(string $uri, string $name, int $depth)
  147. {
  148. $target = $this->path . $uri;
  149. switch ($name) {
  150. case 'DAV::getcontentlength':
  151. return is_dir($target) ? null : filesize($target);
  152. case 'DAV::getcontenttype':
  153. // ownCloud app crashes if mimetype is provided for a directory
  154. // https://github.com/owncloud/android/issues/3768
  155. return is_dir($target) ? null : mime_content_type($target);
  156. case 'DAV::resourcetype':
  157. return is_dir($target) ? 'collection' : '';
  158. case 'DAV::getlastmodified':
  159. if (!$uri && $depth == 0 && is_dir($target)) {
  160. $mtime = self::getDirectoryMTime($target);
  161. }
  162. else {
  163. $mtime = filemtime($target);
  164. }
  165. if (!$mtime) {
  166. return null;
  167. }
  168. return new \DateTime('@' . $mtime);
  169. case 'DAV::ishidden':
  170. return basename($target)[0] == '.';
  171. case 'DAV::getetag':
  172. $hash = filemtime($target) . filesize($target);
  173. return md5($hash . $target);
  174. case 'DAV::lastaccessed':
  175. return new \DateTime('@' . fileatime($target));
  176. case 'DAV::creationdate':
  177. return new \DateTime('@' . filectime($target));
  178. case 'http://owncloud.org/ns:permissions':
  179. $permissions = 'G';
  180. if (is_dir($target)) {
  181. $uri .= '/';
  182. }
  183. if (is_writeable($target) && $this->canWrite($uri)) {
  184. // If the directory is one of the restricted paths,
  185. // then we can only do stuff INSIDE, and not delete/rename the directory itself
  186. if ($this->canOnlyCreate($uri)) {
  187. $permissions .= 'CK';
  188. }
  189. else {
  190. $permissions .= 'DNVWCK';
  191. }
  192. }
  193. return $permissions;
  194. case Server::PROP_DIGEST_MD5:
  195. if (!is_file($target)) {
  196. return null;
  197. }
  198. return md5_file($target);
  199. default:
  200. break;
  201. }
  202. return null;
  203. }
  204. public function properties(string $uri, ?array $properties, int $depth): ?array
  205. {
  206. $target = $this->path . $uri;
  207. if (!file_exists($target)) {
  208. return null;
  209. }
  210. if (null === $properties) {
  211. $properties = WebDAV::BASIC_PROPERTIES;
  212. }
  213. $out = [];
  214. foreach ($properties as $name) {
  215. $v = $this->get_file_property($uri, $name, $depth);
  216. if (null !== $v) {
  217. $out[$name] = $v;
  218. }
  219. }
  220. return $out;
  221. }
  222. public function put(string $uri, $pointer, ?string $hash, ?int $mtime): bool
  223. {
  224. if (preg_match(self::PUT_IGNORE_PATTERN, basename($uri))) {
  225. return false;
  226. }
  227. if (!$this->canWrite($uri)) {
  228. throw new WebDAV_Exception('Access forbidden', 403);
  229. }
  230. $target = $this->path . $uri;
  231. $parent = dirname($target);
  232. if (is_dir($target)) {
  233. throw new WebDAV_Exception('Target is a directory', 409);
  234. }
  235. if (!file_exists($parent)) {
  236. mkdir($parent, 0770, true);
  237. }
  238. $new = !file_exists($target);
  239. $delete = false;
  240. $size = 0;
  241. $quota = disk_free_space($this->path);
  242. $tmp_file = '.tmp.' . sha1($target);
  243. $out = fopen($tmp_file, 'w');
  244. while (!feof($pointer)) {
  245. $bytes = fread($pointer, 8192);
  246. $size += strlen($bytes);
  247. if ($size > $quota) {
  248. $delete = true;
  249. break;
  250. }
  251. fwrite($out, $bytes);
  252. }
  253. fclose($out);
  254. fclose($pointer);
  255. if ($delete) {
  256. @unlink($tmp_file);
  257. throw new WebDAV_Exception('Your quota is exhausted', 403);
  258. }
  259. elseif ($hash && md5_file($tmp_file) != $hash) {
  260. @unlink($tmp_file);
  261. throw new WebDAV_Exception('The data sent does not match the supplied MD5 hash', 400);
  262. }
  263. else {
  264. rename($tmp_file, $target);
  265. }
  266. if ($mtime) {
  267. @touch($target, $mtime);
  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', 403);
  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', 403);
  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. static public function getDirectoryMTime(string $path): int
  367. {
  368. $last = 0;
  369. $path = rtrim($path, '/');
  370. foreach (self::glob($path, '/*', GLOB_NOSORT) as $f) {
  371. if (is_dir($f)) {
  372. $m = self::getDirectoryMTime($f);
  373. if ($m > $last) {
  374. $last = $m;
  375. }
  376. }
  377. $m = filemtime($f);
  378. if ($m > $last) {
  379. $last = $m;
  380. }
  381. }
  382. return $last;
  383. }
  384. }
  385. class Server extends \KD2\WebDAV\Server
  386. {
  387. protected function html_directory(string $uri, iterable $list): ?string
  388. {
  389. $out = parent::html_directory($uri, $list);
  390. if (null !== $out) {
  391. $out = str_replace('<body>', sprintf('<body style="opacity: 0"><script type="text/javascript" src="%s/.webdav/webdav.js"></script>', rtrim($this->base_uri, '/')), $out);
  392. }
  393. return $out;
  394. }
  395. function error(WebDAV_Exception $e)
  396. {
  397. if ($e->getCode() == 403 && !$this->storage->auth() && count($this->storage->users)) {
  398. $user = $_SERVER['PHP_AUTH_USER'] ?? null;
  399. http_response_code(401);
  400. header('WWW-Authenticate: Basic realm="Please login"');
  401. echo '<h2>Error 401</h2><h1>You need to login to access this.</h1>';
  402. return;
  403. }
  404. parent::error($e);
  405. }
  406. }
  407. }
  408. namespace {
  409. use PicoDAV\Server;
  410. use PicoDAV\Storage;
  411. $uri = strtok($_SERVER['REQUEST_URI'], '?');
  412. $root = substr(__DIR__, strlen($_SERVER['DOCUMENT_ROOT']));
  413. if (false !== strpos($uri, '..')) {
  414. http_response_code(404);
  415. die('Invalid URL');
  416. }
  417. $relative_uri = ltrim(substr($uri, strlen($root)), '/');
  418. if (!empty($_SERVER['SERVER_SOFTWARE']) && stristr($_SERVER['SERVER_SOFTWARE'], 'apache') && !file_exists(__DIR__ . '/.htaccess')) {
  419. file_put_contents(__DIR__ . '/.htaccess', /*__HTACCESS__*/);
  420. }
  421. if ($relative_uri == '.webdav/webdav.js' || $relative_uri == '.webdav/webdav.css') {
  422. http_response_code(200);
  423. if ($relative_uri == '.webdav/webdav.js') {
  424. header('Content-Type: text/javascript', true);
  425. }
  426. else {
  427. header('Content-Type: text/css', true);
  428. }
  429. $seconds_to_cache = 3600 * 24 * 365;
  430. $ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
  431. header("Expires: " . $ts);
  432. header("Pragma: cache");
  433. header("Cache-Control: max-age=" . $seconds_to_cache);
  434. $fp = fopen(__FILE__, 'r');
  435. if ($relative_uri == '.webdav/webdav.js') {
  436. fseek($fp, __PHP_SIZE__, SEEK_SET);
  437. echo fread($fp, __JS_SIZE__);
  438. }
  439. else {
  440. fseek($fp, __PHP_SIZE__ + __JS_SIZE__, SEEK_SET);
  441. echo fread($fp, __CSS_SIZE__);
  442. }
  443. fclose($fp);
  444. exit;
  445. }
  446. const CONFIG_FILE = __DIR__ . '/.picodav.ini';
  447. define('PicoDAV\INTERNAL_FILES', ['.picodav.ini', basename(__FILE__), '.webdav/webdav.js', '.webdav/webdav.css']);
  448. const DEFAULT_CONFIG = [
  449. 'ANONYMOUS_READ' => true,
  450. 'ANONYMOUS_WRITE' => false,
  451. ];
  452. $config = [];
  453. $storage = new Storage;
  454. if (file_exists(CONFIG_FILE)) {
  455. $config = parse_ini_file(CONFIG_FILE, true);
  456. $users = array_filter($config, 'is_array');
  457. $config = array_diff_key($config, $users);
  458. $config = array_change_key_case($config, \CASE_UPPER);
  459. $replace = [];
  460. // Encrypt plaintext passwords
  461. foreach ($users as $name => $properties) {
  462. if (isset($properties['password']) && substr($properties['password'], 0, 1) != '$') {
  463. $users[$name]['password'] = $replace[$name] = password_hash($properties['password'], null);
  464. }
  465. }
  466. if (count($replace)) {
  467. $lines = file(CONFIG_FILE);
  468. $current = null;
  469. foreach ($lines as &$line) {
  470. if (preg_match('/^\s*\[(\w+)\]\s*$/', $line, $match)) {
  471. $current = $match[1];
  472. continue;
  473. }
  474. if ($current && isset($replace[$current]) && preg_match('/^\s*password\s*=/', $line)) {
  475. $line = sprintf("password = %s\n", var_export($replace[$current], true));
  476. }
  477. }
  478. unset($line, $current);
  479. file_put_contents(CONFIG_FILE, implode('', $lines));
  480. }
  481. $storage->users = $users;
  482. }
  483. foreach (DEFAULT_CONFIG as $key => $value) {
  484. if (array_key_exists($key, $config)) {
  485. $value = $config[$key];
  486. }
  487. if (is_bool(DEFAULT_CONFIG[$key])) {
  488. $value = boolval($value);
  489. }
  490. define('PicoDAV\\' . $key, $value);
  491. }
  492. $dav = new Server;
  493. $dav->setStorage($storage);
  494. $dav->setBaseURI($root);
  495. if (!$dav->route($uri)) {
  496. http_response_code(404);
  497. die('Invalid URL, sorry');
  498. }
  499. exit;
  500. }