Phoebe/Capsules.pm untested

filter: Statementstmt 0.0% 0 / 356 Branchbran 0.0% 0 / 170 Conditioncond 0.0% 0 / 38 MC/DCmcdc 0.0% 0 / 20 Subroutinesub 0.0% 0 / 29 Podpod 0.0% 0 / 21 totaltotal 0.0% 0 / 634 CC 85 SCAR 41.6
CC
85
Cov
0%
capsules
182.0
serve_capsule_menu
110.0
mime_type
90.0
CRAP 63.8
1 # -*- mode: perl -*-
2 # Copyright (C) 2017–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::Capsules - provide every visitor with a writeable capsule
22  
23 =head1 DESCRIPTION
24  
25 By default, Phoebe creates a wiki editable by all. With this extension, the
26 C</capsule> space turns into a special site: if you have a client certificate,
27 you automatically get an editable capsule with an assigned fantasy name.
28  
29 Simply add it to your F<config> file. If you are virtual hosting, name the host
30 or hosts for your capsules.
31  
32 package App::Phoebe::Capsules;
33 use Modern::Perl;
34 our @capsule_hosts = qw(transjovian.org);
35 use App::Phoebe::Capsules;
36  
37 Every client certificate gets assigned a capsule name.
38  
39 You can provide a link with some documentation, if you want:
40  
41 our $capsule_help = '//transjovian.org/phoebe/page/Capsules';
42  
43 =head1 NO MIME TYPES
44  
45 When uploading to a capsule, the MIME type is ignored. Instead, it is determined
46 from the filename extension.
47  
48 =head1 TROUBLESHOOTING
49  
50 🔥 In the wiki directory, you can have a file called F<fingerprint_equivalents>.
51 Its main use is to allow people to add more fingerprints for their site, such as
52 from other devices or friends. The file format is line oriented, each line
53 containing two fingerprints, C<FROM> and C<TO>.
54  
55 🔥 The capsule name I<login> is reserved.
56  
57 🔥 The file names I<archive>, I<backup>, and I<upload> are reserved.
58  
59 =head1 NO WIKI, ONLY CAPSULES
60  
61 Here's how to disable all wiki functions of Phoebe and just use capsules. The
62 C<nothing_else> function comes right after C<capsules> as an extension and
63 always returns 1, so Phoebe considers this request handled. Therefore, the
64 regular request handlers won't get used. Make sure that any extensions you do
65 want to have are prepended to C<@extensions> after setting it (using
66 C<unshift>).
67  
68 # tested by t/example-capsules-only.t
69 package App::Phoebe::Capsules;
70 use Modern::Perl;
71 use App::Phoebe qw($log @request_handlers @extensions);
72 use App::Phoebe::Capsules;
73 our $capsule_help = '//transjovian.org/phoebe/page/Capsules';
74 our $capsule_space;
75 @extensions = (\&capsules, \&nothing_else);
76 sub nothing_else {
77 my ($stream, $url) = @_;
78 $log->info("No handler for $url: only capsules!");
79 result($stream, "30", "/$capsule_space");
80 1;
81 }
82 $log->info('Only capsules!');
83 1;
84  
85 =cut
86  
87 package App::Phoebe::Capsules;
88 use App::Phoebe qw($server $log @extensions @request_handlers host_regex port success result print_link wiki_dir
89 valid_id valid_mime_type valid_size to_url);
90 use File::Slurper qw(read_dir read_binary write_binary);
91 use Net::IDN::Encode qw(domain_to_ascii);
92 use Encode qw(encode_utf8 decode_utf8);
93 use File::MimeInfo qw(globs);
94 use List::Util qw(sum first);
95 use Modern::Perl;
96 use URI::Escape;
97  
98 push(@extensions, \&capsules);
99  
100 our $capsule_space = "capsule";
101 our @capsule_hosts;
102 our $capsule_help;
103 our @capsule_tokens;
104 our %capsule_equivalent;
105  
106 # load fingerprint equivalents on the next tick
107 Mojo::IOLoop->next_tick(sub {
108 my $dir = $server->{wiki_dir};
109 if (-f "$dir/fingerprint_equivalents") {
110 my $bytes = read_binary("$dir/fingerprint_equivalents");
111 %capsule_equivalent = split(' ', $bytes);
112 } } );
113  
114 sub capsules {
115 my $stream = shift;
116 my $url = shift;
117 my $hosts = capsule_regex();
118 my $port = port($stream);
119 my ($host, $capsule, $id, $token);
120 if ($url =~ m!^gemini://($hosts)(?::$port)?/$capsule_space/([^/]+)/upload$!) {
121 return result($stream, "10", "Filename");
122 } elsif (($host, $capsule, $id) = $url =~ m!^gemini://($hosts)(?::$port)?/$capsule_space/([^/]+)/upload\?([^/]+)$!) {
123 $capsule = decode_utf8(uri_unescape($capsule));
124 return result($stream, "30", "gemini://$host:$port/$capsule_space/$capsule/$id");
125 } elsif (($host) = $url =~ m!^gemini://($hosts)(?::$port)?/$capsule_space/login$!) {
126 return serve_capsule_login($stream, $host);
127 } elsif (($host, $capsule) = $url =~ m!^gemini://($hosts)(?::$port)?/$capsule_space/([^/]+)/archive$!) {
128 return serve_capsule_archive($stream, $host, decode_utf8(uri_unescape($capsule)));
129 } elsif (($host, $capsule, $id) = $url =~ m!^gemini://($hosts)(?::$port)?/$capsule_space/([^/]+)/backup(?:/([^/]+))?$!) {
130 return serve_capsule_backup($stream, $host, map { decode_utf8(uri_unescape($_)) } $capsule, $id||"");
131 } elsif (($host, $capsule, $id) = $url =~ m!^gemini://($hosts)(?::$port)?/$capsule_space/([^/]+)/delete(?:/([^/]+))?$!) {
132 return serve_capsule_delete($stream, $host, map { decode_utf8(uri_unescape($_)) } $capsule, $id||"");
133 } elsif ($url =~ m!^gemini://($hosts)(?::$port)?/$capsule_space/([^/]+)/access$!) {
134 return result($stream, "10", "Password");
135 } elsif (($host, $capsule, $token) = $url =~ m!^gemini://($hosts)(?::$port)?/$capsule_space/([^/]+)/access\?(.+)$!) {
136 return serve_capsule_access($stream, $host, decode_utf8(uri_unescape($capsule)), decode_utf8(uri_unescape($token)));
137 } elsif (($host, $capsule) = $url =~ m!^gemini://($hosts)(?::$port)?/$capsule_space/([^/]+)/share$!) {
138 return serve_capsule_sharing($stream, $host, decode_utf8(uri_unescape($capsule)));
139 } elsif (($host, $capsule, $id) = $url =~ m!^gemini://($hosts)(?::$port)?/$capsule_space/([^/]+)/([^/]+)$!) {
140 return serve_capsule_page($stream, $host, map { decode_utf8(uri_unescape($_)) } $capsule, $id);
141 } elsif (($host, $capsule) = $url =~ m!^gemini://($hosts)(?::$port)?/$capsule_space/([^/]+)/?$!) {
142 return serve_capsule_menu($stream, $host, decode_utf8(uri_unescape($capsule)));
143 } elsif (($host) = $url =~ m!^gemini://($hosts)(?::$port)?/$capsule_space/?$!) {
144 return serve_main_menu($stream, $host);
145 }
146 return;
147 }
148  
149 sub serve_capsule_login {
150 my ($stream, $host) = @_;
151 my $name = capsule_name($stream);
152 if ($name) {
153 $log->info("Redirect to capsule");
154 result($stream, "30", to_url($stream, $host, $capsule_space, ""));
155 } else {
156 $log->info("Requested client certificate for capsule");
157 result($stream, "60", "You need a client certificate to access your capsule");
158 }
159 return 1;
160 }
161  
162 sub serve_capsule_archive {
163 my ($stream, $host, $capsule) = @_;
164 my $name = capsule_name($stream);
165 return 1 unless is_my_capsule($stream, $name, $capsule, 'archive');
166 # use /bin/tar instead of Archive::Tar to save memory
167 my $dir = wiki_dir($host, $capsule_space) . "/" . encode_utf8($capsule);
168 my $file = "$dir/backup/data.tar.gz";
169 if (-e $file and time() - modified($file) <= 300) { # data is valid for 5 minutes
170 $log->info("Serving cached data archive for $capsule");
171 success($stream, "application/tar");
172 $stream->write(read_binary($file));
173 } else {
174 write_binary($file, ""); # truncate in order to avoid "file changed as we read it" warning
175 my @command = ('/bin/tar', '--create', '--gzip',
176 '--file', $file,
177 '--exclude', "backup",
178 '--directory', "$dir/..",
179 encode_utf8($capsule));
180 $log->debug("@command");
181 if (system(@command) == 0) {
182 $log->info("Serving new data archive for $capsule");
183 success($stream, "application/tar");
184 $stream->write(read_binary($file));
185 } else {
186 $log->error("Creation of data archive for $capsule failed");
187 result($stream, "59", "Archive creation failed");
188 }
189 }
190 return 1;
191 }
192  
193 sub serve_capsule_backup {
194 my ($stream, $host, $capsule, $id) = @_;
195 my $name = capsule_name($stream);
196 return 1 unless is_my_capsule($stream, $name, $capsule, 'view the backup of');
197 my $dir = capsule_dir($host, $capsule) . "/backup";
198 if ($id) {
199 $log->info("Serving $capsule backup $id");
200 # this works for text files, too!
201 success($stream, mime_type($id));
202 my $file = $dir . "/" . encode_utf8($id);
203 $stream->write(read_binary($file));
204 } else {
205 $log->info("Backup for $capsule");
206 success($stream);
207 $stream->write("# " . ucfirst($capsule) . " backup\n");
208 $stream->write("When editing a page, a backup is saved here as long as at least 10 minutes have passed.\n");
209 my @files;
210 @files = read_dir($dir) if -d $dir;
211 if (not @files) {
212 $stream->write("There are no backup files, yet.\n") unless @files;
213 } else {
214 $stream->write("Files:\n");
215 for my $file (sort @files) {
216 print_link($stream, $host, $capsule_space, $file, "$capsule/backup/$file");
217 };
218 }
219 }
220 return 1;
221 }
222  
223 sub serve_capsule_delete {
224 my ($stream, $host, $capsule, $id) = @_;
225 my $name = capsule_name($stream);
226 return 1 unless is_my_capsule($stream, $name, $capsule, 'delete a file in');
227 my $dir = capsule_dir($host, $capsule);
228 if ($id) {
229 $log->info("Delete $id from $capsule");
230 my $file = $dir . "/" . encode_utf8($id);
231 my $backup_dir = "$dir/backup";
232 my $backup_file = $backup_dir . "/" . encode_utf8($id);
233 mkdir($backup_dir) unless -d $backup_dir;
234 rename $file, $backup_file if -f $file;
235 result($stream, "30", to_url($stream, $host, $capsule_space, $capsule));
236 } else {
237 $log->info("Delete for $capsule");
238 success($stream);
239 $stream->write("# Delete a file in " . ucfirst($capsule) . "\n");
240 $stream->write("Deleting a file moves it to the backup.\n");
241 my @files;
242 @files = grep { $_ ne "backup" } read_dir($dir) if -d $dir;
243 if (not @files) {
244 $stream->write("There are no files to delete.\n") unless @files;
245 } else {
246 $stream->write("Files:\n");
247 for my $file (sort @files) {
248 print_link($stream, $host, $capsule_space, $file, "$capsule/delete/$file");
249 };
250 }
251 }
252 return 1;
253 }
254  
255 sub serve_capsule_access {
256 my ($stream, $host, $capsule, $token) = @_;
257 my $fingerprint = $stream->handle->get_fingerprint();
258 my $target = first { $_->[1] eq $token } @capsule_tokens;
259 if (not $fingerprint) {
260 $log->info("Attempt to access a capsule without client certificate");
261 result($stream, "60", "You need a client certificate to access this capsule");
262 } elsif ($target) {
263 if ($fingerprint ne $target->[2]) {
264 $log->info("Access to capsule granted");
265 # if the user is testing it, then the two fingerprints are the same and no
266 # equivalency needs to be saved
267 $capsule_equivalent{$fingerprint} = $target->[2];
268 my $dir = $server->{wiki_dir};
269 write_binary("$dir/fingerprint_equivalents",
270 join("\n", map { $_ . " " . $capsule_equivalent{$_} }
271 keys %capsule_equivalent));
272 } else {
273 $log->info("Access to capsule unnecessary for the owner");
274 }
275 result($stream, "30", to_url($stream, $host, $capsule_space, $capsule));
276 } else {
277 $log->info("Access to capsule denied");
278 success($stream);
279 $stream->write("This password is invalid\n");
280 }
281 return 1;
282 }
283  
284 sub serve_capsule_sharing {
285 my ($stream, $host, $capsule) = @_;
286 my $name = capsule_name($stream);
287 return 1 unless is_my_capsule($stream, $name, $capsule, 'share');
288 $log->info("Share capsule");
289 my $token = capsule_name(sprintf "-------%04X%04X%04X", rand(0xffff), rand(0xffff), rand(0xffff));
290 push(@capsule_tokens, [time, $token, $stream->handle->get_fingerprint()]);
291 # forget old access tokens in ten minutes
292 Mojo::IOLoop->timer(601 => \&capsule_token_cleanup);
293 success($stream);
294 $stream->write("# Share access to " . ucfirst($capsule) . "\n");
295 $stream->write("This password is valid for ten minutes: $token\n");
296 return 1;
297 }
298  
299 sub is_my_capsule {
300 my ($stream, $name, $capsule, $verb) = @_;
301 if (not $name) {
302 $log->info("Attempt to $verb a capsule without client certificate");
303 result($stream, "60", "You need a client certificate to $verb this capsule");
304 return 0;
305 } elsif ($capsule and $name ne $capsule) {
306 $log->info("Attempt to $verb the wrong capsule");
307 result($stream, "60", "You need a different client certificate to $verb this capsule");
308 return 0;
309 }
310 return 1;
311 }
312  
313 sub serve_capsule_page {
314 my ($stream, $host, $capsule, $id) = @_;
315 my $dir = capsule_dir($host, $capsule);
316 my $file = $dir . "/" . encode_utf8($id);
317 if (-f $file) {
318 $log->info("Serving $file");
319 # this works for text files, too!
320 success($stream, mime_type($id));
321 $stream->write(read_binary($file));
322 } else {
323 $log->info("Serving invitation to upload $file");
324 success($stream);
325 $stream->write("This file does not exist. Upload it using Titan!\n");
326 $stream->write("=> gemini://transjovian.org/titan What is Titan?\n");
327 }
328 return 1;
329 }
330  
331 sub serve_capsule_menu {
332 my ($stream, $host, $capsule) = @_;
333 my $name = capsule_name($stream);
334 my $dir = capsule_dir($host, $capsule);
335 my @files;
336 @files = read_dir($dir) if -d $dir;
337 my $has_backup = first { $_ eq "backup" } @files;
338 @files = grep { $_ ne "backup" } @files if $has_backup;
339 success($stream);
340 $log->info("Serving $capsule");
341 $stream->write("# " . ucfirst($capsule) . "\n");
342 if ($name) {
343 if ($name eq $capsule) {
344 print_link($stream, $host, $capsule_space, "Specify file for upload", "$capsule/upload");
345 print_link($stream, $host, $capsule_space, "Delete file", "$capsule/delete") if @files;
346 print_link($stream, $host, $capsule_space, "Share access with other people or other devices", "$capsule/share");
347 print_link($stream, $host, $capsule_space, "Access backup", "$capsule/backup") if $has_backup;
348 print_link($stream, $host, $capsule_space, "Download archive", "$capsule/archive") if @files;
349 } elsif (@capsule_tokens) {
350 print_link($stream, $host, $capsule_space, "Access this capsule", "$capsule/access");
351 }
352 }
353 if (@files) {
354 $stream->write("Files:\n");
355 for my $file (sort @files) {
356 print_link($stream, $host, $capsule_space, $file, "$capsule/$file");
357 }
358 }
359 return 1;
360 }
361  
362 sub serve_main_menu {
363 my ($stream, $host) = @_;
364 success($stream);
365 $log->info("Serving capsules");
366 $stream->write("# Capsules\n");
367 my $capsule = capsule_name($stream);
368 if ($capsule) {
369 $stream->write("This is your capsule:\n");
370 print_link($stream, $host, $capsule_space, $capsule, $capsule); # must provide $id to avoid page/ prefix
371 } else {
372 $stream->write("Login if you are interested in a capsule:\n");
373 print_link($stream, $host, $capsule_space, "login", "login"); # must provide $id to avoid page/ prefix
374 }
375 $stream->write("=> $capsule_help Help\n") if $capsule_help;
376 my @capsules = read_dir(wiki_dir($host, $capsule_space));
377 $stream->write("Capsules:\n") if @capsules;
378 for my $dir (sort @capsules) {
379 print_link($stream, $host, $capsule_space, $dir, $dir); # must provide $id to avoid page/ prefix
380 };
381 return 1;
382 }
383  
384 # capsule is already decoded and gets encoded again
385 sub capsule_dir {
386 my $host = shift;
387 my $capsule = shift;
388 my $dir = $server->{wiki_dir};
389 if (keys %{$server->{host}} > 1) {
390 $dir .= "/$host";
391 mkdir($dir) unless -d $dir;
392 }
393 $dir .= "/$capsule_space";
394 mkdir($dir) unless -d $dir;
395 $dir .= "/" . encode_utf8($capsule);
396 return $dir;
397 }
398  
399 sub capsule_regex {
400 return join("|", map { quotemeta domain_to_ascii $_ } @capsule_hosts) || host_regex();
401 }
402  
403 # For 'sha256$5a4a0248b753' the name is tibedied (the first name for Elite names)
404 sub capsule_name {
405 my $stream = shift;
406 # $stream can be a fingerprint string
407 my $fingerprint = ref $stream ? $stream->handle->get_fingerprint() : $stream;
408 return unless $fingerprint;
409 $fingerprint = $capsule_equivalent{$fingerprint} if $capsule_equivalent{$fingerprint};
410 my @stack = map { hex } substr($fingerprint, 7, 12) =~ /(....)/g;
411 my $digraphs = "..lexegezacebisousesarmaindirea.eratenberalavetiedorquanteisrion";
412 my $longname = $stack[0] & 0x40;
413 my $name;
414 # say "@stack";
415 for my $n (1 .. 4) {
416 my $d = (($stack[2] >> 8) & 0x1f) << 1;
417 push(@stack, sum(@stack) % 0x10000);
418 shift(@stack);
419 $name .= substr($digraphs, $d, 2)
420 if $n <= 3 or $longname;
421 }
422 $name =~ s/\.//g;
423 return $name;
424 }
425  
426 sub mime_type {
427 $_ = shift;
428 my $mime = globs($_);
429 return $mime if $mime;
430 # fallback
431 return 'text/gemini' if /\.gmi$/i;
432 return 'text/plain' if /\.te?xt$/i;
433 return 'text/markdown' if /\.md$/i;
434 return 'text/html' if /\.html?$/i;
435 return 'image/png' if /\.png$/i;
436 return 'image/jpeg' if /\.jpe?g$/i;
437 return 'image/gif' if /\.gif$/i;
438 return 'application/octet-stream';
439 }
440  
441 sub capsule_token_cleanup {
442 # only keep tokens created in the last 10 minutes
443 my $ts = time - 600;
444 @capsule_tokens = grep { $_->[0] > $ts } @capsule_tokens;
445 }
446  
447 unshift(@request_handlers, '^titan://(' . capsule_regex() . ')(?::\d+)?/' . $capsule_space . '/' => \&handle_titan);
448  
449 # We need our own Titan handler because we want a different copy of is_upload;
450 # and once we're here we can run our extension directly.
451 sub handle_titan {
452 my $stream = shift;
453 my $data = shift;
454 # extra processing of the request if we didn't do that, yet
455 $data->{upload} ||= is_upload($stream, $data->{request}) or return;
456 my $size = $data->{upload}->{params}->{size};
457 my $actual = length($data->{buffer});
458 if ($actual == $size) {
459 save_file($stream, $data->{request}, $data->{upload}, $data->{buffer}, $size);
460 $stream->close_gracefully();
461 return;
462 } elsif ($actual > $size) {
463 $log->debug("Received more than the promised $size bytes");
464 result($stream, "59", "Received more than the promised $size bytes");
465 $stream->close_gracefully();
466 return;
467 }
468 $log->debug("Waiting for " . ($size - $actual) . " more bytes");
469 }
470  
471 # We need our own is_upload because the regular expression is different.
472 sub is_upload {
473 my $stream = shift;
474 my $request = shift;
475 $log->info("Looking at capsule $request");
476 my $hosts = capsule_regex();
477 my $port = port($stream);
478 if ($request =~ m!^titan://($hosts)(?::$port)?/$capsule_space/([^/?#;]+)/([^/?#;]+);([^?#]+)$!) {
479 my $host = $1;
480 my ($capsule, $id, %params) = map {decode_utf8(uri_unescape($_))} $2, $3, split(/[;=&]/, $4);
481 if (valid_params($stream, $host, $capsule_space, $id, \%params)) {
482 return {
483 host => $host,
484 space => $capsule_space,
485 capsule => $capsule,
486 id => $id,
487 params => \%params,
488 }
489 }
490 # valid_params printed a response and closed the stream
491 return;
492 }
493 $log->debug("Capsule upload with malformed titan URL");
494 if ($request =~ m!^titan://($hosts)(?::$port)?/$capsule_space/([^/?#;]+)/([^/?#;]+);([^?#]*)[?#]!) {
495 result($stream, "59", "The titan URL must not have a query or a fragment at the end");
496 } elsif ($request =~ m!^titan://($hosts)(?::$port)?/$capsule_space/([^/?#;]+)/([^/?#;]+)/!) {
497 result($stream, "59", "These capsules do not allow uploads for subdirectories");
498 } elsif ($request =~ m!^titan://($hosts)(?::$port)?/$capsule_space/([^/?#;]+)/([^/?#;]+)$!) {
499 result($stream, "59", "The titan URL is missing the parameters after a semikolon $1 $2 $3 $4");
500 } elsif ($request =~ m!^titan://($hosts)(?::$port)?/$capsule_space/([^/?#;]+)/?(;.*)$!) {
501 result($stream, "59", "The titan URL is missing the file name");
502 } elsif ($request =~ m!^titan://($hosts)(?::$port)?/$capsule_space/?$!) {
503 result($stream, "59", "The titan URL is missing the capsule name and the file name");
504 } else {
505 result($stream, "59", "The titan URL is malformed");
506 }
507 $stream->close_gracefully();
508 return;
509 }
510  
511 # We need our own valid_params because we don't check the token but we do check
512 # the extension
513 sub valid_params {
514 my $stream = shift;
515 my $host = shift;
516 my $space = shift;
517 my $id = shift;
518 my $params = shift;
519 return unless valid_id($stream, $host, $space, $id, $params);
520 # return unless valid_token($stream, $host, $space, $id, $params);
521 $params->{mime} = mime_type($id);
522 return unless valid_mime_type($stream, $host, $space, $id, $params);
523 return unless valid_size($stream, $host, $space, $id, $params);
524 return 1;
525 }
526  
527 sub save_file {
528 my ($stream, $url, $upload, $buffer, $size) = @_;
529 my $name = capsule_name($stream);
530 my $capsule = $upload->{capsule} || "";
531 if (not $name) {
532 $log->debug("Missing certificate for capsule upload");
533 return result($stream, "60", "Uploading files requires a client certificate");
534 } elsif ($name ne $capsule) {
535 $log->debug("Wrong certificate for capsule upload: $name vs $capsule");
536 return result($stream, "61", "This is not your space: your certificate authorizes you for $name");
537 }
538 return result($stream, "50", "Titan upload failed")
539 unless defined $buffer and defined $size and $upload->{id}
540 and $upload->{space} and $upload->{space} eq "capsule";
541 my $host = $upload->{host};
542 my $dir = capsule_dir($host, $capsule);
543 my $id = $upload->{id};
544 my $file = $dir . "/" . encode_utf8($id);
545 if ($size == 0) {
546 return result($stream, "51", "This capsule does not exist") unless -d $dir;
547 return result($stream, "51", "This file does not exist") unless -f $file;
548 return result($stream, "40", "Cannot delete this file") unless unlink $file;
549 $log->info("Deleted $file");
550 } else {
551 mkdir($dir) unless -d $dir;
552 backup($dir, $id);
553 write_binary($file, $buffer);
554 $log->info("Wrote $file");
555 return result($stream, "30", to_url($stream, $host, $capsule_space, $capsule));
556 }
557 }
558  
559 sub backup {
560 my ($dir, $id) = @_;
561 my $file = $dir . "/" . encode_utf8($id);
562 my $backup_dir = "$dir/backup";
563 my $backup_file = $backup_dir . "/" . encode_utf8($id);
564 return unless -f $file and (time - (stat($file))[9]) > 600;
565 # make a backup if the last edit was more than 10 minutes ago
566 mkdir($backup_dir) unless -d $backup_dir;
567 write_binary($backup_file, read_binary($file));
568 }
569  
570 1;