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