1
0

server.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  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. $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) || is_dir($target) || !is_readable($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_algo, ?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', 507);
  260. }
  261. elseif ($hash && $hash_algo == 'MD5' && 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. elseif ($hash && $hash_algo == 'SHA1' && sha1_file($tmp_file) != $hash) {
  266. @unlink($tmp_file);
  267. throw new WebDAV_Exception('The data sent does not match the supplied SHA1 hash', 400);
  268. }
  269. else {
  270. rename($tmp_file, $target);
  271. }
  272. if ($mtime) {
  273. @touch($target, $mtime);
  274. }
  275. return $new;
  276. }
  277. public function delete(string $uri): void
  278. {
  279. if (!$this->canWrite($uri)) {
  280. throw new WebDAV_Exception('Access forbidden', 403);
  281. }
  282. if ($this->canOnlyCreate($uri)) {
  283. throw new WebDAV_Exception('Access forbidden', 403);
  284. }
  285. $target = $this->path . $uri;
  286. if (!file_exists($target)) {
  287. throw new WebDAV_Exception('Target does not exist', 404);
  288. }
  289. if (!is_writeable($target)) {
  290. throw new WebDAV_Exception('File permissions says that you cannot delete this, sorry.', 403);
  291. }
  292. if (is_dir($target)) {
  293. foreach (self::glob($target, '/*') as $file) {
  294. $this->delete(substr($file, strlen($this->path)));
  295. }
  296. rmdir($target);
  297. }
  298. else {
  299. unlink($target);
  300. }
  301. }
  302. public function copymove(bool $move, string $uri, string $destination): bool
  303. {
  304. if (!$this->canWrite($uri)
  305. || !$this->canWrite($destination)
  306. || $this->canOnlyCreate($uri)) {
  307. throw new WebDAV_Exception('Access forbidden', 403);
  308. }
  309. $source = $this->path . $uri;
  310. $target = $this->path . $destination;
  311. $parent = dirname($target);
  312. if (!file_exists($source)) {
  313. throw new WebDAV_Exception('File not found', 404);
  314. }
  315. $overwritten = file_exists($target);
  316. if (!is_dir($parent)) {
  317. throw new WebDAV_Exception('Target parent directory does not exist', 409);
  318. }
  319. if (false === $move) {
  320. $quota = disk_free_space($this->path);
  321. if (filesize($source) > $quota) {
  322. throw new WebDAV_Exception('Your quota is exhausted', 507);
  323. }
  324. }
  325. if ($overwritten) {
  326. $this->delete($destination);
  327. }
  328. $method = $move ? 'rename' : 'copy';
  329. if ($method == 'copy' && is_dir($source)) {
  330. @mkdir($target, 0770, true);
  331. foreach ($iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source), \RecursiveIteratorIterator::SELF_FIRST) as $item)
  332. {
  333. if ($item->isDir()) {
  334. @mkdir($target . DIRECTORY_SEPARATOR . $iterator->getSubPathname());
  335. } else {
  336. copy($item, $target . DIRECTORY_SEPARATOR . $iterator->getSubPathname());
  337. }
  338. }
  339. }
  340. else {
  341. $method($source, $target);
  342. $this->getResourceProperties($uri)->move($destination);
  343. }
  344. return $overwritten;
  345. }
  346. public function copy(string $uri, string $destination): bool
  347. {
  348. return $this->copymove(false, $uri, $destination);
  349. }
  350. public function move(string $uri, string $destination): bool
  351. {
  352. return $this->copymove(true, $uri, $destination);
  353. }
  354. public function mkcol(string $uri): void
  355. {
  356. if (!$this->canWrite($uri)) {
  357. throw new WebDAV_Exception('Access forbidden', 403);
  358. }
  359. if (!disk_free_space($this->path)) {
  360. throw new WebDAV_Exception('Your quota is exhausted', 507);
  361. }
  362. $target = $this->path . $uri;
  363. $parent = dirname($target);
  364. if (file_exists($target)) {
  365. throw new WebDAV_Exception('There is already a file with that name', 405);
  366. }
  367. if (!file_exists($parent)) {
  368. throw new WebDAV_Exception('The parent directory does not exist', 409);
  369. }
  370. mkdir($target, 0770);
  371. }
  372. static public function getDirectoryMTime(string $path): int
  373. {
  374. $last = 0;
  375. $path = rtrim($path, '/');
  376. foreach (self::glob($path, '/*', GLOB_NOSORT) as $f) {
  377. if (is_dir($f)) {
  378. $m = self::getDirectoryMTime($f);
  379. if ($m > $last) {
  380. $last = $m;
  381. }
  382. }
  383. $m = filemtime($f);
  384. if ($m > $last) {
  385. $last = $m;
  386. }
  387. }
  388. return $last;
  389. }
  390. }
  391. class Server extends \KD2\WebDAV\Server
  392. {
  393. protected function html_directory(string $uri, iterable $list): ?string
  394. {
  395. $out = parent::html_directory($uri, $list);
  396. if (null !== $out) {
  397. $out = str_replace('<body>', sprintf('<body style="opacity: 0"><script type="text/javascript" src="%s/.webdav/webdav.js"></script>', rtrim($this->base_uri, '/')), $out);
  398. }
  399. return $out;
  400. }
  401. public function route(?string $uri = null): bool
  402. {
  403. if (!ANONYMOUS_WRITE && !ANONYMOUS_READ && !$this->storage->auth()) {
  404. $this->requireAuth();
  405. return true;
  406. }
  407. return parent::route($uri);
  408. }
  409. protected function requireAuth(): void
  410. {
  411. http_response_code(401);
  412. header('WWW-Authenticate: Basic realm="Please login"');
  413. echo '<h2>Error 401</h2><h1>You need to login to access this.</h1>';
  414. }
  415. public function error(WebDAV_Exception $e)
  416. {
  417. if ($e->getCode() == 403 && !$this->storage->auth() && count($this->storage->users)) {
  418. return;
  419. }
  420. parent::error($e);
  421. }
  422. protected string $_log = '';
  423. public function log(string $message, ...$params): void
  424. {
  425. if (!HTTP_LOG_FILE) {
  426. return;
  427. }
  428. $this->_log .= vsprintf($message, $params) . "\n";
  429. }
  430. public function __destruct()
  431. {
  432. if (!$this->_log) {
  433. return;
  434. }
  435. file_put_contents(HTTP_LOG_FILE, $this->_log, \FILE_APPEND);
  436. }
  437. }
  438. }
  439. namespace {
  440. use PicoDAV\Server;
  441. use PicoDAV\Storage;
  442. $uri = strtok($_SERVER['REQUEST_URI'], '?');
  443. $self = $_SERVER['SCRIPT_FILENAME'];
  444. $self_dir = dirname($self);
  445. $root = substr(dirname($_SERVER['SCRIPT_FILENAME']), strlen($_SERVER['DOCUMENT_ROOT']));
  446. $root = '/' . ltrim($root, '/');
  447. if (false !== strpos($uri, '..')) {
  448. http_response_code(404);
  449. die('Invalid URL');
  450. }
  451. $relative_uri = ltrim(substr($uri, strlen($root)), '/');
  452. if (!empty($_SERVER['SERVER_SOFTWARE']) && stristr($_SERVER['SERVER_SOFTWARE'], 'apache') && !file_exists($self_dir . '/.htaccess')) {
  453. file_put_contents($self_dir . '/.htaccess', str_replace('index.php', basename($self), /*__HTACCESS__*/));
  454. }
  455. if ($relative_uri == '.webdav/webdav.js' || $relative_uri == '.webdav/webdav.css') {
  456. http_response_code(200);
  457. if ($relative_uri == '.webdav/webdav.js') {
  458. header('Content-Type: text/javascript', true);
  459. }
  460. else {
  461. header('Content-Type: text/css', true);
  462. }
  463. $seconds_to_cache = 3600 * 24 * 5;
  464. $ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
  465. header("Expires: " . $ts);
  466. header("Pragma: cache");
  467. header("Cache-Control: max-age=" . $seconds_to_cache);
  468. $fp = fopen(__FILE__, 'r');
  469. if ($relative_uri == '.webdav/webdav.js') {
  470. fseek($fp, __PHP_SIZE__, SEEK_SET);
  471. echo fread($fp, __JS_SIZE__);
  472. }
  473. else {
  474. fseek($fp, __PHP_SIZE__ + __JS_SIZE__, SEEK_SET);
  475. echo fread($fp, __CSS_SIZE__);
  476. }
  477. fclose($fp);
  478. exit;
  479. }
  480. $config_file = $self_dir . '/.picodav.ini';
  481. define('PicoDAV\INTERNAL_FILES', ['.picodav.ini', $self_dir, '.webdav/webdav.js', '.webdav/webdav.css']);
  482. const DEFAULT_CONFIG = [
  483. 'ANONYMOUS_READ' => true,
  484. 'ANONYMOUS_WRITE' => false,
  485. 'HTTP_LOG_FILE' => null,
  486. ];
  487. $config = [];
  488. $storage = new Storage($self_dir);
  489. if (file_exists($config_file)) {
  490. $config = parse_ini_string(file_get_contents($config_file), true, INI_SCANNER_TYPED);
  491. $users = array_filter($config, 'is_array');
  492. $config = array_diff_key($config, $users);
  493. $config = array_change_key_case($config, \CASE_UPPER);
  494. $replace = [];
  495. // Encrypt plaintext passwords
  496. foreach ($users as $name => $properties) {
  497. if (isset($properties['password']) && substr($properties['password'], 0, 1) != '$') {
  498. $users[$name]['password'] = $replace[$name] = password_hash($properties['password'], null);
  499. }
  500. }
  501. if (count($replace)) {
  502. $lines = file($config_file);
  503. $current = null;
  504. foreach ($lines as &$line) {
  505. if (preg_match('/^\s*\[(\w+)\]\s*$/', $line, $match)) {
  506. $current = $match[1];
  507. continue;
  508. }
  509. if ($current && isset($replace[$current]) && preg_match('/^\s*password\s*=/', $line)) {
  510. $line = sprintf("password = %s\n", var_export($replace[$current], true));
  511. }
  512. }
  513. unset($line, $current);
  514. file_put_contents($config_file, implode('', $lines));
  515. }
  516. $storage->users = $users;
  517. }
  518. foreach (DEFAULT_CONFIG as $key => $value) {
  519. if (array_key_exists($key, $config)) {
  520. $value = $config[$key];
  521. }
  522. if (is_bool(DEFAULT_CONFIG[$key])) {
  523. $value = boolval($value);
  524. }
  525. define('PicoDAV\\' . $key, $value);
  526. }
  527. $dav = new Server();
  528. $dav->setStorage($storage);
  529. $dav->setBaseURI($root);
  530. if (!$dav->route($uri)) {
  531. http_response_code(404);
  532. die('Unknown URL, sorry.');
  533. }
  534. exit;
  535. }