MrGamoo/API/Put.pm untested

filter: Statementstmt 0.0% 0 / 69 Branchbran 0.0% 0 / 12 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 11 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 99 CC 7 SCAR 28.1
CC
7
Cov
0%
_put_file
42.0
handler
6.0
BEGIN
2.0
CRAP 16.6
1 # -*- perl -*-
2  
3 # Copyright (c) 2010 AdCopy
4 # Author: Jeff Weisberg
5 # Created: 2010-Jan-19 18:21 (EST)
6 # Function:
7 #
8 # $Id: Put.pm,v 1.1 2010/11/01 18:41:52 jaw Exp $
9  
10 package AC::MrGamoo::API::Put;
11 use AC::MrGamoo::Debug 'api_put';
12 use AC::MrGamoo::Config;
13 use AC::MrGamoo::API::Simple;
14 use AC::SHA1File;
15 use AC::MrGamoo::Protocol;
16 use AC::MrGamoo::Scriblr;
17 use File::Path;
18 use POSIX;
19  
20 use strict;
21  
22 sub handler {
23 my $class = shift;
24 my $io = shift;
25 my $proto = shift;
26 my $req = shift;
27 my $content = shift;
28  
29 if( conf_value('scriblr') =~ /no|off/i ){
30 reply( 500, 'Error', $io, $proto, $req );
31 return;
32 }
33  
34 in_background( \&_put_file, $io, $proto, $req, $content );
35 }
36  
37 sub _put_file {
38 my $io = shift;
39 my $proto = shift;
40 my $req = shift;
41 my $content = shift;
42  
43 my $file = filename($req->{filename});
44 my $fd = $io->{fd};
45 fcntl($fd, F_SETFL, 0); # unset nbio
46  
47 my($dir) = $file =~ m|^(.+)/[^/]+$|;
48  
49 # mkpath
50 eval{ mkpath($dir, undef, 0755) };
51  
52 # open tmp
53 my $tmp = "$file.tmp";
54 unless( open(F, "> $tmp") ){
55 problem("open file failed: $!");
56 return nbfd_reply(500, 'error', $fd, $proto, $req);
57 }
58  
59 # read + write
60 my $size = $proto->{content_length};
61 my $sha1 = $req->{hash_sha1};
62  
63 verbose("put file '$file' size $size");
64  
65 if( $content ){
66 syswrite( F, $content );
67 $size -= length($content);
68 }
69  
70 eval {
71 my $chk = AC::MrGamoo::Protocol->sendfile(\*F, $fd, $size, 10);
72 close F;
73 die "file size mismatch\n" unless (stat($tmp))[7] == $proto->{content_length};
74 die "SHA1 check failed\n" if $sha1 && $sha1 ne $chk;
75 };
76 if(my $e = $@){
77 unlink $tmp;
78 verbose("error: $e");
79 nbfd_reply(500, 'error', $fd, $proto, $req);
80 return;
81 }
82  
83 rename $tmp, $file;
84  
85 nbfd_reply(200, 'OK', $fd, $proto, $req);
86 }
87  
88 1;