Phoebe/WebDAV.pm untested

filter: Statementstmt 0.0% 0 / 495 Branchbran 0.0% 0 / 192 Conditioncond 0.0% 0 / 139 MC/DCmcdc 0.0% 0 / 77 Subroutinesub 0.0% 0 / 29 Podpod 0.0% 0 / 15 totaltotal 0.0% 0 / 947 CC 97 SCAR 63.3
CC
97
Cov
0%
propfind
1640.0
write_page
132.0
write_file
90.0
CRAP 562.4
1 # -*- mode: perl -*-
2 # Copyright (C) 2005–2021 Alex Schroeder <alex@gnu.org>
3  
4 # This program is free software: you can redistribute it and/or modify it under
5 # the terms of the GNU Affero General Public License as published by the Free
6 # Software Foundation, either version 3 of the License, or (at your option) any
7 # later version.
8 #
9 # This program is distributed in the hope that it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11 # FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
12 # details.
13 #
14 # You should have received a copy of the GNU Affero General Public License along
15 # with this program. If not, see <https://www.gnu.org/licenses/>.
16  
17 =encoding utf8
18  
19 =head1 NAME
20  
21 App::Phoebe::WebDAV - add WebDAV to Phoebe wiki
22  
23 =head1 DESCRIPTION
24  
25 This allows users to mount the wiki as a remote server using WebDAV. If you
26 start it locally, for example, you should be able to mount
27 L<davs://localhost:1965/> as a remote server using your file manager (i.e.
28 Files, Finder, Windows Explorer, whatever it is called). Alternatively, you can
29 use a dedicated WebDAV client such as C<cadaver>.
30  
31 If you want to have write access, you need to provide a username and password if
32 Phoebe requires a token. By default, the token required by Phoebe is "hello".
33 The username you provide is ignored. The password must match one of the tokens.
34  
35 If you use a client such as C<cadaver>, it'll ask you for a username and
36 password when you use the "put" command for the first time. If you use the Gnome
37 Text Editor to edit the file, this fails. The fix is to mount
38 L<davs://localhost:1965/> instead. This forces Gnome Files to ask you for a
39 username and password, and once you provide it, Gnome Text Editor can save
40 files.
41  
42 =head1 SEE ALSO
43  
44 L<RFC 4918|https://datatracker.ietf.org/doc/html/rfc4918> defines WebDAV
45 including the PROPFIND method.
46  
47 L<RFC 2616|https://datatracker.ietf.org/doc/html/rfc2616> defines HTTP/1.1
48 including the OPTION and PUT methods.
49  
50 L<RFC 2617|https://datatracker.ietf.org/doc/html/rfc2617> defines Basic
51 Authentication.
52  
53 =cut
54  
55 package App::Phoebe::WebDAV;
56 use App::Phoebe::Web qw(handle_http_header);
57 use App::Phoebe qw(@request_handlers @extensions run_extensions $server
58 $log host_regex space_regex space port wiki_dir pages files
59 with_lock bogus_hash);
60 use File::Slurper qw(read_text write_text read_binary write_binary read_dir);
61 use HTTP::Date qw(time2str time2isoz);
62 use Digest::MD5 qw(md5_base64);
63 use Encode qw(encode_utf8 decode_utf8);
64 use Mojo::Util qw(b64_decode);
65 use File::stat;
66 use Modern::Perl;
67 use File::MimeInfo::Magic;
68 use URI::Escape;
69 use XML::LibXML;
70 use IO::Scalar;
71 use utf8;
72  
73 unshift(@request_handlers, '^(OPTIONS|PROPFIND|PUT|DELETE|COPY|MOVE) .* HTTP/1\.1$' => \&handle_http_header);
74  
75 # note that the requests handled here must be protected in
76 # App::Phoebe::RegisteredEditorsOnly!
77 push(@extensions, \&process_webdav);
78  
79 sub process_webdav {
80 my ($stream, $request, $headers, $buffer) = @_;
81 my $hosts = host_regex();
82 my $port = port($stream);
83 my $spaces = space_regex();
84 my ($method, $host, $space, $path, $id);
85 if (($space, $path, $id)
86 = $request =~ m!^OPTIONS (?:/($spaces))?(/(?:login|(?:file|page|raw)(?:/([^/]*))?)?)? HTTP/1\.1$!
87 and ($host) = $headers->{host} =~ m!^($hosts)(?::$port)$!) {
88 return if $path eq "/login" and not authorize($stream, $host, space($stream, $host, $space), $headers);
89 options($stream, map { decode_utf8(uri_unescape($_)) } $path, $id);
90 } elsif (($space, $path, $id)
91 = $request =~ m!^PROPFIND (?:/($spaces))?(/(?:login/?|(?:file|page|raw)(?:/([^/]*))?)?)? HTTP/1\.1$!
92 and ($host) = $headers->{host} =~ m!^($hosts)(?::$port)$!) {
93 propfind($stream, $host, space($stream, $host, $space), (map { decode_utf8(uri_unescape($_)) } $path, $id), $headers, $buffer);
94 } elsif (($space, $path, $id)
95 = $request =~ m!^PUT (?:/($spaces))?(/(?:file|raw)/([^/]*)) HTTP/1\.1$!
96 and ($host) = $headers->{host} =~ m!^($hosts)(?::$port)$!) {
97 put($stream, $host, space($stream, $host, $space), (map { decode_utf8(uri_unescape($_)) } $path, $id), $headers, $buffer);
98 } elsif (($space, $path, $id)
99 = $request =~ m!^DELETE (?:/($spaces))?(/(?:file|raw)/([^/]*)) HTTP/1\.1$!
100 and ($host) = $headers->{host} =~ m!^($hosts)(?::$port)$!) {
101 remove($stream, $host, space($stream, $host, $space), (map { decode_utf8(uri_unescape($_)) } $path, $id), $headers);
102 } elsif (($space, $path, $id)
103 = $request =~ m!^COPY (?:/($spaces))?(/(?:file|raw)/([^/]*)) HTTP/1\.1$!
104 and ($host) = $headers->{host} =~ m!^($hosts)(?::$port)$!) {
105 copy($stream, $host, space($stream, $host, $space), (map { decode_utf8(uri_unescape($_)) } $path, $id), $headers);
106 } elsif (($space, $path, $id)
107 = $request =~ m!^MOVE (?:/($spaces))?(/(?:file|raw)/([^/]*)) HTTP/1\.1$!
108 and ($host) = $headers->{host} =~ m!^($hosts)(?::$port)$!) {
109 move($stream, $host, space($stream, $host, $space), (map { decode_utf8(uri_unescape($_)) } $path, $id), $headers);
110 } else {
111 return 0;
112 }
113 return 1;
114 }
115  
116 my %implemented = (
117 options => '*',
118 propfind => '*',
119 get => 'r', # handled by App::Phoebe::Web
120 put => 'w',
121 delete => 'w',
122 copy => 'w',
123 move => 'w',
124 );
125  
126 sub options {
127 my ($stream, $path, $id) = @_;
128 my $allow = join(',', map { uc }
129 grep { $implemented{$_} eq '*'
130 or $implemented{$_} eq 'r' and $id
131 or $implemented{$_} eq 'w' and $id and $path =~ m!^/(raw|file)/.! }
132 keys %implemented);
133 $log->debug("OPTIONS: $allow");
134 $stream->write("HTTP/1.1 200 OK\r\n");
135 $stream->write("DAV: 1\r\n");
136 $stream->write("Allow: $allow\r\n");
137 $stream->write("\r\n");
138 }
139  
140 sub propfind {
141 my ($stream, $host, $space, $path, $id, $headers, $buffer) = @_;
142 $path //= "/";
143 my $depth = $headers->{depth} // "infinity";
144 $log->debug("PROPFIND depth: $depth");
145 $log->debug("PROPFIND content: $buffer");
146  
147 my $parser = XML::LibXML->new;
148 my $req;
149 eval { $req = $parser->parse_string($buffer); };
150 if ($@) {
151 webdav_error($stream, "Cannot parse the PROPFIND body");
152 $log->warn("PROPFIND parse: $@");
153 return;
154 }
155  
156 # what properties do we need?
157 my $reqinfo;
158 my @reqprops;
159 $reqinfo = $req->find('/*/*')->shift->localname;
160 if ($reqinfo eq 'prop') {
161 for my $node ($req->find('/*/*/*')->get_nodelist) {
162 push @reqprops, [ $node->namespaceURI, $node->localname ];
163 }
164 }
165 $log->debug("PROPFIND requested properties: " . join(", ", map {join "", @$_} @reqprops));
166  
167 my @resources;
168 my $re = '^' . quotemeta($id) . '$' if $id;
169 push(@resources, "/")
170 if $path eq "/";
171 push(@resources, map { "/$_/" } @{$server->{wiki_space}}) # all of them, but only at the top level
172 if not $space and $path eq "/" and $depth ne "0";
173 push(@resources, "/login/")
174 if $path eq "/" and $depth ne "0"
175 or $path =~ m!^/login/?$!;
176 push(@resources, "/page/")
177 if $path eq "/" and $depth ne "0"
178 or $path =~ m!^/page/?$!;
179 push(@resources, "/raw/")
180 if $path eq "/" and $depth ne "0"
181 or $path =~ m!^/raw/?$!;
182 push(@resources, map { "/page/$_" } pages($stream, $host, $space))
183 if $path eq "/" and $depth eq "infinity"
184 or $path =~ m!^/page/?$! and $depth ne "0";
185 push(@resources, map { "/raw/$_" } pages($stream, $host, $space))
186 if $path eq "/" and $depth eq "infinity"
187 or $path =~ m!^/raw/?$!;
188 push(@resources, map { "/page/$_" } pages($stream, $host, $space, $re)) # only if it exists!
189 if $id and $path eq "/page/$id";
190 push(@resources, map { "/raw/$_" } pages($stream, $host, $space, $re)) # only if it exists!
191 if $id and $path eq "/raw/$id";
192 push(@resources, "/file/")
193 if $path eq "/" and $depth ne "0"
194 or $path =~ m!^/file/?$!;
195 push(@resources, map { "/file/$_" } files($stream, $host, $space))
196 if $path eq "/" and $depth eq "infinity"
197 or $path =~ m!^/file/?$! and $depth ne "0";
198 push(@resources, map { "/file/$_" } files($stream, $host, $space, $re))
199 if $id and $path eq "/file/$id";
200  
201 my $doc = XML::LibXML::Document->new('1.0', 'utf-8');
202 my $multistat = $doc->createElement('D:multistatus');
203 $multistat->setAttribute('xmlns:D', 'DAV:');
204 $doc->setDocumentElement($multistat);
205  
206 my $dir = wiki_dir($host, $space);
207  
208 for my $resource (@resources) {
209 # skip "hidden" files in the Unix world
210 # and prevent path traversal using ..
211 next if $resource =~ m!/\.!;
212 # Names
213 my $mime;
214 my $is_dir;
215 my $filename;
216 if ($resource eq "/") {
217 $filename = $dir;
218 $is_dir = 1;
219 $mime = "inode/directory";
220 } elsif ($resource =~ m!/([^/]+)/$!) {
221 # the raw directory is a "fake" and is actually the page directory
222 $filename = $dir . ($1 eq "raw" ? "/page" : $resource);
223 $is_dir = 1;
224 $mime = "inode/directory";
225 } elsif ($resource =~ m!/page/([^/]+)$!) {
226 $filename = $dir . "/page/$1.gmi";
227 $is_dir = 0;
228 $mime = "text/html";
229 } elsif ($resource =~ m!/raw/([^/]+)$!) {
230 # the raw directory is a "fake" and is actually the page directory
231 $filename = $dir . "/page/$1.gmi";
232 $is_dir = 0;
233 $mime = "text/plain";
234 } elsif ($resource =~ m!/file/([^/]+)$!) {
235 $filename = $dir . $resource;
236 $is_dir = 0;
237 if (-f "$dir/meta/$1") {
238 # MIME-type for files requires opening the meta files! 😭
239 my %meta = (map { split(/: /, $_, 2) } split /\n/, read_text "$dir/meta/$1");
240 if ($meta{'content-type'}) {
241 $mime = $meta{'content-type'};
242 }
243 }
244 $mime //= "application/octet-stream"; # fallback for binary files
245 } else {
246 $log->error("Requested $resource");
247 next;
248 }
249  
250 $log->debug("Processing $dir$resource");
251  
252 # A stat call for every file and every page! 😭
253 my ($size, $mtime, $ctime, $sb) = (0, 0, 0);
254 if ($resource eq "/login/") {
255 $size = "";
256 $mtime = $ctime = time;
257 } elsif ($sb = stat($filename)) {
258 $size = $sb->size;
259 $mtime = $sb->mtime;
260 $ctime = $sb->ctime;
261 }
262  
263 # Modified time is stringified human readable HTTP::Date style
264 $mtime = time2str($mtime);
265  
266 # Created time is ISO format: We need to tidy up the date format - isoz
267 # isn't exactly what we want
268 $ctime = time2isoz($ctime);
269 $ctime =~ s/ /T/;
270 $ctime =~ s/Z//;
271  
272 my $resp = $doc->createElement('D:response');
273 $multistat->addChild($resp);
274 my $href = $doc->createElement('D:href');
275 $href->appendText(to_url($space, $resource));
276 $resp->addChild($href);
277 my $okprops = $doc->createElement('D:prop');
278 my $nfprops = $doc->createElement('D:prop');
279 my $prop;
280 if ($reqinfo eq 'prop') {
281 my %prefixes = ('DAV:' => 'D');
282 my $i = 0;
283 for my $reqprop (@reqprops) {
284 my ($ns, $name) = @$reqprop;
285 if ($ns eq 'DAV:' && $name eq 'creationdate') {
286 $prop = $doc->createElement('D:creationdate');
287 $prop->appendText($ctime);
288 $okprops->addChild($prop);
289 } elsif ($ns eq 'DAV:' && $name eq 'getcontentlength') {
290 $prop = $doc->createElement('D:getcontentlength');
291 $prop->appendText($size);
292 $okprops->addChild($prop);
293 } elsif ($ns eq 'DAV:' && $name eq 'getcontenttype') {
294 $prop = $doc->createElement('D:getcontenttype');
295 $prop->appendText($mime);
296 $okprops->addChild($prop);
297 } elsif ($ns eq 'DAV:' && $name eq 'getlastmodified') {
298 $prop = $doc->createElement('D:getlastmodified');
299 $prop->appendText($mtime);
300 $okprops->addChild($prop);
301 } elsif ($ns eq 'DAV:' && $name eq 'resourcetype') {
302 $prop = $doc->createElement('D:resourcetype');
303 if ($is_dir) {
304 my $col = $doc->createElement('D:collection');
305 $prop->addChild($col);
306 }
307 $okprops->addChild($prop);
308 } else {
309 my $prefix = $prefixes{$ns};
310 if (!defined $prefix) {
311 $prefix = 'i' . $i++;
312 # mod_dav sets <response> 'xmlns' attribute - whatever
313 #$nfprops->setAttribute("xmlns:$prefix", $ns);
314 $resp->setAttribute("xmlns:$prefix", $ns);
315 $prefixes{$ns} = $prefix;
316 }
317 $prop = $doc->createElement("$prefix:$name");
318 $nfprops->addChild($prop);
319 }
320 }
321 } elsif ($reqinfo eq 'propname') {
322 $prop = $doc->createElement('D:creationdate');
323 $okprops->addChild($prop);
324 $prop = $doc->createElement('D:getcontentlength');
325 $okprops->addChild($prop);
326 $prop = $doc->createElement('D:getcontenttype');
327 $okprops->addChild($prop);
328 $prop = $doc->createElement('D:getlastmodified');
329 $okprops->addChild($prop);
330 $prop = $doc->createElement('D:resourcetype');
331 $okprops->addChild($prop);
332 } else {
333 $prop = $doc->createElement('D:creationdate');
334 $prop->appendText($ctime);
335 $okprops->addChild($prop);
336 $prop = $doc->createElement('D:getcontentlength');
337 $prop->appendText($size);
338 $okprops->addChild($prop);
339 $prop = $doc->createElement('D:getcontenttype');
340 $prop->appendText($mime);
341 $okprops->addChild($prop);
342 $prop = $doc->createElement('D:getlastmodified');
343 $prop->appendText($mtime);
344 $okprops->addChild($prop);
345 $prop = $doc->createElement('D:resourcetype');
346 if ($is_dir) {
347 my $col = $doc->createElement('D:collection');
348 $prop->addChild($col);
349 }
350 $okprops->addChild($prop);
351 }
352 if ($okprops->hasChildNodes) {
353 my $propstat = $doc->createElement('D:propstat');
354 $propstat->addChild($okprops);
355 my $stat = $doc->createElement('D:status');
356 $stat->appendText('HTTP/1.1 200 OK');
357 $propstat->addChild($stat);
358 $resp->addChild($propstat);
359 }
360 if ($nfprops->hasChildNodes) {
361 my $propstat = $doc->createElement('D:propstat');
362 $propstat->addChild($nfprops);
363 my $stat = $doc->createElement('D:status');
364 $stat->appendText('HTTP/1.1 404 Not Found');
365 $propstat->addChild($stat);
366 $resp->addChild($propstat);
367 }
368 }
369 my $str = $doc->toString(1);
370 my $len = length($str);
371 $log->debug("RESPONSE: 207\n" . $doc->toString(1));
372 $stream->write("HTTP/1.1 207 Multi-Status\r\n");
373 $stream->write("Content-Type: application/xml; charset=\"utf-8\"\r\n");
374 $stream->write("Content-Length: $len\r\n");
375 if ($path =~ m!/(page|raw|file|login)$!) {
376 $stream->write("Content-Location: $path/\r\n");
377 }
378 $stream->write("\r\n");
379 $stream->write($str);
380 }
381  
382 sub to_url {
383 my $space = shift;
384 my $resource = shift;
385 my $href;
386 $href .= "/" . uri_escape_utf8($space) if $space;
387 # split doesn't produce empty fields at the end
388 my $d = substr($resource, -1) eq "/";
389 $href .= join("/", map { uri_escape_utf8($_) } split (/\//, $resource));
390 $href .= "/" if $d;
391 return $href;
392 }
393  
394 sub put {
395 my ($stream, $host, $space, $path, $id, $headers, $buffer) = @_;
396 return unless authorize($stream, $host, $space, $headers);
397 return remove($stream, $host, $space, $path, $id, $headers) if length($buffer) == 0;
398 my $mime = $headers->{"content-type"} // guess_mime_type(\$buffer);
399 return webdav_error($stream, "Content type not known") unless $mime;
400 return webdav_error($stream, "Page name is missing") unless $id;
401 return webdav_error($stream, "Page names must not control characters") if $id =~ /[[:cntrl:]]/;
402 # We don't need to close the stream because this is called via process_gemini
403 # which always closes the stream in the end.
404 if ($path eq "/file/$id") {
405 with_lock($stream, $host, $space, sub { write_file($stream, $host, $space, $id, $buffer, $mime) } );
406 } else {
407 my $text = decode_utf8 $buffer // "";
408 $text =~ s/\r\n/\n/g; # fix DOS EOL convention
409 with_lock($stream, $host, $space, sub { write_page($stream, $host, $space, $id, $text) } );
410 }
411 return 1;
412 }
413  
414 sub write_page {
415 my $stream = shift;
416 my $host = shift;
417 my $space = shift;
418 my $id = shift;
419 my $text = shift;
420 my $dir = wiki_dir($host, $space);
421 my $file = "$dir/page/$id.gmi";
422 my $revision = 0;
423 my $new = 0;
424 if (-e $file) {
425 my $old = read_text $file;
426 if ($old eq $text) {
427 $log->info("$id is unchanged");
428 $stream->write("HTTP/1.1 200 OK\r\n");
429 $stream->write("\r\n");
430 return;
431 }
432 mkdir "$dir/keep" unless -d "$dir/keep";
433 if (-d "$dir/keep/$id") {
434 foreach (read_dir("$dir/keep/$id")) {
435 $revision = $1 if m/^(\d+)\.gmi$/ and $1 > $revision;
436 }
437 $revision++;
438 } else {
439 mkdir "$dir/keep/$id";
440 $revision = 1;
441 }
442 rename $file, "$dir/keep/$id/$revision.gmi";
443 } else {
444 my $index = "$dir/index";
445 if (not open(my $fh, ">>:encoding(UTF-8)", $index)) {
446 $log->error("Cannot write index $index: $!");
447 return webdav_error($stream, "Unable to write index");
448 } else {
449 say $fh $id;
450 close($fh);
451 }
452 $new = 1;
453 }
454 my $changes = "$dir/changes.log";
455 if (not open(my $fh, ">>:encoding(UTF-8)", $changes)) {
456 $log->error("Cannot write log $changes: $!");
457 return webdav_error($stream, "Unable to write log");
458 } else {
459 my $peerhost = $stream->handle->peerhost;
460 say $fh join("\x1f", scalar(time), $id, $revision + 1, bogus_hash($peerhost));
461 close($fh);
462 }
463 mkdir "$dir/page" unless -d "$dir/page";
464 eval { write_text($file, $text) };
465 if ($@) {
466 $log->error("Unable to save $id: $@");
467 return webdav_error($stream, "Unable to save $id");
468 } else {
469 $log->info("Wrote $id");
470 if ($new) {
471 $stream->write("HTTP/1.1 201 Created\r\n");
472 } else {
473 $stream->write("HTTP/1.1 200 OK\r\n");
474 }
475 $stream->write("\r\n");
476 }
477 }
478  
479 sub write_file {
480 my $stream = shift;
481 my $host = shift;
482 my $space = shift;
483 my $id = shift;
484 my $data = shift;
485 my $type = shift;
486 my $dir = wiki_dir($host, $space);
487 my $file = "$dir/file/$id";
488 my $meta = "$dir/meta/$id";
489 my $new = 0;
490 if (-e $file) {
491 my $old = read_binary($file);
492 if ($old eq $data) {
493 $log->info("$id is unchanged");
494 $stream->write("HTTP/1.1 200 OK\r\n");
495 $stream->write("\r\n");
496 return;
497 }
498 $new = 1;
499 }
500 my $changes = "$dir/changes.log";
501 if (not open(my $fh, ">>:encoding(UTF-8)", $changes)) {
502 $log->error("Cannot write log $changes: $!");
503 return webdav_error($stream, "Unable to write log");
504 } else {
505 my $peerhost = $stream->handle->peerhost;
506 say $fh join("\x1f", scalar(time), $id, 0, bogus_hash($peerhost));
507 close($fh);
508 }
509 mkdir "$dir/file" unless -d "$dir/file";
510 eval { write_binary($file, $data) };
511 if ($@) {
512 $log->error("Unable to save $id: $@");
513 return webdav_error($stream, "Unable to save $id");
514 }
515 mkdir "$dir/meta" unless -d "$dir/meta";
516 eval { write_text($meta, "content-type: $type\n") };
517 if ($@) {
518 $log->error("Unable to save metadata for $id: $@");
519 return webdav_error($stream, "Unable to save metadata for $id");
520 }
521 $log->info("Wrote $id");
522 if ($new) {
523 $stream->write("HTTP/1.1 201 Created\r\n");
524 } else {
525 $stream->write("HTTP/1.1 200 OK\r\n");
526 }
527 $stream->write("\r\n");
528 }
529  
530 # Can't use "delete" as a name because that's a keyword...
531 sub remove {
532 my ($stream, $host, $space, $path, $id, $headers) = @_;
533 return unless authorize($stream, $host, $space, $headers);
534 return webdav_error($stream, "Page name is missing") unless $id;
535 return webdav_error($stream, "Page names must not control characters") if $id =~ /[[:cntrl:]]/;
536 # We don't need to close the stream because this is called via process_gemini
537 # which always closes the stream in the end.
538 if ($path eq "/file/$id") {
539 with_lock($stream, $host, $space, sub { delete_file($stream, $host, $space, $id) } );
540 } else {
541 with_lock($stream, $host, $space, sub { delete_page($stream, $host, $space, $id) } );
542 }
543 }
544  
545 sub delete_page {
546 my $stream = shift;
547 my $host = shift;
548 my $space = shift;
549 my $id = shift;
550 my $dir = wiki_dir($host, $space);
551 my $file = "$dir/page/$id.gmi";
552 if (-e $file) {
553 my $revision = 0;
554 mkdir "$dir/keep" unless -d "$dir/keep";
555 if (-d "$dir/keep/$id") {
556 foreach (read_dir("$dir/keep/$id")) {
557 $revision = $1 if m/^(\d+)\.gmi$/ and $1 > $revision;
558 }
559 $revision++;
560 } else {
561 mkdir "$dir/keep/$id";
562 $revision = 1;
563 }
564 # effectively deleting the file
565 rename $file, "$dir/keep/$id/$revision.gmi";
566 }
567 my $index = "$dir/index";
568 if (-f $index) {
569 # remove $id from the index
570 my @pages = grep { $_ ne $id } split /\n/, read_text $index;
571 write_text($index, join("\n", @pages, ""));
572 }
573 my $changes = "$dir/changes.log";
574 if (not open(my $fh, ">>:encoding(UTF-8)", $changes)) {
575 $log->error("Cannot write log $changes: $!");
576 return webdav_error($stream, "Unable to write log");
577 } else {
578 my $peerhost = $stream->handle->peerhost;
579 say $fh join("\x1f", scalar(time), $id, "🖹", bogus_hash($peerhost));
580 close($fh);
581 }
582 $log->info("Deleted page $id");
583 $stream->write("HTTP/1.1 204 No Content\r\n");
584 $stream->write("\r\n");
585 }
586  
587 sub delete_file {
588 my $stream = shift;
589 my $host = shift;
590 my $space = shift;
591 my $id = shift;
592 my $dir = wiki_dir($host, $space);
593 unlink("$dir/file/$id", "$dir/meta/$id");
594 my $changes = "$dir/changes.log";
595 if (not open(my $fh, ">>:encoding(UTF-8)", $changes)) {
596 $log->error("Cannot write log $changes: $!");
597 return webdav_error($stream, "Unable to write log");
598 } else {
599 my $peerhost = $stream->handle->peerhost;
600 say $fh join("\x1f", scalar(time), $id, "🖻", bogus_hash($peerhost));
601 close($fh);
602 }
603 $log->info("Deleted file $id");
604 $stream->write("HTTP/1.1 204 No Content\r\n");
605 $stream->write("\r\n");
606 }
607  
608 sub copy {
609 my ($stream, $host, $space, $path, $id, $headers) = @_;
610 return unless authorize($stream, $host, $space, $headers);
611 return webdav_error($stream, "Page name is missing") unless $id;
612 return webdav_error($stream, "Page names must not control characters") if $id =~ /[[:cntrl:]]/;
613 my $destination = $headers->{destination};
614 return webdav_error($stream, "Destination is missing") unless $destination;
615 my $dir = wiki_dir($host, $space);
616 my $source;
617 if ($path =~ m!^/raw/!) {
618 $source = "$dir/page/$id.gmi";
619 } else {
620 $source = "$dir/file/$id";
621 }
622 $log->debug("Copying $source");
623 return webdav_error($stream, "Resource is missing") unless -e $source;
624 my $data = read_binary($source);
625 # figure out the destination
626 my $hosts = host_regex();
627 my $port = port($stream);
628 my $spaces = space_regex();
629 my ($dest_host, $dest_space, $dest_path, $dest_id) =
630 $destination =~ m!^https://($hosts)(?::$port)(?:/($spaces))?(/(?:file|raw)/([^/]*))!;
631 if ($dest_id) {
632 put($stream, $host, space($stream, $host, $dest_space), $dest_path, decode_utf8(uri_unescape($dest_id)), $headers, $data);
633 } else {
634 return webdav_error($stream, "Copying to remote servers not supported");
635 }
636 }
637  
638 sub move {
639 remove(@_) if copy(@_);
640 }
641  
642 sub webdav_error {
643 my $stream = shift;
644 my $message = shift || "Bad Request";
645 $log->error($message);
646 $stream->write("HTTP/1.1 400 $message\r\n");
647 $stream->write("Content-Type: text/plain\r\n");
648 $stream->write("\r\n");
649 $stream->close_gracefully();
650 return 0;
651 }
652  
653 sub authorize {
654 my ($stream, $host, $space, $headers) = @_;
655 my @tokens = @{$server->{wiki_token}};
656 push(@tokens, @{$server->{wiki_space_token}->{$space}})
657 if $space and $server->{wiki_space_token}->{$space};
658 return 1 unless @tokens;
659 my $auth = $headers->{"authorization"};
660 if (not $auth or $auth !~ /^Basic (\S+)/) {
661 $log->info("Missing authorization header");
662 $stream->write("HTTP/1.1 401 Unauthorized\r\n");
663 $stream->write("WWW-Authenticate: Basic realm=\"Phoebe\"\r\n");
664 $stream->write("\r\n");
665 return;
666 }
667 my $bytes = b64_decode $1;
668 my ($userid, $token) = split(/:/, $bytes, 2);
669 if (not $token) {
670 $log->info("Token required (one of @tokens)");
671 $stream->write("HTTP/1.1 401 Unauthorized\r\n");
672 $stream->write("WWW-Authenticate: Basic realm=\"Phoebe\"\r\n");
673 $stream->write("\r\n");
674 return;
675 }
676 if (not grep(/^$token$/, @tokens)) {
677 $log->info("Wrong token ($token)");
678 $stream->write("HTTP/1.1 401 Unauthorized\r\n");
679 $stream->write("WWW-Authenticate: Basic realm=\"Phoebe\"\r\n");
680 $stream->write("\r\n");
681 return;
682 }
683 return 1;
684 }
685  
686 sub guess_mime_type {
687 my $SH = new IO::Scalar shift;
688 return mimetype($SH);
689 }
690  
691 1;