server.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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 true;
  63. }
  64. return false;
  65. }
  66. public function canWrite(string $uri): bool
  67. {
  68. if (!$this->user && !ANONYMOUS_WRITE) {
  69. return false;
  70. }
  71. if (!$this->canRead($uri)) {
  72. return false;
  73. }
  74. if (ANONYMOUS_WRITE) {
  75. return true;
  76. }
  77. if (!empty($this->users[$this->user]['write'])) {
  78. return true;
  79. }
  80. return false;
  81. }
  82. public function list(string $uri, ?array $properties): iterable
  83. {
  84. if (!$this->canRead($uri)) {
  85. throw new WebDAV_Exception('Access forbidden', 403);
  86. }
  87. $dirs = self::glob($this->path . $uri, '/*', \GLOB_ONLYDIR);
  88. $dirs = array_map('basename', $dirs);
  89. $dirs = array_filter($dirs, fn($a) => $this->canRead(ltrim($uri . '/' . $a, '/')));
  90. natcasesort($dirs);
  91. $files = self::glob($this->path . $uri, '/*');
  92. $files = array_map('basename', $files);
  93. $files = array_diff($files, $dirs);
  94. // Remove PHP files and dot-files from listings
  95. $files = array_filter($files, fn($a) => $this->canRead(ltrim($uri . '/' . $a, '/')));
  96. natcasesort($files);
  97. $files = array_flip(array_merge($dirs, $files));
  98. $files = array_map(fn($a) => null, $files);
  99. return $files;
  100. }
  101. public function get(string $uri): ?array
  102. {
  103. if (!$this->canRead($uri)) {
  104. throw new WebDAV_Exception('Access forbidden', 403);
  105. }
  106. $path = $this->path . $uri;
  107. if (!file_exists($path)) {
  108. return null;
  109. }
  110. return ['path' => $path];
  111. }
  112. public function exists(string $uri): bool
  113. {
  114. return file_exists($this->path . $uri);
  115. }
  116. public function get_file_property(string $uri, string $name, int $depth)
  117. {
  118. $target = $this->path . $uri;
  119. switch ($name) {
  120. case 'DAV::getcontentlength':
  121. return is_dir($target) ? null : filesize($target);
  122. case 'DAV::getcontenttype':
  123. // ownCloud app crashes if mimetype is provided for a directory
  124. // https://github.com/owncloud/android/issues/3768
  125. return is_dir($target) ? null : mime_content_type($target);
  126. case 'DAV::resourcetype':
  127. return is_dir($target) ? 'collection' : '';
  128. case 'DAV::getlastmodified':
  129. if (!$uri && $depth == 0 && is_dir($target)) {
  130. $mtime = self::getDirectoryMTime($target);
  131. }
  132. else {
  133. $mtime = filemtime($target);
  134. }
  135. if (!$mtime) {
  136. return null;
  137. }
  138. return new \DateTime('@' . $mtime);
  139. case 'DAV::displayname':
  140. return basename($target);
  141. case 'DAV::ishidden':
  142. return basename($target)[0] == '.';
  143. case 'DAV::getetag':
  144. $hash = filemtime($target) . filesize($target);
  145. return md5($hash . $target);
  146. case 'DAV::lastaccessed':
  147. return new \DateTime('@' . fileatime($target));
  148. case 'DAV::creationdate':
  149. return new \DateTime('@' . filectime($target));
  150. case 'http://owncloud.org/ns:permissions':
  151. $permissions = 'G';
  152. if (is_writeable($target) && $this->canWrite($uri)) {
  153. $permissions .= 'DNVWCK';
  154. }
  155. return $permissions;
  156. case WebDAV::PROP_DIGEST_MD5:
  157. if (!is_file($target)) {
  158. return null;
  159. }
  160. return md5_file($target);
  161. default:
  162. break;
  163. }
  164. return null;
  165. }
  166. public function properties(string $uri, ?array $properties, int $depth): ?array
  167. {
  168. $target = $this->path . $uri;
  169. if (!file_exists($target)) {
  170. return null;
  171. }
  172. if (null === $properties) {
  173. $properties = WebDAV::BASIC_PROPERTIES;
  174. }
  175. $out = [];
  176. foreach ($properties as $name) {
  177. $v = $this->get_file_property($uri, $name, $depth);
  178. if (null !== $v) {
  179. $out[$name] = $v;
  180. }
  181. }
  182. return $out;
  183. }
  184. public function put(string $uri, $pointer, ?string $hash, ?int $mtime): bool
  185. {
  186. if (preg_match(self::PUT_IGNORE_PATTERN, basename($uri))) {
  187. return false;
  188. }
  189. if (!$this->canWrite($uri)) {
  190. throw new WebDAV_Exception('Access forbidden', 403);
  191. }
  192. $target = $this->path . $uri;
  193. $parent = dirname($target);
  194. if (is_dir($target)) {
  195. throw new WebDAV_Exception('Target is a directory', 409);
  196. }
  197. if (!file_exists($parent)) {
  198. mkdir($parent, 0770, true);
  199. }
  200. $new = !file_exists($target);
  201. $delete = false;
  202. $size = 0;
  203. $quota = disk_free_space($this->path);
  204. $tmp_file = '.tmp.' . sha1($target);
  205. $out = fopen($tmp_file, 'w');
  206. while (!feof($pointer)) {
  207. $bytes = fread($pointer, 8192);
  208. $size += strlen($bytes);
  209. if ($size > $quota) {
  210. $delete = true;
  211. break;
  212. }
  213. fwrite($out, $bytes);
  214. }
  215. fclose($out);
  216. fclose($pointer);
  217. if ($delete) {
  218. @unlink($tmp_file);
  219. throw new WebDAV_Exception('Your quota is exhausted', 403);
  220. }
  221. elseif ($hash && md5_file($tmp_file) != $hash) {
  222. @unlink($tmp_file);
  223. throw new WebDAV_Exception('The data sent does not match the supplied MD5 hash', 400);
  224. }
  225. else {
  226. rename($tmp_file, $target);
  227. }
  228. if ($mtime) {
  229. @touch($target, $mtime);
  230. }
  231. return $new;
  232. }
  233. public function delete(string $uri): void
  234. {
  235. if (!$this->canWrite($uri)) {
  236. throw new WebDAV_Exception('Access forbidden', 403);
  237. }
  238. $target = $this->path . $uri;
  239. if (!file_exists($target)) {
  240. throw new WebDAV_Exception('Target does not exist', 404);
  241. }
  242. if (!is_writeable($target)) {
  243. throw new WebDAV_Exception('File permissions says that you cannot delete this, sorry.', 403);
  244. }
  245. if (is_dir($target)) {
  246. foreach (self::glob($target, '/*') as $file) {
  247. $this->delete(substr($file, strlen($this->path)));
  248. }
  249. rmdir($target);
  250. }
  251. else {
  252. unlink($target);
  253. }
  254. }
  255. public function copymove(bool $move, string $uri, string $destination): bool
  256. {
  257. if (!$this->canWrite($uri)) {
  258. throw new WebDAV_Exception('Access forbidden', 403);
  259. }
  260. if (!$this->canWrite($destination)) {
  261. throw new WebDAV_Exception('Access forbidden', 403);
  262. }
  263. $source = $this->path . $uri;
  264. $target = $this->path . $destination;
  265. $parent = dirname($target);
  266. if (!file_exists($source)) {
  267. throw new WebDAV_Exception('File not found', 404);
  268. }
  269. $overwritten = file_exists($target);
  270. if (!is_dir($parent)) {
  271. throw new WebDAV_Exception('Target parent directory does not exist', 409);
  272. }
  273. if (false === $move) {
  274. $quota = disk_free_space($this->path);
  275. if (filesize($source) > $quota) {
  276. throw new WebDAV_Exception('Your quota is exhausted', 403);
  277. }
  278. }
  279. if ($overwritten) {
  280. $this->delete($destination);
  281. }
  282. $method = $move ? 'rename' : 'copy';
  283. if ($method == 'copy' && is_dir($source)) {
  284. @mkdir($target, 0770, true);
  285. foreach ($iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source), \RecursiveIteratorIterator::SELF_FIRST) as $item)
  286. {
  287. if ($item->isDir()) {
  288. @mkdir($target . DIRECTORY_SEPARATOR . $iterator->getSubPathname());
  289. } else {
  290. copy($item, $target . DIRECTORY_SEPARATOR . $iterator->getSubPathname());
  291. }
  292. }
  293. }
  294. else {
  295. $method($source, $target);
  296. $this->getResourceProperties($uri)->move($destination);
  297. }
  298. return $overwritten;
  299. }
  300. public function copy(string $uri, string $destination): bool
  301. {
  302. return $this->copymove(false, $uri, $destination);
  303. }
  304. public function move(string $uri, string $destination): bool
  305. {
  306. return $this->copymove(true, $uri, $destination);
  307. }
  308. public function mkcol(string $uri): void
  309. {
  310. if (!$this->canWrite($uri)) {
  311. throw new WebDAV_Exception('Access forbidden', 403);
  312. }
  313. if (!disk_free_space($this->path)) {
  314. throw new WebDAV_Exception('Your quota is exhausted', 403);
  315. }
  316. $target = $this->path . $uri;
  317. $parent = dirname($target);
  318. if (file_exists($target)) {
  319. throw new WebDAV_Exception('There is already a file with that name', 405);
  320. }
  321. if (!file_exists($parent)) {
  322. throw new WebDAV_Exception('The parent directory does not exist', 409);
  323. }
  324. mkdir($target, 0770);
  325. }
  326. static public function getDirectoryMTime(string $path): int
  327. {
  328. $last = 0;
  329. $path = rtrim($path, '/');
  330. foreach (self::glob($path, '/*', GLOB_NOSORT) as $f) {
  331. if (is_dir($f)) {
  332. $m = self::getDirectoryMTime($f);
  333. if ($m > $last) {
  334. $last = $m;
  335. }
  336. }
  337. $m = filemtime($f);
  338. if ($m > $last) {
  339. $last = $m;
  340. }
  341. }
  342. return $last;
  343. }
  344. }
  345. class Server extends \KD2\WebDAV\Server
  346. {
  347. protected function html_directory(string $uri, iterable $list): ?string
  348. {
  349. $out = parent::html_directory($uri, $list);
  350. if (null !== $out) {
  351. $out = str_replace('<body>', sprintf('<body style="opacity: 0"><script type="text/javascript" src="%s/webdav.js"></script>', rtrim($this->base_uri, '/')), $out);
  352. }
  353. return $out;
  354. }
  355. function error(WebDAV_Exception $e)
  356. {
  357. if ($e->getCode() == 403 && !$this->storage->auth() && count($this->storage->users)) {
  358. $user = $_SERVER['PHP_AUTH_USER'] ?? null;
  359. http_response_code(401);
  360. header('WWW-Authenticate: Basic realm="Please login"');
  361. echo '<h2>Error 401</h2><h1>You need to login to access this.</h1>';
  362. return;
  363. }
  364. parent::error($e);
  365. }
  366. }
  367. }
  368. namespace {
  369. use PicoDAV\Server;
  370. use PicoDAV\Storage;
  371. $uri = strtok($_SERVER['REQUEST_URI'], '?');
  372. $root = substr(__DIR__, strlen($_SERVER['DOCUMENT_ROOT']));
  373. if (false !== strpos($uri, '..')) {
  374. http_response_code(404);
  375. die('Invalid URL');
  376. }
  377. $relative_uri = ltrim(substr($uri, strlen($root)), '/');
  378. if (!empty($_SERVER['SERVER_SOFTWARE']) && stristr($_SERVER['SERVER_SOFTWARE'], 'apache') && !file_exists(__DIR__ . '/.htaccess')) {
  379. file_put_contents(__DIR__ . '/.htaccess', /*__HTACCESS__*/);
  380. }
  381. if ($relative_uri == 'webdav.js' || $relative_uri == 'webdav.css') {
  382. http_response_code(200);
  383. if ($relative_uri == 'webdav.js') {
  384. header('Content-Type: text/javascript', true);
  385. }
  386. else {
  387. header('Content-Type: text/css', true);
  388. }
  389. $seconds_to_cache = 3600 * 24 * 365;
  390. $ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
  391. header("Expires: " . $ts);
  392. header("Pragma: cache");
  393. header("Cache-Control: max-age=" . $seconds_to_cache);
  394. $fp = fopen(__FILE__, 'r');
  395. if ($relative_uri == 'webdav.js') {
  396. fseek($fp, __PHP_SIZE__, SEEK_SET);
  397. echo fread($fp, __JS_SIZE__);
  398. }
  399. else {
  400. fseek($fp, __PHP_SIZE__ + __JS_SIZE__, SEEK_SET);
  401. echo fread($fp, __CSS_SIZE__);
  402. }
  403. fclose($fp);
  404. exit;
  405. }
  406. const CONFIG_FILE = __DIR__ . '/.picodav.ini';
  407. const INTERNAL_FILES = ['.picodav.ini', 'index.php', 'webdav.js', 'webdav.css'];
  408. const DEFAULT_CONFIG = [
  409. 'ANONYMOUS_READ' => false,
  410. 'ANONYMOUS_WRITE' => false,
  411. ];
  412. $config = [];
  413. $storage = new Storage;
  414. if (file_exists(CONFIG_FILE)) {
  415. $config = parse_ini_file(CONFIG_FILE, true);
  416. $users = array_filter($config, 'is_array');
  417. $config = array_diff_key($config, $users);
  418. $config = array_change_key_case($config, \CASE_UPPER);
  419. $replace = [];
  420. // Encrypt plaintext passwords
  421. foreach ($users as $name => $properties) {
  422. if (isset($properties['password']) && substr($properties['password'], 0, 1) != '$') {
  423. $users[$name]['password'] = $replace[$name] = password_hash($properties['password'], null);
  424. }
  425. }
  426. if (count($replace)) {
  427. $lines = file(CONFIG_FILE);
  428. $current = null;
  429. foreach ($lines as &$line) {
  430. if (preg_match('/^\s*\[(\w+)\]\s*$/', $line, $match)) {
  431. $current = $match[1];
  432. continue;
  433. }
  434. if ($current && isset($replace[$current]) && preg_match('/^\s*password\s*=/', $line)) {
  435. $line = sprintf("password = %s\n", var_export($replace[$current], true));
  436. }
  437. }
  438. unset($line, $current);
  439. file_put_contents(CONFIG_FILE, implode('', $lines));
  440. }
  441. $storage->users = $users;
  442. }
  443. foreach (DEFAULT_CONFIG as $key => $value) {
  444. if (array_key_exists($key, $config)) {
  445. $value = $config[$key];
  446. }
  447. if (is_bool(DEFAULT_CONFIG[$key])) {
  448. $value = boolval($value);
  449. }
  450. define('PicoDAV\\' . $key, $value);
  451. }
  452. $dav = new Server;
  453. $dav->setStorage($storage);
  454. $dav->setBaseURI($root);
  455. if (!$dav->route($uri)) {
  456. http_response_code(404);
  457. die('Invalid URL, sorry');
  458. }
  459. exit;
  460. }