76211549ccecaa1dd782cd7639892dc68ea943d8
[pr0n] / perl / Sesse / pr0n / WebDAV.pm
1 package Sesse::pr0n::WebDAV;
2 use strict;
3 use warnings;
4
5 use Sesse::pr0n::Common qw(error dberror);
6 use Digest::SHA1;
7 use MIME::Base64;
8
9 sub handler {
10         my $r = shift;
11         my $dbh = Sesse::pr0n::Common::get_dbh();
12
13         $r->headers_out->{'DAV'} = "1,2";
14
15         # We only handle depth=0, depth=1 (cf. the RFC)
16         my $depth = $r->headers_in->{'depth'};
17         $depth = 0 if (!defined($depth));
18         if (defined($depth) && $depth ne "0" && $depth ne "1") {
19                 $r->content_type('text/plain; charset="utf-8"');
20                 $r->status(403);
21                 $r->print("Invalid depth setting");
22                 return Apache2::Const::OK;
23         }
24
25         my ($user,$takenby) = Sesse::pr0n::Common::check_access($r);
26         if (!defined($user)) {
27                 return Apache2::Const::OK;
28         }
29
30         # Just "ping, are you alive and do you speak WebDAV"
31         if ($r->method eq "OPTIONS") {
32                 $r->content_type('text/plain; charset="utf-8"');
33                 $r->status(200);
34                 $r->headers_out->{'allow'} = 'OPTIONS,PUT';
35                 $r->headers_out->{'ms-author-via'} = 'DAV';
36                 return Apache2::Const::OK;
37         }
38         
39         # Directory listings et al
40         if ($r->method eq "PROPFIND") {
41                 $r->content_type('text/xml; charset="utf-8"');
42                 $r->status(207);
43
44                 if ($r->uri =~ m#^/webdav/?$#) {
45                         $r->headers_out->{'content-location'} = "/webdav/";
46                 
47                         # Root directory
48                         $r->print(<<"EOF");
49 <?xml version="1.0" encoding="utf-8"?>
50 <multistatus xmlns="DAV:">
51   <response>
52      <href>/webdav/</href>
53      <propstat>
54         <prop>
55           <resourcetype><collection/></resourcetype>
56           <getcontenttype>text/xml</getcontenttype>
57         </prop>
58         <status>HTTP/1.1 200 OK</status>
59      </propstat>
60   </response>
61 EOF
62
63                         # Optionally list the upload/ dir
64                         if ($depth >= 1) {
65                                 $r->print(<<"EOF");
66   <response>
67      <href>/webdav/upload/</href>
68      <propstat>
69         <prop>
70           <resourcetype><collection/></resourcetype>
71           <getcontenttype>text/xml</getcontenttype>
72         </prop>
73         <status>HTTP/1.1 200 OK</status>
74      </propstat>
75   </response>
76 EOF
77                         }
78                         $r->print("</multistatus>\n");
79                  } elsif ($r->uri =~ m#^/webdav/upload/?$#) {
80                         $r->headers_out->{'content-location'} = "/webdav/upload/";
81                         
82                         # Upload root directory
83                         $r->print(<<"EOF");
84 <?xml version="1.0" encoding="utf-8"?>
85 <multistatus xmlns="DAV:">
86   <response>
87      <href>/webdav/upload/</href>
88      <propstat>
89         <prop>
90           <resourcetype><collection/></resourcetype>
91           <getcontenttype>text/xml</getcontenttype>
92         </prop>
93         <status>HTTP/1.1 200 OK</status>
94      </propstat>
95   </response>
96 EOF
97
98                         # Optionally list all events
99                         if ($depth >= 1) {
100                                 my $q = $dbh->prepare('SELECT * FROM events WHERE vhost=?') or
101                                         dberror($r, "Couldn't list events");
102                                 $q->execute($r->get_server_name) or
103                                         dberror($r, "Couldn't get events");
104                 
105                                 while (my $ref = $q->fetchrow_hashref()) {
106                                         my $id = $ref->{'id'};
107                                         my $name = $ref->{'name'};
108                                 
109                                         $name =~ s/&/\&amp;/g;  # hack :-)
110                                         $r->print(<<"EOF");
111   <response>
112      <href>/webdav/upload/$id/</href>
113      <propstat>
114         <prop>
115           <resourcetype><collection/></resourcetype>
116           <getcontenttype>text/xml</getcontenttype>
117           <displayname>$name</displayname> 
118         </prop>
119         <status>HTTP/1.1 200 OK</status>
120      </propstat>
121   </response>
122 EOF
123                                 }
124                                 $q->finish;
125                         }
126
127                         $r->print("</multistatus>\n");
128                 } elsif ($r->uri =~ m#^/webdav/upload/([a-zA-Z0-9-]+)/?$#) {
129                         my $event = $1;
130                         
131                         $r->headers_out->{'content-location'} = "/webdav/upload/$event/";
132                         
133                         # Check that we do indeed exist
134                         my $ref = $dbh->selectrow_hashref('SELECT count(*) AS numev FROM events WHERE id=?',
135                                 undef, $event);
136                         if ($ref->{'numev'} != 1) {
137                                 $r->status(404);
138                                 $r->content_type('text/plain; charset=utf-8');
139                                 $r->print("Couldn't find event in database");
140                                 return Apache2::Const::OK;
141                         }
142                         
143                         # OK, list the directory
144                         $r->print(<<"EOF");
145 <?xml version="1.0" encoding="utf-8"?>
146 <multistatus xmlns="DAV:">
147   <response>
148      <href>/webdav/upload/$event/</href>
149      <propstat>
150         <prop>
151           <resourcetype><collection/></resourcetype>
152           <getcontenttype>text/xml</getcontenttype>
153         </prop>
154         <status>HTTP/1.1 200 OK</status>
155      </propstat>
156   </response>
157 EOF
158
159                         # List all the files within too, of course :-)
160                         if ($depth >= 1) {
161                                 my $q = $dbh->prepare('SELECT * FROM images WHERE event=?') or
162                                         dberror($r, "Couldn't list images");
163                                 $q->execute($event) or
164                                         dberror($r, "Couldn't get events");
165                 
166                                 while (my $ref = $q->fetchrow_hashref()) {
167                                         my $id = $ref->{'id'};
168                                         my $filename = $ref->{'filename'};
169                                         my $fname = Sesse::pr0n::Common::get_disk_location($r, $id);
170                                         my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
171                                                 or next;
172                                         $mtime = POSIX::strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime($mtime));
173                                         my $mime_type = Sesse::pr0n::Common::get_mimetype_from_filename($filename);
174
175                                         $r->print(<<"EOF");
176   <response>
177      <href>/webdav/upload/$event/$filename</href>
178      <propstat>
179         <prop>
180           <resourcetype/>
181           <getcontenttype>$mime_type</getcontenttype>
182           <getcontentlength>$size</getcontentlength>
183           <getlastmodified>$mtime</getlastmodified>
184         </prop>
185         <status>HTTP/1.1 200 OK</status>
186      </propstat>
187   </response>
188 EOF
189                                 }
190                                 $q->finish;
191
192                                 # And the magical autorename folder
193                                 $r->print(<<"EOF");
194   <response>
195      <href>/webdav/upload/$event/autorename/</href>
196      <propstat>
197         <prop>
198           <resourcetype><collection/></resourcetype>
199           <getcontenttype>text/xml</getcontenttype>
200         </prop>
201         <status>HTTP/1.1 200 OK</status>
202      </propstat>
203   </response>
204 EOF
205                                 $r->log->info("Full list");
206                         }
207
208                         $r->print("</multistatus>\n");
209
210                         return Apache2::Const::OK;
211                 } elsif ($r->uri =~ m#^/webdav/upload/([a-zA-Z0-9-]+)/autorename/?$#) {
212                         # The autorename folder is always empty
213                         my $event = $1;
214                         
215                         $r->headers_out->{'content-location'} = "/webdav/upload/$event/autorename/";
216                         
217                         # Check that we do indeed exist
218                         my $ref = $dbh->selectrow_hashref('SELECT count(*) AS numev FROM events WHERE id=?',
219                                 undef, $event);
220                         if ($ref->{'numev'} != 1) {
221                                 $r->status(404);
222                                 $r->content_type('text/plain; charset=utf-8');
223                                 $r->print("Couldn't find event in database");
224                                 return Apache2::Const::OK;
225                         }
226                         
227                         # OK, list the (empty) directory
228                         $r->print(<<"EOF");
229 <?xml version="1.0" encoding="utf-8"?>
230 <multistatus xmlns="DAV:">
231   <response>
232      <href>/webdav/upload/$event/autorename/</href>
233      <propstat>
234         <prop>
235           <resourcetype><collection/></resourcetype>
236           <getcontenttype>text/xml</getcontenttype>
237         </prop>
238         <status>HTTP/1.1 200 OK</status>
239      </propstat>
240   </response>
241 </multistatus>
242 EOF
243         
244                         return Apache2::Const::OK;
245                 } elsif ($r->uri =~ m#^/webdav/upload/([a-zA-Z0-9-]+)/([a-zA-Z0-9._-]+)$#) {
246                         # stat a single file
247                         my ($event, $filename) = ($1, $2);
248                         my ($fname, $size, $mtime);
249                         
250                         # check if we have a pending fake file for this
251                         my $ref = $dbh->selectrow_hashref('SELECT count(*) AS numfiles FROM fake_files WHERE event=? AND filename=? AND expires_at > now()',
252                                 undef, $event, $filename);
253                         if ($ref->{'numfiles'} == 1) {
254                                 $fname = "/dev/null";
255                                 $size = 0;
256                                 $mtime = time;
257                         } else {
258                                 ($fname, $size, $mtime) = Sesse::pr0n::Common::stat_image($r, $event, $filename);
259                         }
260                         
261                         if (!defined($fname)) {
262                                 $r->status(404);
263                                 $r->content_type('text/plain; charset=utf-8');
264                                 $r->print("Couldn't find file");
265                                 return Apache2::Const::OK;
266                         }
267                         my $mime_type = Sesse::pr0n::Common::get_mimetype_from_filename($filename);
268                         
269                         $mtime = POSIX::strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime($mtime));
270                         $r->print(<<"EOF");
271 <?xml version="1.0" encoding="utf-8"?>
272 <multistatus xmlns="DAV:">
273   <response>
274     <href>/webdav/upload/$event/$filename</href>
275     <propstat>
276       <prop>
277         <resourcetype/>
278         <getcontenttype>$mime_type</getcontenttype>
279         <getcontentlength>$size</getcontentlength>
280         <getlastmodified>$mtime</getlastmodified>
281       </prop>
282       <status>HTTP/1.1 200 OK</status>
283     </propstat>
284   </response>
285 </multistatus>
286 EOF
287                         return Apache2::Const::OK;
288                 } elsif ($r->uri =~ m#^/webdav/upload/([a-zA-Z0-9-]+)/autorename/(.{1,250})$#) {
289                         # stat a single file in autorename
290                         my ($event, $filename) = ($1, $2);
291                         my ($fname, $size, $mtime);
292                         
293                         # check if we have a pending fake file for this
294                         my $ref = $dbh->selectrow_hashref('SELECT count(*) AS numfiles FROM fake_files WHERE event=? AND filename=? AND expires_at > now()',
295                                 undef, $event, $filename);
296                         if ($ref->{'numfiles'} == 1) {
297                                 $fname = "/dev/null";
298                                 $size = 0;
299                                 $mtime = time;
300                         } else {
301                                 # check if we have a "shadow file" for this
302                                 my $ref = $dbh->selectrow_hashref('SELECT id FROM shadow_files WHERE event=? AND filename=? AND expires_at > now()',
303                                         undef, $event, $filename);
304                                 if (defined($ref)) {
305                                         ($fname, $size, $mtime) = Sesse::pr0n::Common::stat_image_from_id($r, $ref->{'id'});
306                                 }
307                         }
308                         
309                         if (!defined($fname)) {
310                                 $r->status(404);
311                                 $r->content_type('text/plain; charset=utf-8');
312                                 $r->print("Couldn't find file");
313                                 return Apache2::Const::OK;
314                         }
315                         my $mime_type = Sesse::pr0n::Common::get_mimetype_from_filename($filename);
316                         
317                         $mtime = POSIX::strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime($mtime));
318                         $r->print(<<"EOF");
319 <?xml version="1.0" encoding="utf-8"?>
320 <multistatus xmlns="DAV:">
321   <response>
322     <href>/webdav/upload/$event/autorename/$filename</href>
323     <propstat>
324       <prop>
325         <resourcetype/>
326         <getcontenttype>$mime_type</getcontenttype>
327         <getcontentlength>$size</getcontentlength>
328         <getlastmodified>$mtime</getlastmodified>
329       </prop>
330       <status>HTTP/1.1 200 OK</status>
331     </propstat>
332   </response>
333 </multistatus>
334 EOF
335                 } else {
336                         $r->status(404);
337                         $r->content_type('text/plain; charset=utf-8');
338                         $r->print("Couldn't find file");
339                 }
340                 return Apache2::Const::OK;
341         }
342         
343         if ($r->method eq "HEAD" or $r->method eq "GET") {
344                 if ($r->uri !~ m#^/webdav/upload/([a-zA-Z0-9-]+)/(autorename/)?(.{1,250})$#) {
345                         $r->status(404);
346                         $r->content_type('text/xml; charset=utf-8');
347                         $r->print("<?xml version=\"1.0\"?>\n<p>Couldn't find file</p>");
348                         return Apache2::Const::OK;
349                 }
350
351                 my ($event, $autorename, $filename) = ($1, $2, $3);
352                 
353                 # Check if this file really exists
354                 my ($fname, $size, $mtime);
355
356                 # check if we have a pending fake file for this
357                 my $ref = $dbh->selectrow_hashref('SELECT count(*) AS numfiles FROM fake_files WHERE event=? AND filename=? AND expires_at > now()',
358                         undef, $event, $filename);
359                 if ($ref->{'numfiles'} == 1) {
360                         $fname = "/dev/null";
361                         $size = 0;
362                         $mtime = time;
363                 } else {
364                         # check if we have a "shadow file" for this
365                         if (defined($autorename) && $autorename eq "autorename/") {
366                                 my $ref = $dbh->selectrow_hashref('SELECT id FROM shadow_files WHERE event=? AND filename=? AND expires_at > now()',
367                                         undef, $event, $filename);
368                                 if (defined($ref)) {
369                                         ($fname, $size, $mtime) = Sesse::pr0n::Common::stat_image_from_id($r, $ref->{'id'});
370                                 }
371                         } elsif (!defined($fname)) {
372                                 ($fname, $size, $mtime) = Sesse::pr0n::Common::stat_image($r, $event, $filename);
373                         }
374                 }
375                 
376                 if (!defined($fname)) {
377                         $r->status(404);
378                         $r->content_type('text/plain; charset=utf-8');
379                         $r->print("Couldn't find file");
380                         return Apache2::Const::OK;
381                 }
382                 
383                 $r->status(200);
384                 $r->set_content_length($size);
385                 $r->set_last_modified($mtime);
386         
387                 if ($r->method eq "GET") {
388                         $r->sendfile($fname);
389                 }
390                 return Apache2::Const::OK;
391         }
392         
393         if ($r->method eq "PUT") {
394                 if ($r->uri !~ m#^/webdav/upload/([a-zA-Z0-9-]+)/(autorename/)?(.{1,250})$#) {
395                         $r->status(403);
396                         $r->content_type('text/plain; charset=utf-8');
397                         $r->print("No access");
398                         return Apache2::Const::OK;
399                 }
400                 
401                 my ($event, $autorename, $filename) = ($1, $2, $3);
402                 my $size = $r->headers_in->{'content-length'};
403                 my $orig_filename = $filename;
404
405                 # Remove evil characters
406                 if ($filename =~ /[^a-zA-Z0-9._-]/) {
407                         if (defined($autorename) && $autorename eq "autorename/") {
408                                 $filename =~ tr/a-zA-Z0-9.-/_/c;
409                         } else {
410                                 $r->status(403);
411                                 $r->content_type('text/plain; charset=utf-8');
412                                 $r->print("Illegal characters in filename");
413                                 return Apache2::Const::OK;
414                         }
415                 }
416                 
417                 #
418                 # gnome-vfs and mac os x love to make zero-byte files,
419                 # make them happy
420                 # 
421                 if ($r->headers_in->{'content-length'} == 0) {
422                         $dbh->do('DELETE FROM fake_files WHERE expires_at <= now() OR (event=? AND filename=?);',
423                                 undef, $event, $filename)
424                                 or dberror($r, "Couldn't prune fake_files");
425                         $dbh->do('INSERT INTO fake_files (event,filename,expires_at) VALUES (?,?,now() + interval \'30 seconds\');',
426                                 undef, $event, $filename)
427                                 or dberror($r, "Couldn't add file");
428                         $r->content_type('text/plain; charset="utf-8"');
429                         $r->status(201);
430                         $r->print("OK");
431                         $r->log->info("Fake upload of $event/$filename");
432                         return Apache2::Const::OK;
433                 }
434
435                 # Get the new ID
436                 my $ref = $dbh->selectrow_hashref("SELECT NEXTVAL('imageid_seq') AS id;");
437                 my $newid = $ref->{'id'};
438                 if (!defined($newid)) {
439                         dberror($r, "Couldn't get new ID");
440                 }
441                 
442                 # Autorename if we need to
443                 if (defined($autorename) && $autorename eq "autorename/") {
444                         my $ref = $dbh->selectrow_hashref("SELECT COUNT(*) AS numfiles FROM images WHERE event=? AND filename=?",
445                                 undef, $event, $filename)
446                                 or dberror($r, "Couldn't check for existing files");
447                         if ($ref->{'numfiles'} > 0) {
448                                 $r->log->info("Renaming $filename to $newid.jpeg");
449                                 $filename = "$newid.jpeg";
450                         }
451                 }
452                 
453                 {
454                         # Enable transactions and error raising temporarily
455                         local $dbh->{AutoCommit} = 0;
456                         
457                         local $dbh->{RaiseError} = 1;
458
459                         # Try to insert this new file
460                         eval {
461                                 $dbh->do('DELETE FROM fake_files WHERE event=? AND filename=?;',
462                                         undef, $event, $filename);
463                                         
464                                 $dbh->do('INSERT INTO images (id,event,uploadedby,takenby,filename) VALUES (?,?,?,?,?);',
465                                         undef, $newid, $event, $user, $takenby, $filename);
466
467                                 # Now save the file to disk
468                                 my $fname = Sesse::pr0n::Common::get_disk_location($r, $newid);
469                                 open NEWFILE, ">$fname"
470                                         or die "$fname: $!";
471
472                                 my $buf;
473                                 my $content_length = $r->headers_in->{'content-length'};
474                                 if ($r->read($buf, $content_length)) {
475                                         print NEWFILE $buf or die "write($fname): $!";
476                                 }
477
478                                 close NEWFILE or die "close($fname): $!";
479                                 
480                                 # Orient stuff correctly
481                                 system("/usr/bin/exifautotran", $fname) == 0
482                                         or die "/usr/bin/exifautotran: $!";
483
484                                 # Make cache while we're at it.
485                                 # Don't do it for the resource forks Mac OS X loves to upload :-(
486                                 if ($filename !~ /^\._/) {
487                                         Sesse::pr0n::Common::ensure_cached($r, $filename, $newid, -1, -1, 1, 80, 64, 320, 256, -1, -1);
488                                 }
489                                 
490                                 # OK, we got this far, commit
491                                 $dbh->commit;
492
493                                 $r->log->notice("Successfully wrote $event/$filename to $fname");
494                         };
495                         if ($@) {
496                                 # Some error occurred, rollback and bomb out
497                                 $dbh->rollback;
498                                 dberror($r, "Transaction aborted because $@");
499                         }
500                 }
501
502                 # Insert a `shadow file' we can stat the next 30 secs
503                 if (defined($autorename) && $autorename eq "autorename/") {
504                         $dbh->do('DELETE FROM shadow_files WHERE expires_at <= now() OR (event=? AND filename=?);',
505                                 undef, $event, $filename)
506                                 or dberror($r, "Couldn't prune shadow_files");
507                         $dbh->do('INSERT INTO shadow_files (event,filename,id,expires_at) VALUES (?,?,?,now() + interval \'30 seconds\');',
508                                 undef, $event, $orig_filename, $newid)
509                                 or dberror($r, "Couldn't add shadow file");
510                         $r->log->info("Added shadow entry for $event/$filename");
511                 }
512
513                 $r->content_type('text/plain; charset="utf-8"');
514                 $r->status(201);
515                 $r->print("OK");
516
517                 return Apache2::Const::OK;
518         }
519
520         # Yes, we fake locks. :-)
521         if ($r->method eq "LOCK") {
522                 if ($r->uri !~ m#^/webdav/upload/([a-zA-Z0-9-]+)/(autorename/)?([a-zA-Z0-9._-]+)$#) {
523                         $r->status(403);
524                         $r->content_type('text/plain; charset=utf-8');
525                         $r->print("No access");
526                         return Apache2::Const::OK;
527                 }
528
529                 my ($event, $autorename, $filename) = ($1, $2, $3);
530                 my $sha1 = Digest::SHA1::sha1_base64("/$event/$autorename/$filename");
531
532                 $r->status(200);
533                 $r->content_type('text/xml; charset=utf-8');
534
535                 $r->print(<<"EOF");
536 <?xml version="1.0" encoding="utf-8"?>
537 <prop xmlns="DAV:">
538   <lockdiscovery>
539     <activelock>
540       <locktype><write/></locktype>
541       <lockscope><exclusive/></lockscope>
542       <depth>0</depth>
543       <owner>
544         <href>/webdav/upload/$event/$autorename$filename</href>
545       </owner>
546       <timeout>Second-3600</timeout>
547       <locktoken>
548         <href>opaquelocktoken:$sha1</href>
549       </locktoken>
550     </activelock>
551   </lockdiscovery>
552 </prop>
553 EOF
554                 return Apache2::Const::OK;
555         }
556         
557         if ($r->method eq "UNLOCK") {
558                 $r->content_type('text/plain; charset="utf-8"');
559                 $r->status(200);
560                 $r->print("OK");
561
562                 return Apache2::Const::OK;
563         }
564
565         if ($r->method eq "DELETE") {
566                 if ($r->uri !~ m#^/webdav/upload/([a-zA-Z0-9-]+)/(autorename/)?(\._[a-zA-Z0-9._-]+)$#) {
567                         $r->status(403);
568                         $r->content_type('text/plain; charset=utf-8');
569                         $r->print("No access");
570                         return Apache2::Const::OK;
571                 }
572                 
573                 my ($event, $autorename, $filename) = ($1, $2, $3);
574                 $dbh->do('DELETE FROM images WHERE event=? AND filename=?;',
575                         undef, $event, $filename)
576                         or dberror($r, "Couldn't remove file");
577                 $r->status(200);
578                 $r->print("OK");
579
580                 $r->log->info("deleted $event/$filename");
581                 
582                 return Apache2::Const::OK;
583         }
584         
585         if ($r->method eq "MOVE" or
586             $r->method eq "MKCOL" or
587             $r->method eq "RMCOL" or
588             $r->method eq "RENAME" or
589             $r->method eq "COPY") {
590                 $r->content_type('text/plain; charset="utf-8"');
591                 $r->status(403);
592                 $r->print("Sorry, you do not have access to that feature.");
593                 return Apache2::Const::OK;
594         }
595         
596         $r->content_type('text/plain; charset=utf-8');
597         $r->log->error("unknown method " . $r->method);
598         $r->status(500);
599         $r->print("Unknown method");
600         
601         return Apache2::Const::OK;
602 }
603
604 1;
605
606