server.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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::displayname':
  151. return basename($uri);
  152. case 'DAV::getcontentlength':
  153. return is_dir($target) ? null : filesize($target);
  154. case 'DAV::getcontenttype':
  155. // ownCloud app crashes if mimetype is provided for a directory
  156. // https://github.com/owncloud/android/issues/3768
  157. return is_dir($target) ? null : mime_content_type($target);
  158. case 'DAV::resourcetype':
  159. return is_dir($target) ? 'collection' : '';
  160. case 'DAV::getlastmodified':
  161. if (!$uri && $depth == 0 && is_dir($target)) {
  162. $mtime = self::getDirectoryMTime($target);
  163. }
  164. else {
  165. $mtime = filemtime($target);
  166. }
  167. if (!$mtime) {
  168. return null;
  169. }
  170. return new \DateTime('@' . $mtime);
  171. case 'DAV::ishidden':
  172. return basename($target)[0] == '.';
  173. case 'DAV::getetag':
  174. $hash = filemtime($target) . filesize($target);
  175. return md5($hash . $target);
  176. case 'DAV::lastaccessed':
  177. return new \DateTime('@' . fileatime($target));
  178. case 'DAV::creationdate':
  179. return new \DateTime('@' . filectime($target));
  180. case 'http://owncloud.org/ns:permissions':
  181. $permissions = 'G';
  182. if (is_dir($target)) {
  183. $uri .= '/';
  184. }
  185. if (is_writeable($target) && $this->canWrite($uri)) {
  186. // If the directory is one of the restricted paths,
  187. // then we can only do stuff INSIDE, and not delete/rename the directory itself
  188. if ($this->canOnlyCreate($uri)) {
  189. $permissions .= 'CK';
  190. }
  191. else {
  192. $permissions .= 'DNVWCK';
  193. }
  194. }
  195. return $permissions;
  196. case Server::PROP_DIGEST_MD5:
  197. if (!is_file($target)) {
  198. return null;
  199. }
  200. return md5_file($target);
  201. default:
  202. break;
  203. }
  204. return null;
  205. }
  206. public function properties(string $uri, ?array $properties, int $depth): ?array
  207. {
  208. $target = $this->path . $uri;
  209. if (!file_exists($target)) {
  210. return null;
  211. }
  212. if (null === $properties) {
  213. $properties = Server::BASIC_PROPERTIES;
  214. }
  215. $out = [];
  216. foreach ($properties as $name) {
  217. $v = $this->get_file_property($uri, $name, $depth);
  218. if (null !== $v) {
  219. $out[$name] = $v;
  220. }
  221. }
  222. return $out;
  223. }
  224. public function put(string $uri, $pointer, ?string $hash, ?int $mtime): bool
  225. {
  226. if (preg_match(self::PUT_IGNORE_PATTERN, basename($uri))) {
  227. return false;
  228. }
  229. if (!$this->canWrite($uri)) {
  230. throw new WebDAV_Exception('Access forbidden', 403);
  231. }
  232. $target = $this->path . $uri;
  233. $parent = dirname($target);
  234. if (is_dir($target)) {
  235. throw new WebDAV_Exception('Target is a directory', 409);
  236. }
  237. if (!file_exists($parent)) {
  238. mkdir($parent, 0770, true);
  239. }
  240. $new = !file_exists($target);
  241. $delete = false;
  242. $size = 0;
  243. $quota = disk_free_space($this->path);
  244. $tmp_file = $this->path . '.tmp.' . sha1($target);
  245. $out = fopen($tmp_file, 'w');
  246. while (!feof($pointer)) {
  247. $bytes = fread($pointer, 8192);
  248. $size += strlen($bytes);
  249. if ($size > $quota) {
  250. $delete = true;
  251. break;
  252. }
  253. fwrite($out, $bytes);
  254. }
  255. fclose($out);
  256. fclose($pointer);
  257. if ($delete) {
  258. @unlink($tmp_file);
  259. throw new WebDAV_Exception('Your quota is exhausted', 403);
  260. }
  261. elseif ($hash && md5_file($tmp_file) != $hash) {
  262. @unlink($tmp_file);
  263. throw new WebDAV_Exception('The data sent does not match the supplied MD5 hash', 400);
  264. }
  265. else {
  266. rename($tmp_file, $target);
  267. }
  268. if ($mtime) {
  269. @touch($target, $mtime);
  270. }
  271. return $new;
  272. }
  273. public function delete(string $uri): void
  274. {
  275. if (!$this->canWrite($uri)) {
  276. throw new WebDAV_Exception('Access forbidden', 403);
  277. }
  278. if ($this->canOnlyCreate($uri)) {
  279. throw new WebDAV_Exception('Access forbidden', 403);
  280. }
  281. $target = $this->path . $uri;
  282. if (!file_exists($target)) {
  283. throw new WebDAV_Exception('Target does not exist', 404);
  284. }
  285. if (!is_writeable($target)) {
  286. throw new WebDAV_Exception('File permissions says that you cannot delete this, sorry.', 403);
  287. }
  288. if (is_dir($target)) {
  289. foreach (self::glob($target, '/*') as $file) {
  290. $this->delete(substr($file, strlen($this->path)));
  291. }
  292. rmdir($target);
  293. }
  294. else {
  295. unlink($target);
  296. }
  297. }
  298. public function copymove(bool $move, string $uri, string $destination): bool
  299. {
  300. if (!$this->canWrite($uri)
  301. || !$this->canWrite($destination)
  302. || $this->canOnlyCreate($uri)) {
  303. throw new WebDAV_Exception('Access forbidden', 403);
  304. }
  305. $source = $this->path . $uri;
  306. $target = $this->path . $destination;
  307. $parent = dirname($target);
  308. if (!file_exists($source)) {
  309. throw new WebDAV_Exception('File not found', 404);
  310. }
  311. $overwritten = file_exists($target);
  312. if (!is_dir($parent)) {
  313. throw new WebDAV_Exception('Target parent directory does not exist', 409);
  314. }
  315. if (false === $move) {
  316. $quota = disk_free_space($this->path);
  317. if (filesize($source) > $quota) {
  318. throw new WebDAV_Exception('Your quota is exhausted', 403);
  319. }
  320. }
  321. if ($overwritten) {
  322. $this->delete($destination);
  323. }
  324. $method = $move ? 'rename' : 'copy';
  325. if ($method == 'copy' && is_dir($source)) {
  326. @mkdir($target, 0770, true);
  327. foreach ($iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source), \RecursiveIteratorIterator::SELF_FIRST) as $item)
  328. {
  329. if ($item->isDir()) {
  330. @mkdir($target . DIRECTORY_SEPARATOR . $iterator->getSubPathname());
  331. } else {
  332. copy($item, $target . DIRECTORY_SEPARATOR . $iterator->getSubPathname());
  333. }
  334. }
  335. }
  336. else {
  337. $method($source, $target);
  338. $this->getResourceProperties($uri)->move($destination);
  339. }
  340. return $overwritten;
  341. }
  342. public function copy(string $uri, string $destination): bool
  343. {
  344. return $this->copymove(false, $uri, $destination);
  345. }
  346. public function move(string $uri, string $destination): bool
  347. {
  348. return $this->copymove(true, $uri, $destination);
  349. }
  350. public function mkcol(string $uri): void
  351. {
  352. if (!$this->canWrite($uri)) {
  353. throw new WebDAV_Exception('Access forbidden', 403);
  354. }
  355. if (!disk_free_space($this->path)) {
  356. throw new WebDAV_Exception('Your quota is exhausted', 403);
  357. }
  358. $target = $this->path . $uri;
  359. $parent = dirname($target);
  360. if (file_exists($target)) {
  361. throw new WebDAV_Exception('There is already a file with that name', 405);
  362. }
  363. if (!file_exists($parent)) {
  364. throw new WebDAV_Exception('The parent directory does not exist', 409);
  365. }
  366. mkdir($target, 0770);
  367. }
  368. static public function getDirectoryMTime(string $path): int
  369. {
  370. $last = 0;
  371. $path = rtrim($path, '/');
  372. foreach (self::glob($path, '/*', GLOB_NOSORT) as $f) {
  373. if (is_dir($f)) {
  374. $m = self::getDirectoryMTime($f);
  375. if ($m > $last) {
  376. $last = $m;
  377. }
  378. }
  379. $m = filemtime($f);
  380. if ($m > $last) {
  381. $last = $m;
  382. }
  383. }
  384. return $last;
  385. }
  386. }
  387. class Server extends \KD2\WebDAV\Server
  388. {
  389. protected function html_directory(string $uri, iterable $list): ?string
  390. {
  391. $out = parent::html_directory($uri, $list);
  392. if (null !== $out) {
  393. $out = str_replace('<body>', sprintf('<body style="opacity: 0"><script type="text/javascript" src="%s/.webdav/webdav.js"></script>', rtrim($this->base_uri, '/')), $out);
  394. }
  395. return $out;
  396. }
  397. public function route(?string $uri = null): bool
  398. {
  399. if (!ANONYMOUS_WRITE && !ANONYMOUS_READ && !$this->storage->auth()) {
  400. $this->requireAuth();
  401. return true;
  402. }
  403. return parent::route($uri);
  404. }
  405. protected function requireAuth(): void
  406. {
  407. http_response_code(401);
  408. header('WWW-Authenticate: Basic realm="Please login"');
  409. echo '<h2>Error 401</h2><h1>You need to login to access this.</h1>';
  410. }
  411. public function error(WebDAV_Exception $e)
  412. {
  413. if ($e->getCode() == 403 && !$this->storage->auth() && count($this->storage->users)) {
  414. return;
  415. }
  416. parent::error($e);
  417. }
  418. protected string $_log = '';
  419. public function log(string $message, ...$params): void
  420. {
  421. if (!HTTP_LOG_FILE) {
  422. return;
  423. }
  424. $this->_log .= vsprintf($message, $params) . "\n";
  425. }
  426. public function __destruct()
  427. {
  428. if (!$this->_log) {
  429. return;
  430. }
  431. file_put_contents(HTTP_LOG_FILE, $this->_log, \FILE_APPEND);
  432. }
  433. }
  434. }
  435. namespace {
  436. use PicoDAV\Server;
  437. use PicoDAV\Storage;
  438. $uri = strtok($_SERVER['REQUEST_URI'], '?');
  439. $root = substr(__DIR__, strlen($_SERVER['DOCUMENT_ROOT']));
  440. if (false !== strpos($uri, '..')) {
  441. http_response_code(404);
  442. die('Invalid URL');
  443. }
  444. $relative_uri = ltrim(substr($uri, strlen($root)), '/');
  445. if (!empty($_SERVER['SERVER_SOFTWARE']) && stristr($_SERVER['SERVER_SOFTWARE'], 'apache') && !file_exists(__DIR__ . '/.htaccess')) {
  446. file_put_contents(__DIR__ . '/.htaccess', /*__HTACCESS__*/);
  447. }
  448. if ($relative_uri == '.webdav/webdav.js' || $relative_uri == '.webdav/webdav.css') {
  449. http_response_code(200);
  450. if ($relative_uri == '.webdav/webdav.js') {
  451. header('Content-Type: text/javascript', true);
  452. }
  453. else {
  454. header('Content-Type: text/css', true);
  455. }
  456. $seconds_to_cache = 3600 * 24 * 5;
  457. $ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
  458. header("Expires: " . $ts);
  459. header("Pragma: cache");
  460. header("Cache-Control: max-age=" . $seconds_to_cache);
  461. $fp = fopen(__FILE__, 'r');
  462. if ($relative_uri == '.webdav/webdav.js') {
  463. fseek($fp, __PHP_SIZE__, SEEK_SET);
  464. echo fread($fp, __JS_SIZE__);
  465. }
  466. else {
  467. fseek($fp, __PHP_SIZE__ + __JS_SIZE__, SEEK_SET);
  468. echo fread($fp, __CSS_SIZE__);
  469. }
  470. fclose($fp);
  471. exit;
  472. }
  473. const CONFIG_FILE = __DIR__ . '/.picodav.ini';
  474. define('PicoDAV\INTERNAL_FILES', ['.picodav.ini', basename(__FILE__), '.webdav/webdav.js', '.webdav/webdav.css']);
  475. const DEFAULT_CONFIG = [
  476. 'ANONYMOUS_READ' => true,
  477. 'ANONYMOUS_WRITE' => false,
  478. 'HTTP_LOG_FILE' => null,
  479. ];
  480. $config = [];
  481. $storage = new Storage;
  482. if (file_exists(CONFIG_FILE)) {
  483. $config = parse_ini_file(CONFIG_FILE, true);
  484. $users = array_filter($config, 'is_array');
  485. $config = array_diff_key($config, $users);
  486. $config = array_change_key_case($config, \CASE_UPPER);
  487. $replace = [];
  488. // Encrypt plaintext passwords
  489. foreach ($users as $name => $properties) {
  490. if (isset($properties['password']) && substr($properties['password'], 0, 1) != '$') {
  491. $users[$name]['password'] = $replace[$name] = password_hash($properties['password'], null);
  492. }
  493. }
  494. if (count($replace)) {
  495. $lines = file(CONFIG_FILE);
  496. $current = null;
  497. foreach ($lines as &$line) {
  498. if (preg_match('/^\s*\[(\w+)\]\s*$/', $line, $match)) {
  499. $current = $match[1];
  500. continue;
  501. }
  502. if ($current && isset($replace[$current]) && preg_match('/^\s*password\s*=/', $line)) {
  503. $line = sprintf("password = %s\n", var_export($replace[$current], true));
  504. }
  505. }
  506. unset($line, $current);
  507. file_put_contents(CONFIG_FILE, implode('', $lines));
  508. }
  509. $storage->users = $users;
  510. }
  511. foreach (DEFAULT_CONFIG as $key => $value) {
  512. if (array_key_exists($key, $config)) {
  513. $value = $config[$key];
  514. }
  515. if (is_bool(DEFAULT_CONFIG[$key])) {
  516. $value = boolval($value);
  517. }
  518. define('PicoDAV\\' . $key, $value);
  519. }
  520. $dav = new Server;
  521. $dav->setStorage($storage);
  522. $dav->setBaseURI($root);
  523. if (!$dav->route($uri)) {
  524. http_response_code(404);
  525. die('Invalid URL, sorry');
  526. }
  527. exit;
  528. }