epic-s6ts
[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 use Carp;
11 use CGI qw( -no_xhtml);
12 use Config::Std;
13 use DateTime;
14 use Encode;
15 use English qw(-no_match_vars);
16 use FCGI;
17 use File::Basename;
18 use IO::File;
19 use List::MoreUtils qw(all);
20 use List::Util qw(first);
21 use POSIX qw(setlocale);
22 use SL::Auth;
23 use SL::Dispatcher::AuthHandler;
24 use SL::LXDebug;
25 use SL::LxOfficeConf;
26 use SL::Locale;
27 use SL::ClientJS;
28 use SL::Common;
29 use SL::Form;
30 use SL::Helper::DateTime;
31 use SL::InstanceConfiguration;
32 use SL::MoreCommon qw(uri_encode);
33 use SL::Template::Plugin::HTMLFixes;
34 use SL::User;
35
36 use Rose::Object::MakeMethods::Generic (
37   scalar => [ qw(restart_after_request) ],
38 );
39
40 # Trailing new line is added so that Perl will not add the line
41 # number 'die' was called in.
42 use constant END_OF_REQUEST => "END-OF-REQUEST\n";
43
44 my %fcgi_file_cache;
45
46 sub new {
47   my ($class, $interface) = @_;
48
49   my $self           = bless {}, $class;
50   $self->{interface} = lc($interface || 'cgi');
51   $self->{auth_handler} = SL::Dispatcher::AuthHandler->new;
52
53   # Initialize character type locale to be UTF-8 instead of C:
54   foreach my $locale (qw(de_DE.UTF-8 en_US.UTF-8)) {
55     last if setlocale('LC_CTYPE', $locale);
56   }
57
58   return $self;
59 }
60
61 sub interface_type {
62   my ($self) = @_;
63   return $self->{interface} eq 'cgi' ? 'CGI' : 'FastCGI';
64 }
65
66 sub is_admin_request {
67   my %params = @_;
68   return ($params{script} eq 'admin.pl') || (($params{routing_type} eq 'controller') && ($params{script_name} eq 'Admin'));
69 }
70
71 sub pre_request_checks {
72   my (%params) = @_;
73
74   _check_for_old_config_files();
75
76   if (!$::auth->session_tables_present && !is_admin_request(%params)) {
77     show_error('login_screen/auth_db_unreachable');
78   }
79
80   if ($::request->type !~ m/^ (?: html | js | json ) $/x) {
81     die $::locale->text("Invalid request type '#1'", $::request->type);
82   }
83 }
84
85 sub pre_request_initialization {
86   my ($self, %params) = @_;
87
88   $self->unrequire_bin_mozilla;
89
90   $::locale        = Locale->new($::lx_office_conf{system}->{language});
91   $::form          = Form->new;
92   $::instance_conf = SL::InstanceConfiguration->new;
93   $::request       = SL::Request->new(
94     cgi            => CGI->new({}),
95     layout         => SL::Layout::None->new,
96   );
97
98   my $session_result = $::auth->restore_session;
99   $::auth->create_or_refresh_session;
100
101   if ($params{client}) {
102     $::auth->set_client($params{client}) || die("cannot find client " . $params{client});
103
104     if ($params{login}) {
105       die "cannot find user " . $params{login}            unless %::myconfig = $::auth->read_user(login => $params{login});
106       die "cannot find locale for user " . $params{login} unless $::locale   = Locale->new($::myconfig{countrycode});
107
108       $::form->{login} = $params{login}; # normaly implicit at login
109     }
110   }
111
112   return $session_result;
113 }
114
115 sub render_error_ajax {
116   my ($error) = @_;
117
118   SL::ClientJS->new
119     ->error($error)
120     ->render(SL::Controller::Base->new);
121 }
122
123 sub show_error {
124   $::lxdebug->enter_sub;
125   my $template             = shift;
126   my $error_type           = shift || '';
127   my %params               = @_;
128
129   $::myconfig{countrycode} = delete($params{countrycode}) || $::lx_office_conf{system}->{language};
130   $::locale                = Locale->new($::myconfig{countrycode});
131   $::form->{error}         = $::locale->text('The session is invalid or has expired.') if ($error_type eq 'session');
132   $::form->{error}         = $::locale->text('Incorrect password!')                    if ($error_type eq 'password');
133   $::form->{error}         = $::locale->text('The action is missing or invalid.')      if ($error_type eq 'action');
134
135   return render_error_ajax($::form->{error}) if $::request->is_ajax;
136
137   $::form->header;
138   print $::form->parse_html_template($template, \%params);
139   $::lxdebug->leave_sub;
140
141   end_request();
142 }
143
144 sub pre_startup_setup {
145   my ($self) = @_;
146
147   SL::LxOfficeConf->read;
148
149   eval {
150     package main;
151     require "bin/mozilla/common.pl";
152     require "bin/mozilla/installationcheck.pl";
153   } or die $EVAL_ERROR;
154
155   # canonial globals. if it's not here, chances are it will get refactored someday.
156   {
157     no warnings 'once';
158     $::lxdebug     = LXDebug->new;
159     $::auth        = SL::Auth->new;
160     $::form        = undef;
161     $::request     = undef;
162     %::myconfig    = User->get_default_myconfig;
163   }
164
165   $SIG{__WARN__} = sub {
166     $::lxdebug->warn(@_);
167   };
168
169   $SIG{__DIE__} = sub { Carp::confess( @_ ) } if $::lx_office_conf{debug}->{backtrace_on_die};
170
171   $self->_cache_file_modification_times;
172 }
173
174 sub pre_startup_checks {
175   ::verify_installation();
176 }
177
178 sub pre_startup {
179   my ($self) = @_;
180   $self->pre_startup_setup;
181   $self->pre_startup_checks;
182 }
183
184 sub require_main_code {
185   $::lxdebug->enter_sub;
186   my ($script, $suffix) = @_;
187
188   eval {
189     package main;
190     require "bin/mozilla/$script$suffix";
191   } or die $EVAL_ERROR;
192
193   if (-f "bin/mozilla/custom_$script$suffix") {
194     eval {
195       package main;
196       require "bin/mozilla/custom_$script$suffix";
197     };
198     $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
199   }
200   if ($::form->{login} && -f "bin/mozilla/$::form->{login}_$script") {
201     eval {
202       package main;
203       require "bin/mozilla/$::form->{login}_$script";
204     };
205     $::form->error($EVAL_ERROR) if ($EVAL_ERROR);
206   }
207   $::lxdebug->leave_sub;
208 }
209
210 sub _require_controller {
211   my $controller =  shift;
212   $controller    =~ s|[^A-Za-z0-9_]||g;
213   $controller    =  "SL/Controller/${controller}";
214
215   eval {
216     package main;
217     require "${controller}.pm";
218   } or die $EVAL_ERROR;
219 }
220
221 sub _run_controller {
222   "SL::Controller::$_[0]"->new->_run_action($_[1]);
223 }
224
225 sub handle_all_requests {
226   my ($self) = @_;
227
228   my $request = FCGI::Request();
229   while ($request->Accept() >= 0) {
230     $self->handle_request($request);
231
232     $self->restart_after_request(1) if $self->_interface_is_fcgi && SL::System::Process::memory_usage_is_too_high();
233     $request->LastCall              if $self->restart_after_request;
234   }
235
236   exec $0 if $self->restart_after_request;
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   $::request->read_cgi_input($::form);
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->handle_login_error(routing_type => $routing_type,
293                                 script       => $script,
294                                 controller   => $script_name,
295                                 action       => $action,
296                                 error        => 'session');
297     }
298
299     my %auth_result = $self->{auth_handler}->handle(
300       routing_type => $routing_type,
301       script       => $script,
302       controller   => $script_name,
303       action       => $action,
304     );
305
306     $self->end_request unless $auth_result{auth_ok};
307
308     delete @{ $::form }{ grep { m/^\{AUTH\}/ } keys %{ $::form } } unless $auth_result{keep_auth_vars};
309
310     if ($action) {
311       $::form->set_standard_title;
312       if ($routing_type eq 'old') {
313         ::call_sub('::' . $::locale->findsub($action));
314       } else {
315         _run_controller($script_name, $action);
316       }
317     } else {
318       $::form->error($::locale->text('action= not defined!'));
319     }
320
321     1;
322   } or do {
323     if (substr($EVAL_ERROR, 0, length(END_OF_REQUEST())) ne END_OF_REQUEST()) {
324       my $error = $EVAL_ERROR;
325       print STDERR $error;
326
327       if ($::request->is_ajax) {
328         eval { render_error_ajax($error) };
329       } else {
330         $::form->{label_error} = $::request->{cgi}->pre($error);
331         chdir SL::System::Process::exe_dir;
332         eval { show_error('generic/error') };
333       }
334     }
335   };
336
337   $::form->footer;
338
339   if ($self->_interface_is_fcgi) {
340     # fcgi? send send reponse on its way before cleanup.
341     $self->{request}->Flush;
342     $self->{request}->Finish;
343   }
344
345   $::lxdebug->end_request(routing_type => $routing_type, script_name => $script_name, action => $action);
346
347   # cleanup
348   $::auth->save_session;
349   $::auth->expire_sessions;
350   $::auth->reset;
351
352   $::locale   = undef;
353   $::form     = undef;
354   %::myconfig = ();
355   $::request  = undef;
356
357   SL::DBConnect::Cache->reset_all;
358
359   $self->_watch_for_changed_files;
360
361   $::lxdebug->leave_sub;
362 }
363
364 sub reply_with_json_error {
365   my ($self, %params) = @_;
366
367   my %errors = (
368     session  => { code => '401 Unauthorized',          text => 'session expired' },
369     password => { code => '401 Unauthorized',          text => 'incorrect username or password' },
370     action   => { code => '400 Bad request',           text => 'incorrect or missing action' },
371     access   => { code => '403 Forbidden',             text => 'no permissions for accessing this function' },
372     _default => { code => '500 Internal server error', text => 'general server-side error' },
373   );
374
375   my $error = $errors{$params{error}} // $errors{_default};
376   my $reply = SL::JSON::to_json({ status => 'failed', error => $error->{text} });
377
378   print $::request->cgi->header(
379     -type    => 'application/json',
380     -charset => 'utf-8',
381     -status  => $error->{code},
382   );
383
384   print $reply;
385
386   $self->end_request;
387 }
388
389 sub handle_login_error {
390   my ($self, %params) = @_;
391
392   return $self->reply_with_json_error(error => $params{error}) if $::request->type eq 'json';
393
394   my $action          = ($params{script} // '') =~ m/^admin/i ? 'Admin/login' : 'LoginScreen/user_login';
395   $action            .= '&error=' . $params{error} if $params{error};
396
397   my $redirect_url = "controller.pl?action=${action}";
398
399   if (   $action =~ m/LoginScreen\/user_login/
400       && $params{action}
401       && 'get' eq lc($ENV{REQUEST_METHOD})
402       && !_is_callback_blacklisted(map {$_ => $params{$_}} qw(routing_type script controller action) )
403   ) {
404
405     require SL::Controller::Base;
406     my $controller = SL::Controller::Base->new;
407
408     delete $params{error};
409     delete $params{routing_type};
410     delete @{ $::form }{ grep { m/^\{AUTH\}/ } keys %{ $::form } };
411
412     my $callback   = $controller->url_for(%params, %{$::form});
413     $redirect_url .= '&callback=' . uri_encode($callback);
414   }
415
416   print $::request->cgi->redirect($redirect_url);
417   $self->end_request;
418 }
419
420 sub _is_callback_blacklisted {
421   my (%params) = @_;
422
423   # You can give a name only, then all actions are blackisted.
424   # Or you can give name and action, then only this action is blacklisted
425   # examples:
426   # {name => 'is',      action => 'edit'}
427   # {name => 'Project', action => 'edit'},
428   my @script_blacklist = (
429     {name => 'admin'},
430     {name => 'login'},
431   );
432
433   my @controller_blacklist = (
434     {name => 'Admin'},
435     {name => 'LoginScreen'},
436   );
437
438   my ($name, $blacklist);
439   if ('old' eq ($params{routing_type} // '')) {
440     $name      = $params{script};
441     $blacklist = \@script_blacklist;
442   } else {
443     $name      = $params{controller};
444     $blacklist = \@controller_blacklist;
445   }
446
447   foreach my $bl (@$blacklist) {
448     return 1 if _is_name_action_blacklisted($bl->{name}, $bl->{action}, $name, $params{action});
449   }
450
451   return;
452 }
453
454 sub _is_name_action_blacklisted {
455   my ($blacklisted_name, $blacklisted_action, $name, $action) = @_;
456
457   return 1 if ($name // '') eq $blacklisted_name && !$blacklisted_action;
458   return 1 if ($name // '') eq $blacklisted_name && ($action // '') eq $blacklisted_action;
459   return;
460 }
461
462 sub unrequire_bin_mozilla {
463   my $self = shift;
464   return unless $self->_interface_is_fcgi;
465
466   for (keys %INC) {
467     next unless m#^bin/mozilla/#;
468     next if /\bcommon.pl$/;
469     next if /\binstallationcheck.pl$/;
470     delete $INC{$_};
471   }
472 }
473
474 sub _interface_is_fcgi {
475   my $self = shift;
476   return $self->{interface} =~ m/^(?:fastcgi|fcgid|fcgi)$/;
477 }
478
479 sub _route_request {
480   my ($self, $script_name) = @_;
481
482   return $script_name =~ m/dispatcher\.pl$/ ? (type => 'old',        $self->_route_dispatcher_request)
483        : $script_name =~ m/controller\.pl/  ? (type => 'controller', $self->_route_controller_request)
484        :                                      (type => 'old',        controller => $script_name, action => $::form->{action});
485 }
486
487 sub _route_dispatcher_request {
488   my ($self)  = @_;
489   my $name_re = qr{[a-z]\w*};
490   my ($script_name, $action);
491
492   eval {
493     die "Unroutable request -- invalid module name.\n" if !$::form->{M} || ($::form->{M} !~ m/^${name_re}$/);
494     $script_name = $::form->{M} . '.pl';
495
496     if ($::form->{A}) {
497       $action = $::form->{A};
498
499     } else {
500       $action = first { m/^A_${name_re}$/ } keys %{ $::form };
501       die "Unroutable request -- invalid action name.\n" if !$action;
502
503       delete $::form->{$action};
504       $action = substr $action, 2;
505     }
506
507     delete @{$::form}{qw(M A)};
508
509     1;
510   } or do {
511     $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
512     show_error('generic/error');
513   };
514
515   return (controller => $script_name, action => $action);
516 }
517
518 sub _route_controller_request {
519   my ($self) = @_;
520   my ($controller, $action, $request_type);
521
522   eval {
523     # Redirect simple requests to controller.pl without any GET/POST
524     # param to the login page.
525     $self->handle_login_error(error => 'action') if !$::form->{action};
526
527     # Show an error if the »action« parameter doesn't match the
528     # pattern »Controller/action«.
529     $::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";
530     ($controller, $action) =  ($1, $2);
531     delete $::form->{action};
532
533     $request_type = $3 ? lc(substr($3, 1)) : 'html';
534
535     1;
536   } or do {
537     $::form->{label_error} = $::request->{cgi}->pre($EVAL_ERROR);
538     show_error('generic/error');
539   };
540
541   return (controller => $controller, action => $action, request_type => $request_type);
542 }
543
544 sub _cache_file_modification_times {
545   my ($self) = @_;
546
547   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
548
549   require File::Find;
550   require POSIX;
551
552   my $wanted = sub {
553     return unless $File::Find::name =~ m/\.(?:pm|f?pl|html|conf|conf\.default)$/;
554     $fcgi_file_cache{ $File::Find::name } = (stat $File::Find::name)[9];
555   };
556
557   my $cwd = POSIX::getcwd();
558   File::Find::find($wanted, map { "${cwd}/${_}" } qw(config bin SL templates/webpages));
559   map { my $name = "${cwd}/${_}"; $fcgi_file_cache{$name} = (stat $name)[9] } qw(admin.pl dispatcher.fpl);
560 }
561
562 sub _watch_for_changed_files {
563   my ($self) = @_;
564
565   return unless $self->_interface_is_fcgi && $::lx_office_conf{debug}->{restart_fcgi_process_on_changes};
566
567   my $ok = all { (stat($_))[9] == $fcgi_file_cache{$_} } keys %fcgi_file_cache;
568   return if $ok;
569   $::lxdebug->message(LXDebug::DEBUG1(), "Program modifications detected. Restarting.");
570   $self->restart_after_request(1);
571 }
572
573 sub get_standard_filehandles {
574   my $self = shift;
575
576   return $self->{interface} =~ m/f(?:ast)cgi/i ? $self->{request}->GetHandles() : (\*STDIN, \*STDOUT, \*STDERR);
577 }
578
579 sub _check_for_old_config_files {
580   my @old_files = grep { -f "config/${_}" } qw(authentication.pl console.conf lx-erp.conf lx-erp-local.conf);
581   return unless @old_files;
582
583   $::form->{title} = $::locale->text('Old configuration files');
584   $::form->header;
585   print $::form->parse_html_template('login_screen/old_configuration_files', { FILES => \@old_files });
586
587   end_request();
588 }
589
590 sub end_request {
591   die SL::Dispatcher->END_OF_REQUEST;
592 }
593
594 1;