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