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 SL::System::Process;
12 my $exe_dir = SL::System::Process::exe_dir;
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;
20 use CGI qw( -no_xhtml);
24 use English qw(-no_match_vars);
28 use List::MoreUtils qw(all);
29 use List::Util qw(first);
30 use SL::ArchiveZipFixes;
32 use SL::Dispatcher::AuthHandler;
39 use SL::Helper::DateTime;
40 use SL::InstanceConfiguration;
41 use SL::Template::Plugin::HTMLFixes;
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";
51 my ($class, $interface) = @_;
53 my $self = bless {}, $class;
54 $self->{interface} = lc($interface || 'cgi');
55 $self->{auth_handler} = SL::Dispatcher::AuthHandler->new;
57 SL::ArchiveZipFixes->apply_fixes;
64 return $self->{interface} eq 'cgi' ? 'CGI' : 'FastCGI';
67 sub is_admin_request {
69 return ($params{script} eq 'admin.pl') || (($params{routing_type} eq 'controller') && ($params{script_name} eq 'Admin'));
72 sub pre_request_checks {
75 _check_for_old_config_files();
77 if (!$::auth->session_tables_present && !is_admin_request(%params)) {
78 show_error('login_screen/auth_db_unreachable');
81 if ($::request->type !~ m/^ (?: html | js | json ) $/x) {
82 die $::locale->text("Invalid request type '#1'", $::request->type);
86 sub pre_request_initialization {
87 my ($self, %params) = @_;
89 $self->unrequire_bin_mozilla;
91 $::locale = Locale->new($::lx_office_conf{system}->{language});
93 $::instance_conf = SL::InstanceConfiguration->new;
94 $::request = SL::Request->new(
96 layout => SL::Layout::None->new,
99 my $session_result = $::auth->restore_session;
100 $::auth->create_or_refresh_session;
102 if ($params{client}) {
103 $::auth->set_client($params{client}) || die("cannot find client " . $params{client});
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});
109 $::form->{login} = $params{login}; # normaly implicit at login
113 return $session_result;
116 sub render_error_ajax {
121 ->render(SL::Controller::Base->new);
125 $::lxdebug->enter_sub;
126 my $template = shift;
127 my $error_type = shift || '';
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');
136 return render_error_ajax($::form->{error}) if $::request->is_ajax;
139 print $::form->parse_html_template($template, \%params);
140 $::lxdebug->leave_sub;
145 sub pre_startup_setup {
148 SL::LxOfficeConf->read;
152 require "bin/mozilla/common.pl";
153 require "bin/mozilla/installationcheck.pl";
154 } or die $EVAL_ERROR;
156 # canonial globals. if it's not here, chances are it will get refactored someday.
159 $::lxdebug = LXDebug->new;
160 $::auth = SL::Auth->new;
163 %::myconfig = User->get_default_myconfig;
166 $SIG{__WARN__} = sub {
167 $::lxdebug->warn(@_);
170 $SIG{__DIE__} = sub { Carp::confess( @_ ) } if $::lx_office_conf{debug}->{backtrace_on_die};
172 $self->_cache_file_modification_times;
175 sub pre_startup_checks {
176 ::verify_installation();
181 $self->pre_startup_setup;
182 $self->pre_startup_checks;
185 sub require_main_code {
186 $::lxdebug->enter_sub;
187 my ($script, $suffix) = @_;
191 require "bin/mozilla/$script$suffix";
192 } or die $EVAL_ERROR;
194 if (-f "bin/mozilla/custom_$script$suffix") {
197 require "bin/mozilla/custom_$script$suffix";
199 $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
201 if ($::form->{login} && -f "bin/mozilla/$::form->{login}_$script") {
204 require "bin/mozilla/$::form->{login}_$script";
206 $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
208 $::lxdebug->leave_sub;
211 sub _require_controller {
212 my $controller = shift;
213 $controller =~ s|[^A-Za-z0-9_]||g;
214 $controller = "SL/Controller/${controller}";
218 require "${controller}.pm";
219 } or die $EVAL_ERROR;
222 sub _run_controller {
223 "SL::Controller::$_[0]"->new->_run_action($_[1]);
226 sub handle_all_requests {
230 my $request = FCGI::Request();
231 while ($request->Accept() >= 0) {
232 $self->handle_request($request);
233 if (($self->interface_type eq 'FastCGI') && _memory_usage_is_too_high()) {
234 $request->LastCall();
244 $self->{request} = shift;
246 $::lxdebug->enter_sub;
247 $::lxdebug->begin_request;
249 my ($script, $path, $suffix, $script_name, $action, $routing_type);
251 my $session_result = $self->pre_request_initialization;
253 $::form->read_cgi_input;
256 eval { %routing = $self->_route_request($ENV{SCRIPT_NAME}); 1; } or return;
257 ($routing_type, $script_name, $action) = @routing{qw(type controller action)};
258 $::lxdebug->log_request($routing_type, $script_name, $action);
260 $::request->type(lc($routing{request_type} || 'html'));
262 if ($routing_type eq 'old') {
263 $::form->{action} = lc $::form->{action};
264 $::form->{action} =~ s/( |-|,|\#)/_/g;
266 ($script, $path, $suffix) = fileparse($script_name, ".pl");
267 require_main_code($script, $suffix) unless $script eq 'admin';
269 $::form->{script} = $script . $suffix;
272 _require_controller($script_name);
273 $::form->{script} = "controller.pl";
277 pre_request_checks(script => $script, action => $action, routing_type => $routing_type, script_name => $script_name);
279 if ( SL::System::InstallationLock->is_locked
280 && !is_admin_request(script => $script, script_name => $script_name, routing_type => $routing_type)) {
281 $::form->error($::locale->text('System currently down for maintenance!'));
284 # For compatibility with a lot of database upgrade scripts etc:
285 # Re-write request to old 'login.pl?action=login' to new
286 # 'LoginScreen' controller. Make sure to load its code!
287 if (($script eq 'login') && ($action eq 'login')) {
288 ($routing_type, $script, $script_name, $action) = qw(controller controller LoginScreen login);
289 _require_controller('LoginScreen');
292 if ( (($script eq 'login') && !$action)
293 || ($script eq 'admin')
294 || (SL::Auth::SESSION_EXPIRED() == $session_result)) {
295 $self->redirect_to_login(script => $script, error => 'session');
299 my %auth_result = $self->{auth_handler}->handle(
300 routing_type => $routing_type,
302 controller => $script_name,
306 ::end_of_request() unless $auth_result{auth_ok};
308 delete @{ $::form }{ grep { m/^\{AUTH\}/ } keys %{ $::form } } unless $auth_result{keep_auth_vars};
311 $::form->set_standard_title;
312 if ($routing_type eq 'old') {
313 ::call_sub('::' . $::locale->findsub($action));
315 _run_controller($script_name, $action);
318 $::form->error($::locale->text('action= not defined!'));
323 if (substr($EVAL_ERROR, 0, length(END_OF_REQUEST())) ne END_OF_REQUEST()) {
324 my $error = $EVAL_ERROR;
327 if ($::request->is_ajax) {
328 eval { render_error_ajax($error) };
330 $::form->{label_error} = $::request->{cgi}->pre($error);
331 chdir SL::System::Process::exe_dir;
332 eval { show_error('generic/error') };
339 if ($self->_interface_is_fcgi) {
340 # fcgi? send send reponse on its way before cleanup.
341 $self->{request}->Flush;
342 $self->{request}->Finish;
345 $::lxdebug->end_request(routing_type => $routing_type, script_name => $script_name, action => $action);
348 $::auth->save_session;
349 $::auth->expire_sessions;
357 SL::DBConnect::Cache->reset_all;
358 Form::disconnect_standard_dbh;
360 $self->_watch_for_changed_files;
362 $::lxdebug->leave_sub;
365 sub redirect_to_login {
366 my ($self, %params) = @_;
367 my $action = ($params{script} // '') =~ m/^admin/i ? 'Admin/login' : 'LoginScreen/user_login';
368 $action .= '&error=' . $params{error} if $params{error};
370 print $::request->cgi->redirect("controller.pl?action=${action}");
374 sub unrequire_bin_mozilla {
376 return unless $self->_interface_is_fcgi;
379 next unless m#^bin/mozilla/#;
380 next if /\bcommon.pl$/;
381 next if /\binstallationcheck.pl$/;
386 sub _interface_is_fcgi {
388 return $self->{interface} =~ m/^(?:fastcgi|fcgid|fcgi)$/;
392 my ($self, $script_name) = @_;
394 return $script_name =~ m/dispatcher\.pl$/ ? (type => 'old', $self->_route_dispatcher_request)
395 : $script_name =~ m/controller\.pl/ ? (type => 'controller', $self->_route_controller_request)
396 : (type => 'old', controller => $script_name, action => $::form->{action});
399 sub _route_dispatcher_request {
401 my $name_re = qr{[a-z]\w*};
402 my ($script_name, $action);
405 die "Unroutable request -- invalid module name.\n" if !$::form->{M} || ($::form->{M} !~ m/^${name_re}$/);
406 $script_name = $::form->{M} . '.pl';
409 $action = $::form->{A};
412 $action = first { m/^A_${name_re}$/ } keys %{ $::form };
413 die "Unroutable request -- invalid action name.\n" if !$action;
415 delete $::form->{$action};
416 $action = substr $action, 2;
419 delete @{$::form}{qw(M A)};
423 $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
424 show_error('generic/error');
427 return (controller => $script_name, action => $action);
430 sub _route_controller_request {
432 my ($controller, $action, $request_type);
435 # Redirect simple requests to controller.pl without any GET/POST
436 # param to the login page.
437 $self->redirect_to_login(error => 'action') if !$::form->{action};
439 # Show an error if the »action« parameter doesn't match the
440 # pattern »Controller/action«.
441 $::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";
442 ($controller, $action) = ($1, $2);
443 delete $::form->{action};
445 $request_type = $3 ? lc(substr($3, 1)) : 'html';
449 $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
450 show_error('generic/error');
453 return (controller => $controller, action => $action, request_type => $request_type);
456 sub _cache_file_modification_times {
459 return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
465 return unless $File::Find::name =~ m/\.(?:pm|f?pl|html|conf|conf\.default)$/;
466 $fcgi_file_cache{ $File::Find::name } = (stat $File::Find::name)[9];
469 my $cwd = POSIX::getcwd();
470 File::Find::find($wanted, map { "${cwd}/${_}" } qw(config bin SL templates/webpages));
471 map { my $name = "${cwd}/${_}"; $fcgi_file_cache{$name} = (stat $name)[9] } qw(admin.pl dispatcher.fpl);
474 sub _watch_for_changed_files {
477 return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
479 my $ok = all { (stat($_))[9] == $fcgi_file_cache{$_} } keys %fcgi_file_cache;
481 $::lxdebug->message(LXDebug::DEBUG1(), "Program modifications detected. Restarting.");
485 sub get_standard_filehandles {
488 return $self->{interface} =~ m/f(?:ast)cgi/i ? $self->{request}->GetHandles() : (\*STDIN, \*STDOUT, \*STDERR);
491 sub _check_for_old_config_files {
492 my @old_files = grep { -f "config/${_}" } qw(authentication.pl console.conf lx-erp.conf lx-erp-local.conf);
493 return unless @old_files;
495 $::form->{title} = $::locale->text('Old configuration files');
497 print $::form->parse_html_template('login_screen/old_configuration_files', { FILES => \@old_files });
502 sub _parse_number_with_unit {
505 return undef unless defined $number;
506 return $number unless $number =~ m{^ \s* (\d+) \s* ([kmg])b \s* $}xi;
508 my %factors = (K => 1024, M => 1024 * 1024, G => 1024 * 1024 * 1024);
510 return $1 * $factors{uc $2};
513 sub _memory_usage_is_too_high {
514 return undef unless $::lx_office_conf{system};
517 rss => _parse_number_with_unit($::lx_office_conf{system}->{memory_limit_rss}),
518 size => _parse_number_with_unit($::lx_office_conf{system}->{memory_limit_vsz}),
521 # $::lxdebug->dump(0, "limits", \%limits);
523 return undef unless $limits{rss} || $limits{vsz};
527 my $in = IO::File->new("/proc/$$/status", "r") or return undef;
531 $usage{lc $1} = _parse_number_with_unit($2) if m{^ vm(rss|size): \s* (\d+ \s* [kmg]b) \s* $}ix;
536 # $::lxdebug->dump(0, "usage", \%usage);
538 foreach my $type (keys %limits) {
539 next if !$limits{$type};
540 next if $limits{$type} >= ($usage{$type} // 0);
542 $::lxdebug->message(LXDebug::WARN(), "Exiting due to memory size limit reached for type '${type}': limit " . $limits{$type} . " bytes, usage " . $usage{$type} . " bytes");
555 die SL::Dispatcher->END_OF_REQUEST;