357f9f8fd97b48823d56b14b6392121ecc25bcc9
[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_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     $self->end_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
361   $self->_watch_for_changed_files;
362
363   $::lxdebug->leave_sub;
364 }
365
366 sub redirect_to_login {
367   my ($self, %params) = @_;
368   my $action          = ($params{script} // '') =~ m/^admin/i ? 'Admin/login' : 'LoginScreen/user_login';
369   $action            .= '&error=' . $params{error} if $params{error};
370
371   print $::request->cgi->redirect("controller.pl?action=${action}");
372   $self->end_request;
373 }
374
375 sub unrequire_bin_mozilla {
376   my $self = shift;
377   return unless $self->_interface_is_fcgi;
378
379   for (keys %INC) {
380     next unless m#^bin/mozilla/#;
381     next if /\bcommon.pl$/;
382     next if /\binstallationcheck.pl$/;
383     delete $INC{$_};
384   }
385 }
386
387 sub _interface_is_fcgi {
388   my $self = shift;
389   return $self->{interface} =~ m/^(?:fastcgi|fcgid|fcgi)$/;
390 }
391
392 sub _route_request {
393   my ($self, $script_name) = @_;
394
395   return $script_name =~ m/dispatcher\.pl$/ ? (type => 'old',        $self->_route_dispatcher_request)
396        : $script_name =~ m/controller\.pl/  ? (type => 'controller', $self->_route_controller_request)
397        :                                      (type => 'old',        controller => $script_name, action => $::form->{action});
398 }
399
400 sub _route_dispatcher_request {
401   my ($self)  = @_;
402   my $name_re = qr{[a-z]\w*};
403   my ($script_name, $action);
404
405   eval {
406     die "Unroutable request -- invalid module name.\n" if !$::form->{M} || ($::form->{M} !~ m/^${name_re}$/);
407     $script_name = $::form->{M} . '.pl';
408
409     if ($::form->{A}) {
410       $action = $::form->{A};
411
412     } else {
413       $action = first { m/^A_${name_re}$/ } keys %{ $::form };
414       die "Unroutable request -- invalid action name.\n" if !$action;
415
416       delete $::form->{$action};
417       $action = substr $action, 2;
418     }
419
420     delete @{$::form}{qw(M A)};
421
422     1;
423   } or do {
424     $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
425     show_error('generic/error');
426   };
427
428   return (controller => $script_name, action => $action);
429 }
430
431 sub _route_controller_request {
432   my ($self) = @_;
433   my ($controller, $action, $request_type);
434
435   eval {
436     # Redirect simple requests to controller.pl without any GET/POST
437     # param to the login page.
438     $self->redirect_to_login(error => 'action') if !$::form->{action};
439
440     # Show an error if the »action« parameter doesn't match the
441     # pattern »Controller/action«.
442     $::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";
443     ($controller, $action) =  ($1, $2);
444     delete $::form->{action};
445
446     $request_type = $3 ? lc(substr($3, 1)) : 'html';
447
448     1;
449   } or do {
450     $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
451     show_error('generic/error');
452   };
453
454   return (controller => $controller, action => $action, request_type => $request_type);
455 }
456
457 sub _cache_file_modification_times {
458   my ($self) = @_;
459
460   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
461
462   require File::Find;
463   require POSIX;
464
465   my $wanted = sub {
466     return unless $File::Find::name =~ m/\.(?:pm|f?pl|html|conf|conf\.default)$/;
467     $fcgi_file_cache{ $File::Find::name } = (stat $File::Find::name)[9];
468   };
469
470   my $cwd = POSIX::getcwd();
471   File::Find::find($wanted, map { "${cwd}/${_}" } qw(config bin SL templates/webpages));
472   map { my $name = "${cwd}/${_}"; $fcgi_file_cache{$name} = (stat $name)[9] } qw(admin.pl dispatcher.fpl);
473 }
474
475 sub _watch_for_changed_files {
476   my ($self) = @_;
477
478   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
479
480   my $ok = all { (stat($_))[9] == $fcgi_file_cache{$_} } keys %fcgi_file_cache;
481   return if $ok;
482   $::lxdebug->message(LXDebug::DEBUG1(), "Program modifications detected. Restarting.");
483   $self->restart_after_request(1);
484 }
485
486 sub get_standard_filehandles {
487   my $self = shift;
488
489   return $self->{interface} =~ m/f(?:ast)cgi/i ? $self->{request}->GetHandles() : (\*STDIN, \*STDOUT, \*STDERR);
490 }
491
492 sub _check_for_old_config_files {
493   my @old_files = grep { -f "config/${_}" } qw(authentication.pl console.conf lx-erp.conf lx-erp-local.conf);
494   return unless @old_files;
495
496   $::form->{title} = $::locale->text('Old configuration files');
497   $::form->header;
498   print $::form->parse_html_template('login_screen/old_configuration_files', { FILES => \@old_files });
499
500   end_request();
501 }
502
503 sub _parse_number_with_unit {
504   my ($number) = @_;
505
506   return undef   unless defined $number;
507   return $number unless $number =~ m{^ \s* (\d+) \s* ([kmg])b \s* $}xi;
508
509   my %factors = (K => 1024, M => 1024 * 1024, G => 1024 * 1024 * 1024);
510
511   return $1 * $factors{uc $2};
512 }
513
514 sub _memory_usage_is_too_high {
515   return undef unless $::lx_office_conf{system};
516
517   my %limits = (
518     rss  => _parse_number_with_unit($::lx_office_conf{system}->{memory_limit_rss}),
519     size => _parse_number_with_unit($::lx_office_conf{system}->{memory_limit_vsz}),
520   );
521
522   # $::lxdebug->dump(0, "limits", \%limits);
523
524   return undef unless $limits{rss} || $limits{vsz};
525
526   my %usage;
527
528   my $in = IO::File->new("/proc/$$/status", "r") or return undef;
529
530   while (<$in>) {
531     chomp;
532     $usage{lc $1} = _parse_number_with_unit($2) if m{^ vm(rss|size): \s* (\d+ \s* [kmg]b) \s* $}ix;
533   }
534
535   $in->close;
536
537   # $::lxdebug->dump(0, "usage", \%usage);
538
539   foreach my $type (keys %limits) {
540     next if !$limits{$type};
541     next if $limits{$type} >= ($usage{$type} // 0);
542
543     $::lxdebug->message(LXDebug::WARN(), "Exiting due to memory size limit reached for type '${type}': limit " . $limits{$type} . " bytes, usage " . $usage{$type} . " bytes");
544
545     return 1;
546   }
547
548   return 0;
549 }
550
551 sub end_request {
552   die SL::Dispatcher->END_OF_REQUEST;
553 }
554
555 1;