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 POSIX qw(setlocale);
22 use SL::ArchiveZipFixes;
24 use SL::Dispatcher::AuthHandler;
31 use SL::Helper::DateTime;
32 use SL::InstanceConfiguration;
33 use SL::MoreCommon qw(uri_encode);
34 use SL::Template::Plugin::HTMLFixes;
37 use Rose::Object::MakeMethods::Generic (
38 scalar => [ qw(restart_after_request) ],
41 # Trailing new line is added so that Perl will not add the line
42 # number 'die' was called in.
43 use constant END_OF_REQUEST => "END-OF-REQUEST\n";
48 my ($class, $interface) = @_;
50 my $self = bless {}, $class;
51 $self->{interface} = lc($interface || 'cgi');
52 $self->{auth_handler} = SL::Dispatcher::AuthHandler->new;
54 SL::ArchiveZipFixes->apply_fixes;
56 # Initialize character type locale to be UTF-8 instead of C:
57 foreach my $locale (qw(de_DE.UTF-8 en_US.UTF-8)) {
58 last if setlocale('LC_CTYPE', $locale);
66 return $self->{interface} eq 'cgi' ? 'CGI' : 'FastCGI';
69 sub is_admin_request {
71 return ($params{script} eq 'admin.pl') || (($params{routing_type} eq 'controller') && ($params{script_name} eq 'Admin'));
74 sub pre_request_checks {
77 _check_for_old_config_files();
79 if (!$::auth->session_tables_present && !is_admin_request(%params)) {
80 show_error('login_screen/auth_db_unreachable');
83 if ($::request->type !~ m/^ (?: html | js | json ) $/x) {
84 die $::locale->text("Invalid request type '#1'", $::request->type);
88 sub pre_request_initialization {
89 my ($self, %params) = @_;
91 $self->unrequire_bin_mozilla;
93 $::locale = Locale->new($::lx_office_conf{system}->{language});
95 $::instance_conf = SL::InstanceConfiguration->new;
96 $::request = SL::Request->new(
98 layout => SL::Layout::None->new,
101 my $session_result = $::auth->restore_session;
102 $::auth->create_or_refresh_session;
104 if ($params{client}) {
105 $::auth->set_client($params{client}) || die("cannot find client " . $params{client});
107 if ($params{login}) {
108 die "cannot find user " . $params{login} unless %::myconfig = $::auth->read_user(login => $params{login});
109 die "cannot find locale for user " . $params{login} unless $::locale = Locale->new($::myconfig{countrycode});
111 $::form->{login} = $params{login}; # normaly implicit at login
115 return $session_result;
118 sub render_error_ajax {
123 ->render(SL::Controller::Base->new);
127 $::lxdebug->enter_sub;
128 my $template = shift;
129 my $error_type = shift || '';
132 $::myconfig{countrycode} = delete($params{countrycode}) || $::lx_office_conf{system}->{language};
133 $::locale = Locale->new($::myconfig{countrycode});
134 $::form->{error} = $::locale->text('The session is invalid or has expired.') if ($error_type eq 'session');
135 $::form->{error} = $::locale->text('Incorrect password!') if ($error_type eq 'password');
136 $::form->{error} = $::locale->text('The action is missing or invalid.') if ($error_type eq 'action');
138 return render_error_ajax($::form->{error}) if $::request->is_ajax;
141 print $::form->parse_html_template($template, \%params);
142 $::lxdebug->leave_sub;
147 sub pre_startup_setup {
150 SL::LxOfficeConf->read;
154 require "bin/mozilla/common.pl";
155 require "bin/mozilla/installationcheck.pl";
156 } or die $EVAL_ERROR;
158 # canonial globals. if it's not here, chances are it will get refactored someday.
161 $::lxdebug = LXDebug->new;
162 $::auth = SL::Auth->new;
165 %::myconfig = User->get_default_myconfig;
168 $SIG{__WARN__} = sub {
169 $::lxdebug->warn(@_);
172 $SIG{__DIE__} = sub { Carp::confess( @_ ) } if $::lx_office_conf{debug}->{backtrace_on_die};
174 $self->_cache_file_modification_times;
177 sub pre_startup_checks {
178 ::verify_installation();
183 $self->pre_startup_setup;
184 $self->pre_startup_checks;
187 sub require_main_code {
188 $::lxdebug->enter_sub;
189 my ($script, $suffix) = @_;
193 require "bin/mozilla/$script$suffix";
194 } or die $EVAL_ERROR;
196 if (-f "bin/mozilla/custom_$script$suffix") {
199 require "bin/mozilla/custom_$script$suffix";
201 $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
203 if ($::form->{login} && -f "bin/mozilla/$::form->{login}_$script") {
206 require "bin/mozilla/$::form->{login}_$script";
208 $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
210 $::lxdebug->leave_sub;
213 sub _require_controller {
214 my $controller = shift;
215 $controller =~ s|[^A-Za-z0-9_]||g;
216 $controller = "SL/Controller/${controller}";
220 require "${controller}.pm";
221 } or die $EVAL_ERROR;
224 sub _run_controller {
225 "SL::Controller::$_[0]"->new->_run_action($_[1]);
228 sub handle_all_requests {
231 my $request = FCGI::Request();
232 while ($request->Accept() >= 0) {
233 $self->handle_request($request);
235 $self->restart_after_request(1) if $self->_interface_is_fcgi && SL::System::Process::memory_usage_is_too_high();
236 $request->LastCall if $self->restart_after_request;
239 exec $0 if $self->restart_after_request;
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->handle_login_error(routing_type => $routing_type,
297 controller => $script_name,
302 my %auth_result = $self->{auth_handler}->handle(
303 routing_type => $routing_type,
305 controller => $script_name,
309 $self->end_request unless $auth_result{auth_ok};
311 delete @{ $::form }{ grep { m/^\{AUTH\}/ } keys %{ $::form } } unless $auth_result{keep_auth_vars};
314 $::form->set_standard_title;
315 if ($routing_type eq 'old') {
316 ::call_sub('::' . $::locale->findsub($action));
318 _run_controller($script_name, $action);
321 $::form->error($::locale->text('action= not defined!'));
326 if (substr($EVAL_ERROR, 0, length(END_OF_REQUEST())) ne END_OF_REQUEST()) {
327 my $error = $EVAL_ERROR;
330 if ($::request->is_ajax) {
331 eval { render_error_ajax($error) };
333 $::form->{label_error} = $::request->{cgi}->pre($error);
334 chdir SL::System::Process::exe_dir;
335 eval { show_error('generic/error') };
342 if ($self->_interface_is_fcgi) {
343 # fcgi? send send reponse on its way before cleanup.
344 $self->{request}->Flush;
345 $self->{request}->Finish;
348 $::lxdebug->end_request(routing_type => $routing_type, script_name => $script_name, action => $action);
351 $::auth->save_session;
352 $::auth->expire_sessions;
360 SL::DBConnect::Cache->reset_all;
362 $self->_watch_for_changed_files;
364 $::lxdebug->leave_sub;
367 sub reply_with_json_error {
368 my ($self, %params) = @_;
371 session => { code => '401 Unauthorized', text => 'session expired' },
372 password => { code => '401 Unauthorized', text => 'incorrect username or password' },
373 action => { code => '400 Bad request', text => 'incorrect or missing action' },
374 access => { code => '403 Forbidden', text => 'no permissions for accessing this function' },
375 _default => { code => '500 Internal server error', text => 'general server-side error' },
378 my $error = $errors{$params{error}} // $errors{_default};
379 my $reply = SL::JSON::to_json({ status => 'failed', error => $error->{text} });
381 print $::request->cgi->header(
382 -type => 'application/json',
384 -status => $error->{code},
392 sub handle_login_error {
393 my ($self, %params) = @_;
395 return $self->reply_with_json_error(error => $params{error}) if $::request->type eq 'json';
397 my $action = ($params{script} // '') =~ m/^admin/i ? 'Admin/login' : 'LoginScreen/user_login';
398 $action .= '&error=' . $params{error} if $params{error};
400 my $redirect_url = "controller.pl?action=${action}";
402 if ( $action =~ m/LoginScreen\/user_login/
404 && 'get' eq lc($ENV{REQUEST_METHOD})
405 && !_is_callback_blacklisted(map {$_ => $params{$_}} qw(routing_type script controller action) )
408 require SL::Controller::Base;
409 my $controller = SL::Controller::Base->new;
411 delete $params{error};
412 delete $params{routing_type};
413 delete @{ $::form }{ grep { m/^\{AUTH\}/ } keys %{ $::form } };
415 my $callback = $controller->url_for(%params, %{$::form});
416 $redirect_url .= '&callback=' . uri_encode($callback);
419 print $::request->cgi->redirect($redirect_url);
423 sub _is_callback_blacklisted {
426 # You can give a name only, then all actions are blackisted.
427 # Or you can give name and action, then only this action is blacklisted
429 # {name => 'is', action => 'edit'}
430 # {name => 'Project', action => 'edit'},
431 my @script_blacklist = (
436 my @controller_blacklist = (
438 {name => 'LoginScreen'},
441 my ($name, $blacklist);
442 if ('old' eq ($params{routing_type} // '')) {
443 $name = $params{script};
444 $blacklist = \@script_blacklist;
446 $name = $params{controller};
447 $blacklist = \@controller_blacklist;
450 foreach my $bl (@$blacklist) {
451 return 1 if _is_name_action_blacklisted($bl->{name}, $bl->{action}, $name, $params{action});
457 sub _is_name_action_blacklisted {
458 my ($blacklisted_name, $blacklisted_action, $name, $action) = @_;
460 return 1 if ($name // '') eq $blacklisted_name && !$blacklisted_action;
461 return 1 if ($name // '') eq $blacklisted_name && ($action // '') eq $blacklisted_action;
465 sub unrequire_bin_mozilla {
467 return unless $self->_interface_is_fcgi;
470 next unless m#^bin/mozilla/#;
471 next if /\bcommon.pl$/;
472 next if /\binstallationcheck.pl$/;
477 sub _interface_is_fcgi {
479 return $self->{interface} =~ m/^(?:fastcgi|fcgid|fcgi)$/;
483 my ($self, $script_name) = @_;
485 return $script_name =~ m/dispatcher\.pl$/ ? (type => 'old', $self->_route_dispatcher_request)
486 : $script_name =~ m/controller\.pl/ ? (type => 'controller', $self->_route_controller_request)
487 : (type => 'old', controller => $script_name, action => $::form->{action});
490 sub _route_dispatcher_request {
492 my $name_re = qr{[a-z]\w*};
493 my ($script_name, $action);
496 die "Unroutable request -- invalid module name.\n" if !$::form->{M} || ($::form->{M} !~ m/^${name_re}$/);
497 $script_name = $::form->{M} . '.pl';
500 $action = $::form->{A};
503 $action = first { m/^A_${name_re}$/ } keys %{ $::form };
504 die "Unroutable request -- invalid action name.\n" if !$action;
506 delete $::form->{$action};
507 $action = substr $action, 2;
510 delete @{$::form}{qw(M A)};
514 $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
515 show_error('generic/error');
518 return (controller => $script_name, action => $action);
521 sub _route_controller_request {
523 my ($controller, $action, $request_type);
526 # Redirect simple requests to controller.pl without any GET/POST
527 # param to the login page.
528 $self->handle_login_error(error => 'action') if !$::form->{action};
530 # Show an error if the »action« parameter doesn't match the
531 # pattern »Controller/action«.
532 $::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";
533 ($controller, $action) = ($1, $2);
534 delete $::form->{action};
536 $request_type = $3 ? lc(substr($3, 1)) : 'html';
540 $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
541 show_error('generic/error');
544 return (controller => $controller, action => $action, request_type => $request_type);
547 sub _cache_file_modification_times {
550 return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
556 return unless $File::Find::name =~ m/\.(?:pm|f?pl|html|conf|conf\.default)$/;
557 $fcgi_file_cache{ $File::Find::name } = (stat $File::Find::name)[9];
560 my $cwd = POSIX::getcwd();
561 File::Find::find($wanted, map { "${cwd}/${_}" } qw(config bin SL templates/webpages));
562 map { my $name = "${cwd}/${_}"; $fcgi_file_cache{$name} = (stat $name)[9] } qw(admin.pl dispatcher.fpl);
565 sub _watch_for_changed_files {
568 return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
570 my $ok = all { (stat($_))[9] == $fcgi_file_cache{$_} } keys %fcgi_file_cache;
572 $::lxdebug->message(LXDebug::DEBUG1(), "Program modifications detected. Restarting.");
573 $self->restart_after_request(1);
576 sub get_standard_filehandles {
579 return $self->{interface} =~ m/f(?:ast)cgi/i ? $self->{request}->GetHandles() : (\*STDIN, \*STDOUT, \*STDERR);
582 sub _check_for_old_config_files {
583 my @old_files = grep { -f "config/${_}" } qw(authentication.pl console.conf lx-erp.conf lx-erp-local.conf);
584 return unless @old_files;
586 $::form->{title} = $::locale->text('Old configuration files');
588 print $::form->parse_html_template('login_screen/old_configuration_files', { FILES => \@old_files });
594 die SL::Dispatcher->END_OF_REQUEST;