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 use Rose::Object::MakeMethods::Generic (
45 scalar => [ qw(restart_after_request) ],
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";
55 my ($class, $interface) = @_;
57 my $self = bless {}, $class;
58 $self->{interface} = lc($interface || 'cgi');
59 $self->{auth_handler} = SL::Dispatcher::AuthHandler->new;
61 SL::ArchiveZipFixes->apply_fixes;
68 return $self->{interface} eq 'cgi' ? 'CGI' : 'FastCGI';
71 sub is_admin_request {
73 return ($params{script} eq 'admin.pl') || (($params{routing_type} eq 'controller') && ($params{script_name} eq 'Admin'));
76 sub pre_request_checks {
79 _check_for_old_config_files();
81 if (!$::auth->session_tables_present && !is_admin_request(%params)) {
82 show_error('login_screen/auth_db_unreachable');
85 if ($::request->type !~ m/^ (?: html | js | json ) $/x) {
86 die $::locale->text("Invalid request type '#1'", $::request->type);
90 sub pre_request_initialization {
91 my ($self, %params) = @_;
93 $self->unrequire_bin_mozilla;
95 $::locale = Locale->new($::lx_office_conf{system}->{language});
97 $::instance_conf = SL::InstanceConfiguration->new;
98 $::request = SL::Request->new(
100 layout => SL::Layout::None->new,
103 my $session_result = $::auth->restore_session;
104 $::auth->create_or_refresh_session;
106 if ($params{client}) {
107 $::auth->set_client($params{client}) || die("cannot find client " . $params{client});
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});
113 $::form->{login} = $params{login}; # normaly implicit at login
117 return $session_result;
120 sub render_error_ajax {
125 ->render(SL::Controller::Base->new);
129 $::lxdebug->enter_sub;
130 my $template = shift;
131 my $error_type = shift || '';
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');
140 return render_error_ajax($::form->{error}) if $::request->is_ajax;
143 print $::form->parse_html_template($template, \%params);
144 $::lxdebug->leave_sub;
149 sub pre_startup_setup {
152 SL::LxOfficeConf->read;
156 require "bin/mozilla/common.pl";
157 require "bin/mozilla/installationcheck.pl";
158 } or die $EVAL_ERROR;
160 # canonial globals. if it's not here, chances are it will get refactored someday.
163 $::lxdebug = LXDebug->new;
164 $::auth = SL::Auth->new;
167 %::myconfig = User->get_default_myconfig;
170 $SIG{__WARN__} = sub {
171 $::lxdebug->warn(@_);
174 $SIG{__DIE__} = sub { Carp::confess( @_ ) } if $::lx_office_conf{debug}->{backtrace_on_die};
176 $self->_cache_file_modification_times;
179 sub pre_startup_checks {
180 ::verify_installation();
185 $self->pre_startup_setup;
186 $self->pre_startup_checks;
189 sub require_main_code {
190 $::lxdebug->enter_sub;
191 my ($script, $suffix) = @_;
195 require "bin/mozilla/$script$suffix";
196 } or die $EVAL_ERROR;
198 if (-f "bin/mozilla/custom_$script$suffix") {
201 require "bin/mozilla/custom_$script$suffix";
203 $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
205 if ($::form->{login} && -f "bin/mozilla/$::form->{login}_$script") {
208 require "bin/mozilla/$::form->{login}_$script";
210 $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
212 $::lxdebug->leave_sub;
215 sub _require_controller {
216 my $controller = shift;
217 $controller =~ s|[^A-Za-z0-9_]||g;
218 $controller = "SL/Controller/${controller}";
222 require "${controller}.pm";
223 } or die $EVAL_ERROR;
226 sub _run_controller {
227 "SL::Controller::$_[0]"->new->_run_action($_[1]);
230 sub handle_all_requests {
233 my $request = FCGI::Request();
234 while ($request->Accept() >= 0) {
235 $self->handle_request($request);
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;
241 exec $0 if $self->restart_after_request;
246 $self->{request} = shift;
248 $::lxdebug->enter_sub;
249 $::lxdebug->begin_request;
251 my ($script, $path, $suffix, $script_name, $action, $routing_type);
253 my $session_result = $self->pre_request_initialization;
255 $::form->read_cgi_input;
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);
262 $::request->type(lc($routing{request_type} || 'html'));
264 if ($routing_type eq 'old') {
265 $::form->{action} = lc $::form->{action};
266 $::form->{action} =~ s/( |-|,|\#)/_/g;
268 ($script, $path, $suffix) = fileparse($script_name, ".pl");
269 require_main_code($script, $suffix) unless $script eq 'admin';
271 $::form->{script} = $script . $suffix;
274 _require_controller($script_name);
275 $::form->{script} = "controller.pl";
279 pre_request_checks(script => $script, action => $action, routing_type => $routing_type, script_name => $script_name);
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!'));
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');
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');
301 my %auth_result = $self->{auth_handler}->handle(
302 routing_type => $routing_type,
304 controller => $script_name,
308 $self->end_request unless $auth_result{auth_ok};
310 delete @{ $::form }{ grep { m/^\{AUTH\}/ } keys %{ $::form } } unless $auth_result{keep_auth_vars};
313 $::form->set_standard_title;
314 if ($routing_type eq 'old') {
315 ::call_sub('::' . $::locale->findsub($action));
317 _run_controller($script_name, $action);
320 $::form->error($::locale->text('action= not defined!'));
325 if (substr($EVAL_ERROR, 0, length(END_OF_REQUEST())) ne END_OF_REQUEST()) {
326 my $error = $EVAL_ERROR;
329 if ($::request->is_ajax) {
330 eval { render_error_ajax($error) };
332 $::form->{label_error} = $::request->{cgi}->pre($error);
333 chdir SL::System::Process::exe_dir;
334 eval { show_error('generic/error') };
341 if ($self->_interface_is_fcgi) {
342 # fcgi? send send reponse on its way before cleanup.
343 $self->{request}->Flush;
344 $self->{request}->Finish;
347 $::lxdebug->end_request(routing_type => $routing_type, script_name => $script_name, action => $action);
350 $::auth->save_session;
351 $::auth->expire_sessions;
359 SL::DBConnect::Cache->reset_all;
360 Form::disconnect_standard_dbh;
362 $self->_watch_for_changed_files;
364 $::lxdebug->leave_sub;
367 sub redirect_to_login {
368 my ($self, %params) = @_;
369 my $action = ($params{script} // '') =~ m/^admin/i ? 'Admin/login' : 'LoginScreen/user_login';
370 $action .= '&error=' . $params{error} if $params{error};
372 print $::request->cgi->redirect("controller.pl?action=${action}");
376 sub unrequire_bin_mozilla {
378 return unless $self->_interface_is_fcgi;
381 next unless m#^bin/mozilla/#;
382 next if /\bcommon.pl$/;
383 next if /\binstallationcheck.pl$/;
388 sub _interface_is_fcgi {
390 return $self->{interface} =~ m/^(?:fastcgi|fcgid|fcgi)$/;
394 my ($self, $script_name) = @_;
396 return $script_name =~ m/dispatcher\.pl$/ ? (type => 'old', $self->_route_dispatcher_request)
397 : $script_name =~ m/controller\.pl/ ? (type => 'controller', $self->_route_controller_request)
398 : (type => 'old', controller => $script_name, action => $::form->{action});
401 sub _route_dispatcher_request {
403 my $name_re = qr{[a-z]\w*};
404 my ($script_name, $action);
407 die "Unroutable request -- invalid module name.\n" if !$::form->{M} || ($::form->{M} !~ m/^${name_re}$/);
408 $script_name = $::form->{M} . '.pl';
411 $action = $::form->{A};
414 $action = first { m/^A_${name_re}$/ } keys %{ $::form };
415 die "Unroutable request -- invalid action name.\n" if !$action;
417 delete $::form->{$action};
418 $action = substr $action, 2;
421 delete @{$::form}{qw(M A)};
425 $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
426 show_error('generic/error');
429 return (controller => $script_name, action => $action);
432 sub _route_controller_request {
434 my ($controller, $action, $request_type);
437 # Redirect simple requests to controller.pl without any GET/POST
438 # param to the login page.
439 $self->redirect_to_login(error => 'action') if !$::form->{action};
441 # Show an error if the »action« parameter doesn't match the
442 # pattern »Controller/action«.
443 $::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";
444 ($controller, $action) = ($1, $2);
445 delete $::form->{action};
447 $request_type = $3 ? lc(substr($3, 1)) : 'html';
451 $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
452 show_error('generic/error');
455 return (controller => $controller, action => $action, request_type => $request_type);
458 sub _cache_file_modification_times {
461 return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
467 return unless $File::Find::name =~ m/\.(?:pm|f?pl|html|conf|conf\.default)$/;
468 $fcgi_file_cache{ $File::Find::name } = (stat $File::Find::name)[9];
471 my $cwd = POSIX::getcwd();
472 File::Find::find($wanted, map { "${cwd}/${_}" } qw(config bin SL templates/webpages));
473 map { my $name = "${cwd}/${_}"; $fcgi_file_cache{$name} = (stat $name)[9] } qw(admin.pl dispatcher.fpl);
476 sub _watch_for_changed_files {
479 return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
481 my $ok = all { (stat($_))[9] == $fcgi_file_cache{$_} } keys %fcgi_file_cache;
483 $::lxdebug->message(LXDebug::DEBUG1(), "Program modifications detected. Restarting.");
484 $self->restart_after_request(1);
487 sub get_standard_filehandles {
490 return $self->{interface} =~ m/f(?:ast)cgi/i ? $self->{request}->GetHandles() : (\*STDIN, \*STDOUT, \*STDERR);
493 sub _check_for_old_config_files {
494 my @old_files = grep { -f "config/${_}" } qw(authentication.pl console.conf lx-erp.conf lx-erp-local.conf);
495 return unless @old_files;
497 $::form->{title} = $::locale->text('Old configuration files');
499 print $::form->parse_html_template('login_screen/old_configuration_files', { FILES => \@old_files });
504 sub _parse_number_with_unit {
507 return undef unless defined $number;
508 return $number unless $number =~ m{^ \s* (\d+) \s* ([kmg])b \s* $}xi;
510 my %factors = (K => 1024, M => 1024 * 1024, G => 1024 * 1024 * 1024);
512 return $1 * $factors{uc $2};
515 sub _memory_usage_is_too_high {
516 return undef unless $::lx_office_conf{system};
519 rss => _parse_number_with_unit($::lx_office_conf{system}->{memory_limit_rss}),
520 size => _parse_number_with_unit($::lx_office_conf{system}->{memory_limit_vsz}),
523 # $::lxdebug->dump(0, "limits", \%limits);
525 return undef unless $limits{rss} || $limits{vsz};
529 my $in = IO::File->new("/proc/$$/status", "r") or return undef;
533 $usage{lc $1} = _parse_number_with_unit($2) if m{^ vm(rss|size): \s* (\d+ \s* [kmg]b) \s* $}ix;
538 # $::lxdebug->dump(0, "usage", \%usage);
540 foreach my $type (keys %limits) {
541 next if !$limits{$type};
542 next if $limits{$type} >= ($usage{$type} // 0);
544 $::lxdebug->message(LXDebug::WARN(), "Exiting due to memory size limit reached for type '${type}': limit " . $limits{$type} . " bytes, usage " . $usage{$type} . " bytes");
553 die SL::Dispatcher->END_OF_REQUEST;