memory_usage_is_too_high von Dispatcher nach System::Process verschoben
[kivitendo-erp.git] / SL / Dispatcher.pm
1 package SL::Dispatcher;
2
3 use strict;
4
5 # Force scripts/locales.pl to parse these templates:
6 #   parse_html_template('login_screen/auth_db_unreachable')
7 #   parse_html_template('login_screen/user_login')
8 #   parse_html_template('generic/error')
9
10 use Carp;
11 use CGI qw( -no_xhtml);
12 use Config::Std;
13 use DateTime;
14 use Encode;
15 use English qw(-no_match_vars);
16 use FCGI;
17 use File::Basename;
18 use IO::File;
19 use List::MoreUtils qw(all);
20 use List::Util qw(first);
21 use POSIX qw(setlocale);
22 use SL::ArchiveZipFixes;
23 use SL::Auth;
24 use SL::Dispatcher::AuthHandler;
25 use SL::LXDebug;
26 use SL::LxOfficeConf;
27 use SL::Locale;
28 use SL::ClientJS;
29 use SL::Common;
30 use SL::Form;
31 use SL::Helper::DateTime;
32 use SL::InstanceConfiguration;
33 use SL::Template::Plugin::HTMLFixes;
34 use SL::User;
35
36 use Rose::Object::MakeMethods::Generic (
37   scalar => [ qw(restart_after_request) ],
38 );
39
40 # Trailing new line is added so that Perl will not add the line
41 # number 'die' was called in.
42 use constant END_OF_REQUEST => "END-OF-REQUEST\n";
43
44 my %fcgi_file_cache;
45
46 sub new {
47   my ($class, $interface) = @_;
48
49   my $self           = bless {}, $class;
50   $self->{interface} = lc($interface || 'cgi');
51   $self->{auth_handler} = SL::Dispatcher::AuthHandler->new;
52
53   SL::ArchiveZipFixes->apply_fixes;
54
55   # Initialize character type locale to be UTF-8 instead of C:
56   foreach my $locale (qw(de_DE.UTF-8 en_US.UTF-8)) {
57     last if setlocale('LC_CTYPE', $locale);
58   }
59
60   return $self;
61 }
62
63 sub interface_type {
64   my ($self) = @_;
65   return $self->{interface} eq 'cgi' ? 'CGI' : 'FastCGI';
66 }
67
68 sub is_admin_request {
69   my %params = @_;
70   return ($params{script} eq 'admin.pl') || (($params{routing_type} eq 'controller') && ($params{script_name} eq 'Admin'));
71 }
72
73 sub pre_request_checks {
74   my (%params) = @_;
75
76   _check_for_old_config_files();
77
78   if (!$::auth->session_tables_present && !is_admin_request(%params)) {
79     show_error('login_screen/auth_db_unreachable');
80   }
81
82   if ($::request->type !~ m/^ (?: html | js | json ) $/x) {
83     die $::locale->text("Invalid request type '#1'", $::request->type);
84   }
85 }
86
87 sub pre_request_initialization {
88   my ($self, %params) = @_;
89
90   $self->unrequire_bin_mozilla;
91
92   $::locale        = Locale->new($::lx_office_conf{system}->{language});
93   $::form          = Form->new;
94   $::instance_conf = SL::InstanceConfiguration->new;
95   $::request       = SL::Request->new(
96     cgi            => CGI->new({}),
97     layout         => SL::Layout::None->new,
98   );
99
100   my $session_result = $::auth->restore_session;
101   $::auth->create_or_refresh_session;
102
103   if ($params{client}) {
104     $::auth->set_client($params{client}) || die("cannot find client " . $params{client});
105
106     if ($params{login}) {
107       die "cannot find user " . $params{login}            unless %::myconfig = $::auth->read_user(login => $params{login});
108       die "cannot find locale for user " . $params{login} unless $::locale   = Locale->new($::myconfig{countrycode});
109
110       $::form->{login} = $params{login}; # normaly implicit at login
111     }
112   }
113
114   return $session_result;
115 }
116
117 sub render_error_ajax {
118   my ($error) = @_;
119
120   SL::ClientJS->new
121     ->error($error)
122     ->render(SL::Controller::Base->new);
123 }
124
125 sub show_error {
126   $::lxdebug->enter_sub;
127   my $template             = shift;
128   my $error_type           = shift || '';
129   my %params               = @_;
130
131   $::myconfig{countrycode} = delete($params{countrycode}) || $::lx_office_conf{system}->{language};
132   $::locale                = Locale->new($::myconfig{countrycode});
133   $::form->{error}         = $::locale->text('The session is invalid or has expired.') if ($error_type eq 'session');
134   $::form->{error}         = $::locale->text('Incorrect password!')                    if ($error_type eq 'password');
135   $::form->{error}         = $::locale->text('The action is missing or invalid.')      if ($error_type eq 'action');
136
137   return render_error_ajax($::form->{error}) if $::request->is_ajax;
138
139   $::form->header;
140   print $::form->parse_html_template($template, \%params);
141   $::lxdebug->leave_sub;
142
143   end_request();
144 }
145
146 sub pre_startup_setup {
147   my ($self) = @_;
148
149   SL::LxOfficeConf->read;
150
151   eval {
152     package main;
153     require "bin/mozilla/common.pl";
154     require "bin/mozilla/installationcheck.pl";
155   } or die $EVAL_ERROR;
156
157   # canonial globals. if it's not here, chances are it will get refactored someday.
158   {
159     no warnings 'once';
160     $::lxdebug     = LXDebug->new;
161     $::auth        = SL::Auth->new;
162     $::form        = undef;
163     $::request     = undef;
164     %::myconfig    = User->get_default_myconfig;
165   }
166
167   $SIG{__WARN__} = sub {
168     $::lxdebug->warn(@_);
169   };
170
171   $SIG{__DIE__} = sub { Carp::confess( @_ ) } if $::lx_office_conf{debug}->{backtrace_on_die};
172
173   $self->_cache_file_modification_times;
174 }
175
176 sub pre_startup_checks {
177   ::verify_installation();
178 }
179
180 sub pre_startup {
181   my ($self) = @_;
182   $self->pre_startup_setup;
183   $self->pre_startup_checks;
184 }
185
186 sub require_main_code {
187   $::lxdebug->enter_sub;
188   my ($script, $suffix) = @_;
189
190   eval {
191     package main;
192     require "bin/mozilla/$script$suffix";
193   } or die $EVAL_ERROR;
194
195   if (-f "bin/mozilla/custom_$script$suffix") {
196     eval {
197       package main;
198       require "bin/mozilla/custom_$script$suffix";
199     };
200     $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
201   }
202   if ($::form->{login} && -f "bin/mozilla/$::form->{login}_$script") {
203     eval {
204       package main;
205       require "bin/mozilla/$::form->{login}_$script";
206     };
207     $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
208   }
209   $::lxdebug->leave_sub;
210 }
211
212 sub _require_controller {
213   my $controller =  shift;
214   $controller    =~ s|[^A-Za-z0-9_]||g;
215   $controller    =  "SL/Controller/${controller}";
216
217   eval {
218     package main;
219     require "${controller}.pm";
220   } or die $EVAL_ERROR;
221 }
222
223 sub _run_controller {
224   "SL::Controller::$_[0]"->new->_run_action($_[1]);
225 }
226
227 sub handle_all_requests {
228   my ($self) = @_;
229
230   my $request = FCGI::Request();
231   while ($request->Accept() >= 0) {
232     $self->handle_request($request);
233
234     $self->restart_after_request(1) if $self->_interface_is_fcgi && SL::System::Process::memory_usage_is_too_high();
235     $request->LastCall              if $self->restart_after_request;
236   }
237
238   exec $0 if $self->restart_after_request;
239 }
240
241 sub handle_request {
242   my $self         = shift;
243   $self->{request} = shift;
244
245   $::lxdebug->enter_sub;
246   $::lxdebug->begin_request;
247
248   my ($script, $path, $suffix, $script_name, $action, $routing_type);
249
250   my $session_result = $self->pre_request_initialization;
251
252   $::form->read_cgi_input;
253
254   my %routing;
255   eval { %routing = $self->_route_request($ENV{SCRIPT_NAME}); 1; } or return;
256   ($routing_type, $script_name, $action) = @routing{qw(type controller action)};
257   $::lxdebug->log_request($routing_type, $script_name, $action);
258
259   $::request->type(lc($routing{request_type} || 'html'));
260
261   if ($routing_type eq 'old') {
262     $::form->{action}  =  lc $::form->{action};
263     $::form->{action}  =~ s/( |-|,|\#)/_/g;
264
265    ($script, $path, $suffix) = fileparse($script_name, ".pl");
266     require_main_code($script, $suffix) unless $script eq 'admin';
267
268     $::form->{script} = $script . $suffix;
269
270   } else {
271     _require_controller($script_name);
272     $::form->{script} = "controller.pl";
273   }
274
275   eval {
276     pre_request_checks(script => $script, action => $action, routing_type => $routing_type, script_name => $script_name);
277
278     if (   SL::System::InstallationLock->is_locked
279         && !is_admin_request(script => $script, script_name => $script_name, routing_type => $routing_type)) {
280       $::form->error($::locale->text('System currently down for maintenance!'));
281     }
282
283     # For compatibility with a lot of database upgrade scripts etc:
284     # Re-write request to old 'login.pl?action=login' to new
285     # 'LoginScreen' controller. Make sure to load its code!
286     if (($script eq 'login') && ($action eq 'login')) {
287       ($routing_type, $script, $script_name, $action) = qw(controller controller LoginScreen login);
288       _require_controller('LoginScreen');
289     }
290
291     if (   (($script eq 'login') && !$action)
292         || ($script eq 'admin')
293         || (SL::Auth::SESSION_EXPIRED() == $session_result)) {
294       $self->redirect_to_login(script => $script, error => 'session');
295
296     }
297
298     my %auth_result = $self->{auth_handler}->handle(
299       routing_type => $routing_type,
300       script       => $script,
301       controller   => $script_name,
302       action       => $action,
303     );
304
305     $self->end_request unless $auth_result{auth_ok};
306
307     delete @{ $::form }{ grep { m/^\{AUTH\}/ } keys %{ $::form } } unless $auth_result{keep_auth_vars};
308
309     if ($action) {
310       $::form->set_standard_title;
311       if ($routing_type eq 'old') {
312         ::call_sub('::' . $::locale->findsub($action));
313       } else {
314         _run_controller($script_name, $action);
315       }
316     } else {
317       $::form->error($::locale->text('action= not defined!'));
318     }
319
320     1;
321   } or do {
322     if (substr($EVAL_ERROR, 0, length(END_OF_REQUEST())) ne END_OF_REQUEST()) {
323       my $error = $EVAL_ERROR;
324       print STDERR $error;
325
326       if ($::request->is_ajax) {
327         eval { render_error_ajax($error) };
328       } else {
329         $::form->{label_error} = $::request->{cgi}->pre($error);
330         chdir SL::System::Process::exe_dir;
331         eval { show_error('generic/error') };
332       }
333     }
334   };
335
336   $::form->footer;
337
338   if ($self->_interface_is_fcgi) {
339     # fcgi? send send reponse on its way before cleanup.
340     $self->{request}->Flush;
341     $self->{request}->Finish;
342   }
343
344   $::lxdebug->end_request(routing_type => $routing_type, script_name => $script_name, action => $action);
345
346   # cleanup
347   $::auth->save_session;
348   $::auth->expire_sessions;
349   $::auth->reset;
350
351   $::locale   = undef;
352   $::form     = undef;
353   %::myconfig = ();
354   $::request  = undef;
355
356   SL::DBConnect::Cache->reset_all;
357
358   $self->_watch_for_changed_files;
359
360   $::lxdebug->leave_sub;
361 }
362
363 sub redirect_to_login {
364   my ($self, %params) = @_;
365   my $action          = ($params{script} // '') =~ m/^admin/i ? 'Admin/login' : 'LoginScreen/user_login';
366   $action            .= '&error=' . $params{error} if $params{error};
367
368   print $::request->cgi->redirect("controller.pl?action=${action}");
369   $self->end_request;
370 }
371
372 sub unrequire_bin_mozilla {
373   my $self = shift;
374   return unless $self->_interface_is_fcgi;
375
376   for (keys %INC) {
377     next unless m#^bin/mozilla/#;
378     next if /\bcommon.pl$/;
379     next if /\binstallationcheck.pl$/;
380     delete $INC{$_};
381   }
382 }
383
384 sub _interface_is_fcgi {
385   my $self = shift;
386   return $self->{interface} =~ m/^(?:fastcgi|fcgid|fcgi)$/;
387 }
388
389 sub _route_request {
390   my ($self, $script_name) = @_;
391
392   return $script_name =~ m/dispatcher\.pl$/ ? (type => 'old',        $self->_route_dispatcher_request)
393        : $script_name =~ m/controller\.pl/  ? (type => 'controller', $self->_route_controller_request)
394        :                                      (type => 'old',        controller => $script_name, action => $::form->{action});
395 }
396
397 sub _route_dispatcher_request {
398   my ($self)  = @_;
399   my $name_re = qr{[a-z]\w*};
400   my ($script_name, $action);
401
402   eval {
403     die "Unroutable request -- invalid module name.\n" if !$::form->{M} || ($::form->{M} !~ m/^${name_re}$/);
404     $script_name = $::form->{M} . '.pl';
405
406     if ($::form->{A}) {
407       $action = $::form->{A};
408
409     } else {
410       $action = first { m/^A_${name_re}$/ } keys %{ $::form };
411       die "Unroutable request -- invalid action name.\n" if !$action;
412
413       delete $::form->{$action};
414       $action = substr $action, 2;
415     }
416
417     delete @{$::form}{qw(M A)};
418
419     1;
420   } or do {
421     $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
422     show_error('generic/error');
423   };
424
425   return (controller => $script_name, action => $action);
426 }
427
428 sub _route_controller_request {
429   my ($self) = @_;
430   my ($controller, $action, $request_type);
431
432   eval {
433     # Redirect simple requests to controller.pl without any GET/POST
434     # param to the login page.
435     $self->redirect_to_login(error => 'action') if !$::form->{action};
436
437     # Show an error if the »action« parameter doesn't match the
438     # pattern »Controller/action«.
439     $::form->{action}      =~ m|^ ( [A-Z] [A-Za-z0-9_]* ) / ( [a-z] [a-z0-9_]* ) ( \. [a-zA-Z]+ )? $|x || die "Unroutable request -- invalid controller/action.\n";
440     ($controller, $action) =  ($1, $2);
441     delete $::form->{action};
442
443     $request_type = $3 ? lc(substr($3, 1)) : 'html';
444
445     1;
446   } or do {
447     $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
448     show_error('generic/error');
449   };
450
451   return (controller => $controller, action => $action, request_type => $request_type);
452 }
453
454 sub _cache_file_modification_times {
455   my ($self) = @_;
456
457   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
458
459   require File::Find;
460   require POSIX;
461
462   my $wanted = sub {
463     return unless $File::Find::name =~ m/\.(?:pm|f?pl|html|conf|conf\.default)$/;
464     $fcgi_file_cache{ $File::Find::name } = (stat $File::Find::name)[9];
465   };
466
467   my $cwd = POSIX::getcwd();
468   File::Find::find($wanted, map { "${cwd}/${_}" } qw(config bin SL templates/webpages));
469   map { my $name = "${cwd}/${_}"; $fcgi_file_cache{$name} = (stat $name)[9] } qw(admin.pl dispatcher.fpl);
470 }
471
472 sub _watch_for_changed_files {
473   my ($self) = @_;
474
475   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
476
477   my $ok = all { (stat($_))[9] == $fcgi_file_cache{$_} } keys %fcgi_file_cache;
478   return if $ok;
479   $::lxdebug->message(LXDebug::DEBUG1(), "Program modifications detected. Restarting.");
480   $self->restart_after_request(1);
481 }
482
483 sub get_standard_filehandles {
484   my $self = shift;
485
486   return $self->{interface} =~ m/f(?:ast)cgi/i ? $self->{request}->GetHandles() : (\*STDIN, \*STDOUT, \*STDERR);
487 }
488
489 sub _check_for_old_config_files {
490   my @old_files = grep { -f "config/${_}" } qw(authentication.pl console.conf lx-erp.conf lx-erp-local.conf);
491   return unless @old_files;
492
493   $::form->{title} = $::locale->text('Old configuration files');
494   $::form->header;
495   print $::form->parse_html_template('login_screen/old_configuration_files', { FILES => \@old_files });
496
497   end_request();
498 }
499
500 sub end_request {
501   die SL::Dispatcher->END_OF_REQUEST;
502 }
503
504 1;