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