This commit was generated by cvs2svn to compensate for changes in r11022,
[freeside.git] / rt / bin / standalone_httpd.in
index bf44945..8c8c1ae 100755 (executable)
@@ -1,39 +1,41 @@
 #!@PERL@ -w
-# {{{ BEGIN BPS TAGGED BLOCK
-# 
+# BEGIN BPS TAGGED BLOCK {{{
+#
 # COPYRIGHT:
-#  
-# This software is Copyright (c) 1996-2004 Best Practical Solutions, LLC 
-#                                          <jesse@bestpractical.com>
-# 
+#
+# This software is Copyright (c) 1996-2011 Best Practical Solutions, LLC
+#                                          <sales@bestpractical.com>
+#
 # (Except where explicitly superseded by other copyright notices)
-# 
-# 
+#
+#
 # LICENSE:
-# 
+#
 # This work is made available to you under the terms of Version 2 of
 # the GNU General Public License. A copy of that license should have
 # been provided with this software, but in any event can be snarfed
 # from www.gnu.org.
-# 
+#
 # This work is distributed in the hope that it will be useful, but
 # WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 # General Public License for more details.
-# 
+#
 # You should have received a copy of the GNU General Public License
 # along with this program; if not, write to the Free Software
-# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-# 
-# 
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301 or visit their web page on the internet at
+# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
+#
+#
 # CONTRIBUTION SUBMISSION POLICY:
-# 
+#
 # (The following paragraph is not intended to limit the rights granted
 # to you to modify and distribute this software under the terms of
 # the GNU General Public License and is only of importance to you if
 # you choose to contribute your changes and enhancements to the
 # community by submitting them to Best Practical Solutions, LLC.)
-# 
+#
 # By intentionally submitting any modifications, corrections or
 # derivatives to this work, or any other work intended for use with
 # Request Tracker, to Best Practical Solutions, LLC, you confirm that
 # royalty-free, perpetual, license to use, copy, create derivative
 # works based on those contributions, and sublicense and distribute
 # those contributions and any derivatives thereof.
-# 
-# }}} END BPS TAGGED BLOCK
-package RT::Mason;
-
+#
+# END BPS TAGGED BLOCK }}}
+use warnings;
 use strict;
-use vars '$Handler';
-
-require ('@RT_BIN_PATH@/webmux.pl');
 
-use lib( "@LOCAL_LIB_PATH@", "@RT_LIB_PATH@");
+# fix lib paths, some may be relative
+BEGIN {
+    require File::Spec;
+    my @libs = ("@RT_LIB_PATH@", "@LOCAL_LIB_PATH@");
+    my $bin_path;
+
+    for my $lib (@libs) {
+        unless ( File::Spec->file_name_is_absolute($lib) ) {
+            unless ($bin_path) {
+                if ( File::Spec->file_name_is_absolute(__FILE__) ) {
+                    $bin_path = ( File::Spec->splitpath(__FILE__) )[1];
+                }
+                else {
+                    require FindBin;
+                    no warnings "once";
+                    $bin_path = $FindBin::Bin;
+                }
+            }
+            $lib = File::Spec->catfile( $bin_path, File::Spec->updir, $lib );
+        }
+        unshift @INC, $lib;
+    }
 
-use Socket;
+}
 
-RT::Init();
+use RT;
+RT::LoadConfig();
+RT->InitLogging();
+if (RT->Config->Get('DevelMode')) { require Module::Refresh; }
 
-my $port = shift || '8080';
+RT::CheckPerlRequirements();
+RT->InitPluginPaths();
 
-main_loop($port);
+my $explicit_port = shift @ARGV;
+my $port = $explicit_port || RT->Config->Get('WebPort') || '8080';
 
-sub main_loop {
-    my $port = shift;
-    my $tcp  = getprotobyname('tcp');
 
-    socket( HTTPDaemon, PF_INET, SOCK_STREAM, $tcp ) or die "socket: $!";
-    setsockopt( HTTPDaemon, SOL_SOCKET, SO_REUSEADDR, pack( "l", 1 ) )
-      or warn "setsockopt: $!";
-    bind( HTTPDaemon, sockaddr_in( $port, INADDR_ANY ) ) or die "bind: $!";
-    listen( HTTPDaemon, SOMAXCONN ) or die "listen: $!";
+require RT::Handle;
+my ($integrity, $state, $msg) = RT::Handle->CheckIntegrity;
 
-    print("You can connect to your RT server at http://localhost:$port/\n");
+unless ( $integrity ) {
+    print STDERR <<EOF;
+    
+RT couldn't connect to the database where tickets are stored.
+If this is a new installation of RT, you should visit the URL below
+to configure RT and initialize your database.
 
-    while (1) {
+If this is an existing RT installation, this may indicate a database
+connectivity problem.
 
-        for ( ; accept( Remote, HTTPDaemon ); close Remote ) {
+The error RT got back when trying to connect to your database was:
 
-            *STDIN  = *Remote;
-            *STDOUT = *Remote;
+$msg
 
-            my $remote_sockaddr = getpeername(STDIN);
-            my ( undef, $iaddr ) = sockaddr_in($remote_sockaddr);
-            my $peername = gethostbyaddr( $iaddr, AF_INET ) || "localhost";
-            my $peeraddr = inet_ntoa($iaddr) || "127.0.0.1";
+EOF
 
-            my $local_sockaddr = getsockname(STDIN);
-            my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr);
-            my $localname = gethostbyaddr( $localiaddr, AF_INET )
-              || "localhost";
-            my $localaddr = inet_ntoa($localiaddr) || "127.0.0.1";
+    require RT::Installer;
+    # don't enter install mode if the file exists but is unwritable
+    if (-e RT::Installer->ConfigFile && !-w _) {
+        die 'Since your configuration exists ('
+          . RT::Installer->ConfigFile
+          . ") but is not writable, I'm refusing to do anything.\n";
+    }
 
-            chomp( $_ = <STDIN> );
-            my ( $method, $request_uri, $proto, undef ) = split;
+    RT->Config->Set( 'LexiconLanguages' => '*' );
+    RT::I18N->Init;
+
+    RT->InstallMode(1);
+} else {
+    RT->ConnectToDatabase();
+    RT->InitSystemObjects();
+    RT->InitClasses( Heavy => 1 );
+    RT->InitPlugins();
+    RT->Config->PostLoadCheck();
+
+    my ($status, $msg) = RT::Handle->CheckCompatibility(
+        $RT::Handle->dbh, 'post'
+    );
+    unless ( $status ) {
+        print STDERR $msg, "\n\n";
+        exit -1;
+    }
+}
 
-            #$request_uri =~ s#\\#/#g;
-            $RT::Logger->info("<- $peername: $_");
-            my ( $file, undef, $query_string ) =
-              ( $request_uri =~ /([^?]*)(\?(.*))?/ );    # split at ?
-            #$file =~ s/%([\dA-Fa-f]{2})/chr(hex($1))/eg;  # decode url-escaped entities
+require RT::Interface::Web::Standalone;
+my $server = RT::Interface::Web::Standalone->new;
+run_server($port);
+exit 0;
 
-            last if ( $method !~ /^(GET|POST|HEAD)$/ );
+sub run_server {
+    my $port = shift;
+    $server->port($port);
+    eval { $server->run() };
 
-            build_cgi_env( method       => $method,
-                           query_string => $query_string,
-                           path         => $file,
-                           method       => $method,
-                           port         => $port,
-                           peername     => $peername,
-                           peeraddr     => $peeraddr,
-                           localname    => $localname,
-                           request_uri  => $request_uri );
+    if ( my $err = $@ ) {
+        handle_startup_error($err);
+    }
+}
 
-            RT::ConnectToDatabase();
-            my $cgi = CGI->new();
+sub handle_startup_error {
+    my $err = shift;
+    if ( $err =~ /bind: Permission denied/ ) {
+        handle_bind_error();
+    } else {
+        die
+            "Something went wrong while trying to run RT's standalone web server:\n\t"
+            . $err;
+    }
+}
 
-            print "HTTP/1.0 200 OK\n";    # probably OK by now
 
-            if ( ( !$Handler->interp->comp_exists( $cgi->path_info ) )
-                && ($Handler->interp->comp_exists( $cgi->path_info . "/index.html" ) )
-              ) {
-                $cgi->path_info( $cgi->path_info . "/index.html" );
-            }
+sub handle_bind_error {
 
-            eval { $Handler->handle_cgi_object($cgi); };
-            $RT::Logger->crit($@) if ($@);
+    print STDERR <<EOF;
+WARNING: RT couldn't start up a web server on port @{[$port]}.
+This is often the case if you're running @{[$0]} as 
+someone other than your system's "root" user.  
+EOF
 
-            if ( $RT::Handle->TransactionDepth ) {
-                $RT::Handle->ForceRollback;
-                $RT::Logger->crit( "Transaction not committed. Usually indicates a software fault. Data loss may have occurred");
-            }
+    if ($explicit_port) {
+        print STDERR
+            "Please check your system configuration or choose another port\n\n";
+    } else {
+        print STDERR "\nFor now, RT has chosen an alternate port to run on.\n\n";
+        if ( !$integrity ) {
+            print STDERR <<EOF;
+You can use this server to configure and explore RT.  While configuring
+RT, you'll have a chance to set a permanent port and URL for your
+server.
 
+EOF
         }
-
+        run_server( 8000 + int( rand(1024) ) );
     }
-
 }
-
-
-
-sub build_cgi_env {
-        my %args = ( query_string => '',
-                     path => '',
-                     port => undef,
-                     protocol => undef,
-                     localname => undef,
-                     method => undef,
-                     remote_name => undef,
-
-                        @_);
-                    
-        foreach my $var qw(USER_AGENT CONTENT_LENGTH CONTENT_TYPE
-          COOKIE SERVER_PORT SERVER_PROTOCOL SERVER_NAME
-          PATH_INFO REQUEST_URI REQUEST_METHOD REMOTE_ADDR
-          REMOTE_HOST QUERY_STRING SERVER_SOFTWARE) {
-            delete $ENV{$var};
-          }
-        while (<STDIN>) {
-            s/[\r\l\n\s]+$//;
-            if( /^([\w\-]+): (.+)/i) {
-                my $tag = uc($1);
-                $tag =~ s/^COOKIES$/COOKIE/;
-                my $val = $2;
-                $tag =~ s/-/_/g;
-                $tag = "HTTP_".$tag unless (grep /^$tag$/, qw(CONTENT_LENGTH CONTENT_TYPE COOKIE));
-                if ($ENV{$tag}) {
-                $ENV{$tag} .= "; $val";
-                }
-                else {
-                $ENV{$tag} = $val;
-                }
-            } 
-            last if (/^$/);
-        }
-
-
-        $ENV{SERVER_PROTOCOL} = $args{protocol};
-        $ENV{SERVER_PORT}     = $args{port};
-        $ENV{SERVER_NAME}     = $args{'localname'};
-        $ENV{SERVER_URL}      = "http://".$args{'localname'}.":".$args{'port'}."/";
-        $ENV{PATH_INFO}       = $args{'path'};
-        $ENV{REQUEST_URI}     = $args{'request_uri'};
-        $ENV{REQUEST_METHOD}  = $args{method};
-        $ENV{REMOTE_ADDR}     = $args{'peeraddr'};
-        $ENV{REMOTE_HOST}     = $args{'peername'};
-        $ENV{QUERY_STRING}    = $args{'query_string'};
-        $ENV{SERVER_SOFTWARE} = "rt-standalone/$RT::VERSION";
-
-        CGI::initialize_globals();
-}