1 package SL::Dispatcher;
 
   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')
 
  11 use CGI qw( -no_xhtml);
 
  15 use English qw(-no_match_vars);
 
  19 use List::MoreUtils qw(all);
 
  20 use List::Util qw(first);
 
  21 use SL::ArchiveZipFixes;
 
  23 use SL::Dispatcher::AuthHandler;
 
  30 use SL::Helper::DateTime;
 
  31 use SL::InstanceConfiguration;
 
  32 use SL::Template::Plugin::HTMLFixes;
 
  35 use Rose::Object::MakeMethods::Generic (
 
  36   scalar => [ qw(restart_after_request) ],
 
  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";
 
  46   my ($class, $interface) = @_;
 
  48   my $self           = bless {}, $class;
 
  49   $self->{interface} = lc($interface || 'cgi');
 
  50   $self->{auth_handler} = SL::Dispatcher::AuthHandler->new;
 
  52   SL::ArchiveZipFixes->apply_fixes;
 
  59   return $self->{interface} eq 'cgi' ? 'CGI' : 'FastCGI';
 
  62 sub is_admin_request {
 
  64   return ($params{script} eq 'admin.pl') || (($params{routing_type} eq 'controller') && ($params{script_name} eq 'Admin'));
 
  67 sub pre_request_checks {
 
  70   _check_for_old_config_files();
 
  72   if (!$::auth->session_tables_present && !is_admin_request(%params)) {
 
  73     show_error('login_screen/auth_db_unreachable');
 
  76   if ($::request->type !~ m/^ (?: html | js | json ) $/x) {
 
  77     die $::locale->text("Invalid request type '#1'", $::request->type);
 
  81 sub pre_request_initialization {
 
  82   my ($self, %params) = @_;
 
  84   $self->unrequire_bin_mozilla;
 
  86   $::locale        = Locale->new($::lx_office_conf{system}->{language});
 
  88   $::instance_conf = SL::InstanceConfiguration->new;
 
  89   $::request       = SL::Request->new(
 
  91     layout         => SL::Layout::None->new,
 
  94   my $session_result = $::auth->restore_session;
 
  95   $::auth->create_or_refresh_session;
 
  97   if ($params{client}) {
 
  98     $::auth->set_client($params{client}) || die("cannot find client " . $params{client});
 
 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});
 
 104       $::form->{login} = $params{login}; # normaly implicit at login
 
 108   return $session_result;
 
 111 sub render_error_ajax {
 
 116     ->render(SL::Controller::Base->new);
 
 120   $::lxdebug->enter_sub;
 
 121   my $template             = shift;
 
 122   my $error_type           = shift || '';
 
 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');
 
 131   return render_error_ajax($::form->{error}) if $::request->is_ajax;
 
 134   print $::form->parse_html_template($template, \%params);
 
 135   $::lxdebug->leave_sub;
 
 140 sub pre_startup_setup {
 
 143   SL::LxOfficeConf->read;
 
 147     require "bin/mozilla/common.pl";
 
 148     require "bin/mozilla/installationcheck.pl";
 
 149   } or die $EVAL_ERROR;
 
 151   # canonial globals. if it's not here, chances are it will get refactored someday.
 
 154     $::lxdebug     = LXDebug->new;
 
 155     $::auth        = SL::Auth->new;
 
 158     %::myconfig    = User->get_default_myconfig;
 
 161   $SIG{__WARN__} = sub {
 
 162     $::lxdebug->warn(@_);
 
 165   $SIG{__DIE__} = sub { Carp::confess( @_ ) } if $::lx_office_conf{debug}->{backtrace_on_die};
 
 167   $self->_cache_file_modification_times;
 
 170 sub pre_startup_checks {
 
 171   ::verify_installation();
 
 176   $self->pre_startup_setup;
 
 177   $self->pre_startup_checks;
 
 180 sub require_main_code {
 
 181   $::lxdebug->enter_sub;
 
 182   my ($script, $suffix) = @_;
 
 186     require "bin/mozilla/$script$suffix";
 
 187   } or die $EVAL_ERROR;
 
 189   if (-f "bin/mozilla/custom_$script$suffix") {
 
 192       require "bin/mozilla/custom_$script$suffix";
 
 194     $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
 
 196   if ($::form->{login} && -f "bin/mozilla/$::form->{login}_$script") {
 
 199       require "bin/mozilla/$::form->{login}_$script";
 
 201     $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
 
 203   $::lxdebug->leave_sub;
 
 206 sub _require_controller {
 
 207   my $controller =  shift;
 
 208   $controller    =~ s|[^A-Za-z0-9_]||g;
 
 209   $controller    =  "SL/Controller/${controller}";
 
 213     require "${controller}.pm";
 
 214   } or die $EVAL_ERROR;
 
 217 sub _run_controller {
 
 218   "SL::Controller::$_[0]"->new->_run_action($_[1]);
 
 221 sub handle_all_requests {
 
 224   my $request = FCGI::Request();
 
 225   while ($request->Accept() >= 0) {
 
 226     $self->handle_request($request);
 
 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;
 
 232   exec $0 if $self->restart_after_request;
 
 237   $self->{request} = shift;
 
 239   $::lxdebug->enter_sub;
 
 240   $::lxdebug->begin_request;
 
 242   my ($script, $path, $suffix, $script_name, $action, $routing_type);
 
 244   my $session_result = $self->pre_request_initialization;
 
 246   $::form->read_cgi_input;
 
 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);
 
 253   $::request->type(lc($routing{request_type} || 'html'));
 
 255   if ($routing_type eq 'old') {
 
 256     $::form->{action}  =  lc $::form->{action};
 
 257     $::form->{action}  =~ s/( |-|,|\#)/_/g;
 
 259    ($script, $path, $suffix) = fileparse($script_name, ".pl");
 
 260     require_main_code($script, $suffix) unless $script eq 'admin';
 
 262     $::form->{script} = $script . $suffix;
 
 265     _require_controller($script_name);
 
 266     $::form->{script} = "controller.pl";
 
 270     pre_request_checks(script => $script, action => $action, routing_type => $routing_type, script_name => $script_name);
 
 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!'));
 
 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');
 
 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');
 
 292     my %auth_result = $self->{auth_handler}->handle(
 
 293       routing_type => $routing_type,
 
 295       controller   => $script_name,
 
 299     $self->end_request unless $auth_result{auth_ok};
 
 301     delete @{ $::form }{ grep { m/^\{AUTH\}/ } keys %{ $::form } } unless $auth_result{keep_auth_vars};
 
 304       $::form->set_standard_title;
 
 305       if ($routing_type eq 'old') {
 
 306         ::call_sub('::' . $::locale->findsub($action));
 
 308         _run_controller($script_name, $action);
 
 311       $::form->error($::locale->text('action= not defined!'));
 
 316     if (substr($EVAL_ERROR, 0, length(END_OF_REQUEST())) ne END_OF_REQUEST()) {
 
 317       my $error = $EVAL_ERROR;
 
 320       if ($::request->is_ajax) {
 
 321         eval { render_error_ajax($error) };
 
 323         $::form->{label_error} = $::request->{cgi}->pre($error);
 
 324         chdir SL::System::Process::exe_dir;
 
 325         eval { show_error('generic/error') };
 
 332   if ($self->_interface_is_fcgi) {
 
 333     # fcgi? send send reponse on its way before cleanup.
 
 334     $self->{request}->Flush;
 
 335     $self->{request}->Finish;
 
 338   $::lxdebug->end_request(routing_type => $routing_type, script_name => $script_name, action => $action);
 
 341   $::auth->save_session;
 
 342   $::auth->expire_sessions;
 
 350   SL::DBConnect::Cache->reset_all;
 
 352   $self->_watch_for_changed_files;
 
 354   $::lxdebug->leave_sub;
 
 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};
 
 362   print $::request->cgi->redirect("controller.pl?action=${action}");
 
 366 sub unrequire_bin_mozilla {
 
 368   return unless $self->_interface_is_fcgi;
 
 371     next unless m#^bin/mozilla/#;
 
 372     next if /\bcommon.pl$/;
 
 373     next if /\binstallationcheck.pl$/;
 
 378 sub _interface_is_fcgi {
 
 380   return $self->{interface} =~ m/^(?:fastcgi|fcgid|fcgi)$/;
 
 384   my ($self, $script_name) = @_;
 
 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});
 
 391 sub _route_dispatcher_request {
 
 393   my $name_re = qr{[a-z]\w*};
 
 394   my ($script_name, $action);
 
 397     die "Unroutable request -- invalid module name.\n" if !$::form->{M} || ($::form->{M} !~ m/^${name_re}$/);
 
 398     $script_name = $::form->{M} . '.pl';
 
 401       $action = $::form->{A};
 
 404       $action = first { m/^A_${name_re}$/ } keys %{ $::form };
 
 405       die "Unroutable request -- invalid action name.\n" if !$action;
 
 407       delete $::form->{$action};
 
 408       $action = substr $action, 2;
 
 411     delete @{$::form}{qw(M A)};
 
 415     $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
 
 416     show_error('generic/error');
 
 419   return (controller => $script_name, action => $action);
 
 422 sub _route_controller_request {
 
 424   my ($controller, $action, $request_type);
 
 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};
 
 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};
 
 437     $request_type = $3 ? lc(substr($3, 1)) : 'html';
 
 441     $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
 
 442     show_error('generic/error');
 
 445   return (controller => $controller, action => $action, request_type => $request_type);
 
 448 sub _cache_file_modification_times {
 
 451   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
 
 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];
 
 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);
 
 466 sub _watch_for_changed_files {
 
 469   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
 
 471   my $ok = all { (stat($_))[9] == $fcgi_file_cache{$_} } keys %fcgi_file_cache;
 
 473   $::lxdebug->message(LXDebug::DEBUG1(), "Program modifications detected. Restarting.");
 
 474   $self->restart_after_request(1);
 
 477 sub get_standard_filehandles {
 
 480   return $self->{interface} =~ m/f(?:ast)cgi/i ? $self->{request}->GetHandles() : (\*STDIN, \*STDOUT, \*STDERR);
 
 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;
 
 487   $::form->{title} = $::locale->text('Old configuration files');
 
 489   print $::form->parse_html_template('login_screen/old_configuration_files', { FILES => \@old_files });
 
 494 sub _parse_number_with_unit {
 
 497   return undef   unless defined $number;
 
 498   return $number unless $number =~ m{^ \s* (\d+) \s* ([kmg])b \s* $}xi;
 
 500   my %factors = (K => 1024, M => 1024 * 1024, G => 1024 * 1024 * 1024);
 
 502   return $1 * $factors{uc $2};
 
 505 sub _memory_usage_is_too_high {
 
 506   return undef unless $::lx_office_conf{system};
 
 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}),
 
 513   # $::lxdebug->dump(0, "limits", \%limits);
 
 515   return undef unless $limits{rss} || $limits{vsz};
 
 519   my $in = IO::File->new("/proc/$$/status", "r") or return undef;
 
 523     $usage{lc $1} = _parse_number_with_unit($2) if m{^ vm(rss|size): \s* (\d+ \s* [kmg]b) \s* $}ix;
 
 528   # $::lxdebug->dump(0, "usage", \%usage);
 
 530   foreach my $type (keys %limits) {
 
 531     next if !$limits{$type};
 
 532     next if $limits{$type} >= ($usage{$type} // 0);
 
 534     $::lxdebug->message(LXDebug::WARN(), "Exiting due to memory size limit reached for type '${type}': limit " . $limits{$type} . " bytes, usage " . $usage{$type} . " bytes");
 
 543   die SL::Dispatcher->END_OF_REQUEST;