]> git.donarmstrong.com Git - debbugs.git/blob - Debbugs/Libravatar.pm
Libravatar: Lazy-load LWP::UserAgent
[debbugs.git] / Debbugs / Libravatar.pm
1 # This module is part of debbugs, and is released
2 # under the terms of the GPL version 2, or any later version. See the
3 # file README and COPYING for more information.
4 # Copyright 2013 by Don Armstrong <don@donarmstrong.com>.
5
6 package Debbugs::Libravatar;
7
8 =head1 NAME
9
10 Debbugs::Libravatar -- Libravatar service handler (mod_perl)
11
12 =head1 SYNOPSIS
13
14 <Location /libravatar>
15    SetHandler perl-script
16    PerlResponseHandler Debbugs::Libravatar
17 </Location>
18
19 =head1 DESCRIPTION
20
21 Debbugs::Libravatar is a libravatar service handler which will serve
22 libravatar requests. It also contains utility routines which are used
23 by the libravatar.cgi script for those who do not have mod_perl.
24
25 =head1 BUGS
26
27 None known.
28
29 =cut
30
31 use warnings;
32 use strict;
33 use vars qw($VERSION $DEBUG %EXPORT_TAGS @EXPORT_OK @EXPORT);
34 use Exporter qw(import);
35
36 use Debbugs::Config qw(:config);
37 use Debbugs::Common qw(:lock);
38 use Libravatar::URL;
39 use CGI::Simple;
40 use Debbugs::CGI qw(cgi_parameters);
41 use Digest::MD5 qw(md5_hex);
42 use File::Temp qw(tempfile);
43 use File::LibMagic;
44 use Cwd qw(abs_path);
45
46 use Carp;
47
48 BEGIN{
49      ($VERSION) = q$Revision$ =~ /^Revision:\s+([^\s+])/;
50      $DEBUG = 0 unless defined $DEBUG;
51
52      @EXPORT = ();
53      %EXPORT_TAGS = (libravatar => [qw(cache_valid retrieve_libravatar cache_location)]
54                     );
55      @EXPORT_OK = ();
56      Exporter::export_ok_tags(keys %EXPORT_TAGS);
57      $EXPORT_TAGS{all} = [@EXPORT_OK];
58 }
59
60 sub cache_valid{
61     my ($cache_location) = @_;
62     if (-e $cache_location) {
63         if (time - (stat($cache_location))[9] < 60*60) {
64             return 1;
65         }
66     }
67     return 0;
68 }
69
70 =over
71
72 =item retrieve_libravatar
73
74      $cache_location = retrieve_libravatar(location => $cache_location,
75                                            email => lc($param{email}),
76                                           );
77
78 Returns the cache location where a specific avatar can be loaded. If
79 there isn't a matching avatar, or there is an error, returns undef.
80
81
82 =cut
83
84 sub retrieve_libravatar{
85     my %type_mapping =
86         (jpeg => 'jpg',
87          png => 'png',
88          gif => 'png',
89          tiff => 'png',
90          tif => 'png',
91          pjpeg => 'jpg',
92          jpg => 'jpg'
93         );
94     my %param = @_;
95     my $cache_location = $param{location};
96     $cache_location =~ s/\.[^\.\/]+$//;
97     # take out a lock on the cache location so that if another request
98     # is made while we are serving this one, we don't do double work
99     my ($fh,$lockfile,$errors) =
100         simple_filelock($cache_location.'.lock',20,0.5);
101     if (not $fh) {
102         return undef;
103     } else {
104         # figure out if the cache is now valid; if it is, return the
105         # cache location
106         my $temp_location = cache_location(email => $param{email});
107         if (cache_valid($temp_location)) {
108             return $temp_location;
109         }
110     }
111     require LWP::UserAgent;
112
113     my $dest_type;
114     eval {
115         my $uri = libravatar_url(email => $param{email},
116                                  default => 404,
117                                  size => 80);
118         my $ua = LWP::UserAgent->new(agent => 'Debbugs libravatar service (not Mozilla)',
119                                     );
120         $ua->from($config{maintainer});
121         # if we don't get an avatar within 10 seconds, return so we
122         # don't block forever
123         $ua->timeout(10);
124         # if the avatar is bigger than 30K, we don't want it either
125         $ua->max_size(30*1024);
126         my $r = $ua->get($uri);
127         if (not $r->is_success()) {
128             die "Not successful in request";
129         }
130         my $aborted = $r->header('Client-Aborted');
131         # if we exceeded max size, I'm not sure if we'll be
132         # successfull or not, but regardless, there will be a
133         # Client-Aborted header. Stop here if that header is defined.
134         die "Client aborted header" if defined $aborted;
135         my $type = $r->header('Content-Type');
136         # if there's no content type, or it's not one we like, we won't
137         # bother going further
138         die "No content type" if not defined $type;
139         die "Wrong content type" if not $type =~ m{^image/([^/]+)$};
140         $dest_type = $type_mapping{$1};
141         die "No dest type" if not defined $dest_type;
142         # undo any content encoding
143         $r->decode() or die "Unable to decode content encoding";
144         # ok, now we need to convert it from whatever it is into a
145         # format that we actually like
146         my ($temp_fh,$temp_fn) = tempfile() or
147             die "Unable to create temporary file";
148         eval {
149             print {$temp_fh} $r->content() or
150                 die "Unable to print to temp file";
151             close ($temp_fh);
152             ### resize all images to 80x80 and strip comments out of
153             ### them. If convert has a bug, it would be possible for
154             ### this to be an attack vector, but hopefully minimizing
155             ### the size above, and requiring proper mime types will
156             ### minimize that slightly. Doing this will at least make
157             ### it harder for malicious web images to harm our users
158             system('convert','-resize','80x80',
159                    '-strip',
160                    $temp_fn,
161                    $cache_location.'.'.$dest_type) == 0 or
162                        die "convert file failed";
163             unlink($temp_fn);
164         };
165         if ($@) {
166             unlink($cache_location.'.'.$dest_type) if -e $cache_location.'.'.$dest_type;
167             unlink($temp_fn) if -e $temp_fn;
168             die "Unable to convert image";
169         }
170     };
171     if ($@) {
172         # there was some kind of error; return undef and unlock the
173         # lock
174         simple_unlockfile($fh,$lockfile);
175         return undef;
176     }
177     simple_unlockfile($fh,$lockfile);
178     return $cache_location.'.'.$dest_type;
179 }
180
181 sub blocked_libravatar {
182     my ($email,$md5sum) = @_;
183     my $blocked = 0;
184     for my $blocker (@{$config{libravatar_blacklist}||[]}) {
185         for my $element ($email,$md5sum) {
186             next unless defined $element;
187             eval {
188                 if ($element =~ /$blocker/) {
189                     $blocked=1;
190                 }
191             };
192         }
193     }
194     return $blocked;
195 }
196
197 sub cache_location {
198     my %param = @_;
199     my $md5sum;
200     if (exists $param{md5sum}) {
201         $md5sum = $param{md5sum};
202     }elsif (exists $param{email}) {
203         $md5sum = md5_hex(lc($param{email}));
204     } else {
205         croak("cache_location must be called with one of md5sum or email");
206     }
207     return undef if blocked_libravatar($param{email},$md5sum);
208     for my $ext (qw(.png .jpg)) {
209         if (-e $config{libravatar_cache_dir}.'/'.$md5sum.$ext) {
210             return $config{libravatar_cache_dir}.'/'.$md5sum.$ext;
211         }
212     }
213     return $config{libravatar_cache_dir}.'/'.$md5sum;
214 }
215
216 ## the following is mod_perl specific
217
218 BEGIN{
219     if (exists $ENV{MOD_PERL_API_VERSION}) {
220         if ($ENV{MOD_PERL_API_VERSION} == 2) {
221             require Apache2::RequestIO;
222             require Apache2::RequestRec;
223             require Apache2::RequestUtil;
224             require Apache2::Const;
225             require APR::Finfo;
226             require APR::Const;
227             APR::Const->import(-compile => qw(FINFO_NORM));
228             Apache2::Const->import(-compile => qw(OK DECLINED FORBIDDEN NOT_FOUND HTTP_NOT_MODIFIED));
229         } else {
230             die "Unsupported mod perl api; mod_perl 2.0.0 or later is required";
231         }
232     }
233 }
234
235 sub handler {
236     die "Calling handler only makes sense if this is running under mod_perl" unless exists $ENV{MOD_PERL_API_VERSION};
237     my $r = shift or Apache2::RequestUtil->request;
238
239     # we only want GET or HEAD requests
240     unless ($r->method eq 'HEAD' or $r->method eq 'GET') {
241         return Apache2::Const::DECLINED();
242     }
243     $r->headers_out->{"X-Powered-By"} = "Debbugs libravatar";
244
245     my $uri = $r->uri();
246     # subtract out location
247     my $location = $r->location();
248     my ($email) = $uri =~ m/\Q$location\E\/?(.*)$/;
249     if (not length $email) {
250         return Apache2::Const::NOT_FOUND();
251     }
252     my $q = CGI::Simple->new();
253     my %param = cgi_parameters(query => $q,
254                                single => [qw(avatar)],
255                                default => {avatar => 'yes',
256                                           },
257                               );
258     if ($param{avatar} ne 'yes' or not defined $email or not length $email) {
259         serve_cache_mod_perl('',$r);
260         return Apache2::Const::DECLINED();
261     }
262     # figure out what the md5sum of the e-mail is.
263     my $cache_location = cache_location(email => $email);
264     # if we've got it, and it's less than one hour old, return it.
265     if (cache_valid($cache_location)) {
266         serve_cache_mod_perl($cache_location,$r);
267         return Apache2::Const::DECLINED();
268     }
269     $cache_location = retrieve_libravatar(location => $cache_location,
270                                           email => $email,
271                                          );
272     if (not defined $cache_location) {
273         # failure, serve the default image
274         serve_cache_mod_perl('',$r);
275         return Apache2::Const::DECLINED();
276     } else {
277         serve_cache_mod_perl($cache_location,$r);
278         return Apache2::Const::DECLINED();
279     }
280 }
281
282
283
284 our $magic;
285
286 sub serve_cache_mod_perl {
287     my ($cache_location,$r) = @_;
288     if (not defined $cache_location or not length $cache_location) {
289         # serve the default image
290         $cache_location = $config{libravatar_default_image};
291     }
292     $magic = File::LibMagic->new() if not defined $magic;
293
294     return Apache2::Const::DECLINED() if not defined $magic;
295
296     $r->content_type($magic->checktype_filename(abs_path($cache_location)));
297
298     $r->filename($cache_location);
299     $r->path_info('');
300     $r->finfo(APR::Finfo::stat($cache_location, APR::Const::FINFO_NORM(), $r->pool));
301 }
302
303 =back
304
305 =cut
306
307 1;
308
309
310 __END__