]> git.deb.at Git - deb/packages.git/blob - lib/Packages/Dispatcher.pm
105117f6ca6f0a382043ed10ea4ff943808bdbdf
[deb/packages.git] / lib / Packages / Dispatcher.pm
1 #!/usr/bin/perl -T
2 # Packages::Dispatcher -- CGI interface for packages.debian.org
3 #
4 # Copyright (C) 2004-2008 Frank Lichtenheld
5 #
6 #    This program is free software; you can redistribute it and/or modify
7 #    it under the terms of the GNU General Public License as published by
8 #    the Free Software Foundation; either version 1 of the License, or
9 #    (at your option) any later version.
10 #
11 #    This program is distributed in the hope that it will be useful,
12 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
13 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 #    GNU General Public License for more details.
15 #
16 #    You should have received a copy of the GNU General Public License
17 #    along with this program; if not, write to the Free Software
18 #    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 package Packages::Dispatcher;
21
22 use strict;
23 use warnings;
24
25 use CGI;
26 use POSIX;
27 use File::Basename;
28 use Template;
29 use DB_File;
30 use URI::Escape;
31 use Benchmark ':hireswallclock';
32 use I18N::AcceptLanguage;
33 use Date::Parse;
34
35 use Deb::Versions;
36 use Packages::Config qw( $DBDIR $ROOT $TEMPLATEDIR $CACHEDIR
37                          @SUITES @SECTIONS @ARCHIVES @ARCHITECTURES @PRIORITIES
38                          @LANGUAGES @DDTP_LANGUAGES );
39 use Packages::CGI qw( :DEFAULT error get_all_messages );
40 use Packages::DB;
41 use Packages::Search qw( :all );
42 use Packages::Template ();
43 use Packages::Sections;
44 use Packages::I18N::Locale;
45
46 use Packages::DoSearch;
47 use Packages::DoSearchContents;
48 use Packages::DoShow;
49 use Packages::DoIndex;
50 use Packages::DoNewPkg;
51 use Packages::DoDownload;
52 use Packages::DoFilelist;
53
54
55 sub do_dispatch {
56
57     &Packages::CGI::reset;
58     $Packages::Search::too_many_hits = 0;
59
60     # clean up env
61     $ENV{PATH} = "/bin:/usr/bin";
62     delete $ENV{'LANGUAGE'};
63     delete $ENV{'LANG'};
64     delete $ENV{'LC_ALL'};
65     delete $ENV{'LC_MESSAGES'};
66
67     my %SUITES_ALIAS = ( oldstable => 'etch',
68                          stable => 'lenny',
69                          testing => 'squeeze',
70                          unstable => 'sid',
71                          '4.0' => 'etch',
72                          '5.0' => 'lenny' );
73
74     # Read in all the variables set by the form
75     my $input;
76     if ($ARGV[0] && ($ARGV[0] eq 'php')) {
77         $input = new CGI(\*STDIN);
78     } else {
79         $input = new CGI;
80     }
81     my $cgi_error = $input->cgi_error;
82     if ($cgi_error) {
83         fatal_error( "Error parsing the request", $cgi_error );
84     }
85
86     my $pet0 = new Benchmark;
87     my $tet0 = new Benchmark;
88     my $debug = DEBUG && $input->param("debug");
89     $debug = 0 if !defined($debug) || $debug !~ /^\d+$/o;
90     $Packages::CGI::debug = $debug;
91
92     my $homedir = dirname($ENV{SCRIPT_FILENAME}).'/../';
93     &Packages::Config::init( $homedir );
94     &Packages::DB::init();
95     my $last_modified = $Packages::DB::db_read_time;
96     my $now = time;
97     my $expires = $last_modified + (12*3600);
98     $expires = $now + 3600 if $expires < $now;
99     # allow some fudge, since the db mod time is not the end of
100     # the cron job
101     $last_modified = $now if $now - $last_modified < 3600;
102
103     if ($input->http('If-Modified-Since') and
104         (my $client_timestamp = str2time($input->http('If-Modified-Since'), 'UTC'))) {
105         if ($client_timestamp > $last_modified) {
106             # we are not modified since asked -> return "304 Not Modified"
107             print $input->header(-status => 304);
108             exit;
109         }
110     }
111
112     my %PO_LANGUAGES = map { $_ => 1 } @LANGUAGES;
113     my %DDTP_LANGUAGES = map { $_ => 1 } @DDTP_LANGUAGES;
114     my $acc = I18N::AcceptLanguage->new(defaultLanguage => 'en');
115     my $ddtp_lang = $acc->accepts( $input->http("Accept-Language"),
116                                    \@DDTP_LANGUAGES );
117     my $po_lang = $acc->accepts( $input->http("Accept-Language"),
118                                  \@LANGUAGES );
119     debug( "LANGS=@LANGUAGES DDTP_LANGS=@DDTP_LANGUAGES header=".
120            ($input->http("Accept-Language")||'').
121            " po_lang=$po_lang ddtp_lang=$ddtp_lang", 1 ) if DEBUG;
122
123     # backwards compatibility stuff
124     debug( "SCRIPT_URL=$ENV{SCRIPT_URL} SCRIPT_URI=$ENV{SCRIPT_URI}" ) if DEBUG;
125
126     if ($ENV{SCRIPT_URL} =~ m|^/cgi-bin/search_|) {
127         error( "You reached this site over an old URL. ".
128                "Depending on the exact parameters your search might work or not." );
129         # contents search changed a lot
130         if ($ENV{SCRIPT_URL} =~ m|^/cgi-bin/search_contents|) {
131             $input->param('keywords',$input->param('word')) if $input->param('word');
132             $input->param('searchon','contents');
133             for ($input->param('searchmode')) {
134                 /^searchfiles/ && do {
135                     $input->param('mode','filename');
136                     last;
137                 };
138                 /^filelist/ && do {
139                     $ENV{PATH_INFO} = '/'.join('/',($input->param('version')||'stable',
140                                                     $input->param('keywords'),
141                                                     $input->param('arch')||'i386',
142                                                     'filelist' ));
143                     $input->delete('searchon','version','keywords','arch');
144                     last;
145                 };
146             }
147         }
148     }
149     if ($ENV{is_reportbug}) {
150         $input->param('exact', 1);
151         debug( "reportbug detected, set paramater exact to '1'" ) if DEBUG;
152     }
153
154     my $what_to_do = 'show';
155     my $source = 0;
156     if (my $path = $ENV{'PATH_INFO'} || $input->param('PATH_INFO')) {
157         my @components = grep { $_ } map { lc $_ } split /\/+/, $path;
158
159         debug( "PATH_INFO=$path components=@components", 3) if DEBUG;
160
161         push @components, 'index' if @components && $path =~ m,/$,;
162
163         my %LANGUAGES = map { $_ => 1 } (@LANGUAGES, @DDTP_LANGUAGES);
164         if (@components > 1 and $LANGUAGES{$components[0]}
165             and !$input->param('lang')) {
166             $input->param( 'lang', shift(@components) );
167         }
168         if (@components > 1 and $components[0] eq 'source') {
169             shift @components;
170             $input->param( 'source', 1 );
171         }
172         if (@components > 0 and $components[0] eq 'search') {
173             shift @components;
174             $what_to_do = 'search';
175             # Done
176             fatal_error( "search doesn't take any more path elements" )
177                 if @components;
178         } elsif (@components == 0) {
179             fatal_error( "We're supposed to display the homepage here, instead of getting dispatch.pl" );
180         } elsif (@components == 1) {
181             if ($components[0] eq 'index') {
182                 $what_to_do = 'homepage';
183             } else {
184                 $what_to_do = 'search';
185             }
186         } else {
187
188             for ($components[-1]) {
189                 /^(index|allpackages|newpkg|changelog|copyright|download|filelist)$/ && do {
190                     pop @components;
191                     $what_to_do = $1;
192                     last;
193                 };
194             }
195
196             my %SUITES = map { $_ => 1 } @SUITES;
197             my %SECTIONS = map { $_ => 1 } @SECTIONS;
198             my %ARCHIVES = map { $_ => 1 } @ARCHIVES;
199             my %ARCHITECTURES = map { $_ => 1 } (@ARCHITECTURES, 'all', 'any');
200             my %PRIORITIES = map { $_ => 1 } @PRIORITIES;
201             my %params_set;
202             sub set_param_once {
203                 my ($cgi, $params_set, $key, $val) = @_;
204                 debug("set_param_once key=$key val=$val",4) if DEBUG;
205                 if ($params_set->{$key}++) {
206                     fatal_error( "$key set more than once in path" );
207                 } else {
208                     $cgi->param( $key, $val );
209                 }
210             }
211
212             my (@pkg, $need_pkg);
213             foreach (reverse @components) {
214                 $need_pkg = !@pkg
215                     && ($what_to_do !~ /^(index|allpackages|newpkg)$/);
216                 debug("need_pkg=$need_pkg component=$_",4) if DEBUG;
217                 if (!$need_pkg && $SUITES{$_}) {
218                     set_param_once( $input, \%params_set, 'suite', $_);
219                 } elsif (!$need_pkg && (my $s = $SUITES_ALIAS{$_})) {
220                     set_param_once( $input, \%params_set, 'suite', $s);
221                 } elsif (!$need_pkg && $SECTIONS{$_}) {
222                     set_param_once( $input, \%params_set, 'section', $_);
223                 } elsif (!$need_pkg && $sections_descs{$_}) {
224                     set_param_once( $input, \%params_set, 'subsection', $_);
225                 } elsif (!$need_pkg && ($_ eq 'source')) {
226                     set_param_once( $input, \%params_set, 'source', 1);
227                 } elsif ($ARCHITECTURES{$_}) {
228                     set_param_once( $input, \%params_set, 'arch', $_)
229                         unless $_ eq 'any';
230                 } elsif (!$need_pkg && $ARCHIVES{$_}) {
231                     set_param_once( $input, \%params_set, 'archive', $_);
232                 } elsif ($PRIORITIES{$_}) {
233                     set_param_once( $input, \%params_set, 'priority', $_);
234                 } else {
235                     push @pkg, $_;
236                 }
237             }
238             @components = @pkg;
239
240             if (@components > 1) {
241                 fatal_error( "two or more packages specified (@components)" );
242             }
243         } # else if (@components == 1)
244
245         if (@components) {
246             my $c = uri_unescape($components[0]);
247             $input->param( 'keywords', $c );
248             $input->param( 'package', $c );
249         }
250     }
251
252     my ( $pkg, @suites, @sections, @subsections, @archives, @archs );
253
254     my %params_def = ( keywords => { default => undef,
255                                      array => '\s+',
256                                      match => '^([-+\@\w\/.:]+)$',
257                                  },
258                        'package' => { default => undef,
259                                       match => '^([\w.+-]+)$',
260                                       var => \$pkg },
261                        suite => { default => 'default', match => '^([\w-]+)$',
262                                   array => ',', var => \@suites,
263                                   replace => { all => \@SUITES,
264                                                default => \@SUITES,
265                                                %SUITES_ALIAS } },
266                        archive => { default => ($what_to_do eq 'search') ?
267                                         'all' : 'default',
268                                         match => '^([\w-]+)$',
269                                         array => ',', var => \@archives,
270                                         replace => { all => \@ARCHIVES,
271                                                      default => \@ARCHIVES} },
272                        exact => { default => 0, match => '^(\w+)$',  },
273                        lang => { default => undef, match => '^([\w-]+)$',  },
274                        source => { default => 0, match => '^(\d+)$',  },
275                        debug => { default => 0, match => '^(\d+)$',  },
276                        searchon => { default => 'names', match => '^(\w+)$', },
277                        section => { default => 'all', match => '^([\w-]+)$',
278                                     alias => 'release', array => ',',
279                                     var => \@sections,
280                                     replace => { all => \@SECTIONS } },
281                        subsection => { default => 'default', match => '^([\w-]+)$',
282                                        array => ',', var => \@subsections,
283                                        replace => { default => [] } },
284                        priority => { default => 'default', match => '^([\w-]+)$',
285                                      array => ',',
286                                      replace => { default => [] } },
287                        arch => { default => 'any', match => '^([\w-]+)$',
288                                  array => ',', var => \@archs, replace =>
289                                  { any => \@ARCHITECTURES } },
290                        'format' => { default => 'html', match => '^([\w.]+)$',  },
291                        mode => { default => '', match => '^(\w+)$',  },
292                        sort_by => { default => 'file', match => '^(\w+)$', },
293                        );
294     my %opts;
295     my %params = Packages::CGI::parse_params( $input, \%params_def, \%opts );
296     Packages::CGI::init_url( $input, \%params, \%opts );
297
298     if (defined($opts{lang})) {
299         $opts{po_lang} = $PO_LANGUAGES{$opts{lang}} ? $opts{lang} : 'en';
300         $opts{ddtp_lang} = $DDTP_LANGUAGES{$opts{lang}} ? $opts{lang} : 'en';
301     } else {
302         $opts{po_lang} = $po_lang;
303         $opts{ddtp_lang} = $ddtp_lang;
304     }
305     my $charset = "UTF-8";
306     my $cat = Packages::I18N::Locale->get_handle( $opts{po_lang}, 'en' )
307         or die "get_handle failed for $opts{po_lang}";
308     $opts{cat} = $cat;
309
310     $opts{h_suites} = { map { $_ => 1 } @suites };
311     $opts{h_sections} = { map { $_ => 1 } @sections };
312     $opts{h_archives} = { map { $_ => 1 } @archives };
313     $opts{h_archs} = { map { $_ => 1 } @archs };
314
315     if ((($opts{searchon} eq 'names') && $opts{source}) ||
316         ($opts{searchon} eq 'sourcenames')) {
317         $opts{source} = 1;
318         $opts{searchon} = 'names',
319         $opts{searchon_form} = 'sourcenames';
320     } else {
321         $opts{searchon_form} = $opts{searchon};
322     }
323     if ($opts{searchon} eq 'contents' or $opts{searchon} eq 'filenames') {
324         $what_to_do = 'search_contents';
325     }
326
327     my $pet1 = new Benchmark;
328     my $petd = timediff($pet1, $pet0);
329     debug( "Parameter evaluation took ".timestr($petd) ) if DEBUG;
330
331     my $template = new Packages::Template( $TEMPLATEDIR, $opts{format},
332                                            { po_lang => $opts{po_lang}, ddtp_lang => $opts{ddtp_lang},
333                                              charset => $charset, cat => $cat,
334                                              debug => ( DEBUG ? $opts{debug} : 0 ) },
335                                            ( $CACHEDIR ? { COMPILE_DIR => $CACHEDIR } : {} ) );
336
337     #FIXME: ugly hack
338     unless (($what_to_do eq 'allpackages' and $opts{format} =~ /^(html|txt\.gz)/)
339             || ($what_to_do eq 'index' and $opts{format} eq 'html')
340             || -e "$TEMPLATEDIR/$opts{format}/${what_to_do}.tmpl") {
341         fatal_error( $cat->g("requested format not available for this document"),
342                      "406 requested format not available");
343     }
344
345     my (%page_content);
346     unless (@Packages::CGI::fatal_errors) {
347         no strict 'refs';
348         &{"do_$what_to_do"}( \%params, \%opts, \%page_content );
349     }
350
351     $page_content{opts} = \%opts;
352     $page_content{params} = \%params;
353
354     unless (@Packages::CGI::fatal_errors) {
355         print $input->header(-charset => $charset,
356                              -type => get_mime($opts{format}),
357                              -vary => 'negotiate,accept-language',
358                              -last_modified => strftime("%a, %d %b %Y %T %z",
359                                                         localtime($last_modified)),
360                              -expires => strftime("%a, %d %b %Y %T %z",
361                                                   localtime($expires)),
362                              );
363         #use Data::Dumper;
364         #print '<pre>'.Dumper(\%ENV, \%page_content, get_all_messages()).'</pre>';
365         print $template->page( $what_to_do, { %page_content, %{ get_all_messages() } } );
366     } elsif ($Packages::CGI::http_code && $Packages::CGI::http_code !~ /^2\d\d/) {
367         print $input->header( -charset => $charset, -status => $Packages::CGI::http_code );
368     } else {
369         # We currently have only an error page in html
370         # so no format support here
371         print $input->header( -charset => $charset );
372         print $template->error_page( get_all_messages() );
373     }
374 }
375
376 1;
377 # vim: ts=8 sw=4