Apache2-API

 view release on metacpan or  search on metacpan

lib/Apache2/API/Request.pm  view on Meta::CPAN

sub server_software { return( shift->env( 'SERVER_SOFTWARE', @_ ) ); }

# Or maybe the environment variable SERVER_SOFTWARE, e.g. Apache/2.4.18
# sub server_version { return( version->parse( Apache2::ServerUtil::get_server_version ) ); }
sub server_version
{
    my $self = shift( @_ );
    $self->{_server_version} = $SERVER_VERSION if( !CORE::length( $self->{_server_version} ) && CORE::length( $SERVER_VERSION ) );
    $self->{_server_version} = shift( @_ ) if( @_ );
    return( $self->{_server_version} ) if( $self->{_server_version} );
    my $vers = '';
    if( $self->mod_perl )
    {
        # try-catch
        local $@;
        eval
        {
            my $desc = Apache2::ServerUtil::get_server_description();
            if( $desc =~ /\bApache\/([\d\.]+)/ )
            {
                $vers = $1;
            }
        };
        if( $@ )
        {
        }
    }
    
    # NOTE: to test our alternative approach
    if( !$vers && ( my $apxs = File::Which::which( 'apxs' ) ) )
    {
        $vers = qx( $apxs -q -v HTTPD_VERSION );
        chomp( $vers );
        $vers = '' unless( $vers =~ /^[\d\.]+$/ );
    }
    # Try apache2
    if( !$vers )
    {
        foreach my $bin ( qw( apache2 httpd ) )
        {
            if( ( my $apache2 = File::Which::which( $bin ) ) )
            {
                my $v_str = qx( $apache2 -v );
                if( ( split( /\r?\n/, $v_str ) )[0] =~ /\bApache\/([\d\.]+)/ )
                {
                    $vers = $1;
                    chomp( $vers );
                    last;
                }
            }
        }
    }
    if( $vers )
    {
        $self->{_server_version} = $SERVER_VERSION = version->parse( $vers );
        return( $self->{_server_version} );
    }
    return( '' );
}

# e.g. set_basic_credentials( $user, $password );
sub set_basic_credentials { return( shift->_try( 'request', 'set_basic_credentials', @_ ) ); }

# set_handlers( PerlCleanupHandler => [] );
# $ok = $r->set_handlers($hook_name => \&handler);
# $ok = $r->set_handlers($hook_name => ['Foo::Bar::handler', \&handler2]);
# $ok = $r->set_handlers($hook_name => []);
# $ok = $r->set_handlers($hook_name => undef);
# https://perl.apache.org/docs/2.0/api/Apache2/RequestUtil.html#C_set_handlers_
sub set_handlers { return( shift->_try( 'request', 'set_handlers', @_ ) ); }

sub slurp_filename { return( shift->_try( 'request', 'slurp_filename' ) ); }

# Returns a APR::Socket
# See Apache2::Connection manual page
sub socket { return( shift->_try( 'connection', 'client_socket', @_ ) ); }

sub status { return( shift->_try( 'request', 'status', @_ ) ); }

sub status_line { return( shift->_try( 'request', 'status_line', @_ ) ); }

# NOTE: str2datetime for compatibility
sub str2datetime { return( shift->datetime->str2datetime( @_ ) ); }

# NOTE: str2time for compatibility
sub str2time { return( shift->datetime->str2time( @_ ) ); }

sub subnet_of
{
    my $self = shift( @_ );
    my( $ip, $mask ) = @_;
    my $ipsub;
    # try-catch
    local $@;
    my $error;
    eval
    {
        if( $ip && $mask )
        {
            $ipsub = APR::IpSubnet->new( $self->pool, $ip, $mask );
        }
        elsif( $ip )
        {
            $ipsub = APR::IpSubnet->new( $self->pool, $ip );
        }
        else
        {
            $error = "No ip address or block was provided to evaluate current ip against";
        }
    };
    return( $self->error( $error ) ) if( defined( $error ) );
    if( $@ )
    {
        return( $self->error( "An error occurred while trying to create a APR::IpSubnet object with ip \"$ip\" and mask \"$mask\": $@" ) );
    }
    return( $ipsub->test( $self->remote_addr ) );
}

sub subprocess_env { return( shift->_try( 'request', 'subprocess_env' ) ); }

sub temp_dir { return( shift->_try( 'apr', 'temp_dir', @_ ) ); }

lib/Apache2/API/Request.pm  view on Meta::CPAN

    my $val = $req->param( $name );
    my $hash_ref = $req->params;
    
    my $dt = $req->parse_date( $http_date_string );
    
    my $path = $req->path;
    my $path_info = $req->path_info;
    # for JSON payloads
    my $hash_ref = $req->payload;
    my $val = $req->per_dir_config( $my_config_name );
    # APR::Pool object
    my $pool = $req->pool;
    
    my $best_lang = $req->preferred_language( $lang_array_ref );
    
    my $req0 = $req->prev;
    my $proto = $req->protocol;
    $req->proxyreq( Apache2::Const::PROXYREQ_PROXY );
    $req->push_handlers( $name => $code_ref );
    
    # get hash reference from the query string using Apache2::API::Query instead of APR::Body->args
    # To use APR::Body->args, call args() instead
    my $hash_ref = $req->query;
    my $string = $req->query_string;
    
    my $nbytes = $req->read( $buff, 1024 );
    my $notes = $req->redirect_error_notes;
    my $qs = $req->redirect_query_string;
    my $status = $req->redirect_status;
    my $url = $req->redirect_url;
    my $referrer = $req->referer;

    # APR::SockAddr object
    my $addr = $req->remote_addr;
    my $host = $req->remote_host;
    my $string = $req->remote_ip;
    my $port = $req->remote_port;
    
    $req->reply( Apache2::Const::FORBIDDEN => { message => "Get away" } );
    
    # Apache2::RequestRec
    my $r = $req->request;
    my $scheme = $req->request_scheme;
    # DateTime object
    my $dt = $req->request_time;
    my $uri = $req->request_uri;
    my $filename = $req->script_filename;
    my $name = $req->script_name;
    my $uri = $req->script_uri;
    # Apache2::ServerUtil object
    my $server = $req->server;
    my $addr = $req->server_addr;
    my $admin = $req->server_admin;
    my $hostname = $req->server_hostname;
    my $name = $req->server_name;
    my $port = $req->server_port;
    my $proto = $req->server_protocol;
    my $sig = $req->server_signature;
    my $software = $req->server_software;
    my $vers = $req->server_version;
    $req->set_basic_credentials( $user => $password );
    $req->set_handlers( $name => $code_ref );
    my $data = $req->slurp_filename;
    # Apache2::Connection object
    my $socket = $req->socket;
    my $status = $req->status;
    my $line = $req->status_line;
    
    my $dt = $req->str2datetime( $http_date_string );
    my $rc = $req->subnet_of( $ip, $mask );
    # APR::Table object
    my $env = subprocess_env;
    
    my $dir = $req->temp_dir;
    
    my $r = $req->the_request;
    my $dt = $req->time2datetime( $time );
    say $req->time2str( $seconds );
    
    # text/plain
    my $type = $req->type;
    my $raw = $req->unparsed_uri;
    
    # Apache2::API::Request::Params
    my $uploads = $req->uploads;
    my $uri = $req->uri;
    my $decoded = $req->url_decode( $url );
    my $encoded = $req->url_encode( $url );
    my $user = $req->user;
    my $agent = $req->user_agent;

=head1 VERSION

    v0.2.1

=head1 DESCRIPTION

The purpose of this module is to provide an easy access to various methods designed to process and manipulate incoming requests.

This is designed to work under modperl.

Normally, one would need to know which method to access across various Apache2 mod perl modules, which makes development more time consuming and even difficult, because of the scattered documentation and even sometime outdated.

This module alleviate this problem by providing all the necessary methods in one place. Also, at the contrary of L<Apache2> modules suit, all the methods here are die safe. When an error occurs, it will always return undef() and the error will be abl...

For its alter ego to manipulate outgoing HTTP response, use the L<Apache2::API::Response> module.

Throughout this documentation, we refer to C<$r> as the L<Apache request object|Apache2::RequestRec> and C<$req> as an object from this module.

=head1 CONSTRUCTORS

=head2 new

This takes an optional hash or hash reference of options and instantiate a new object.

It takes the following parameters:

=over 4

=item * C<checkonly>

lib/Apache2/API/Request.pm  view on Meta::CPAN


Get or sets the query string data by calling L<APR::Body/args>

With no arguments, this method returns a tied L<APR::Request::Param::Table> object (or undef if the query string is absent) in scalar context, or the names (in order, with repetitions) of all the parsed query-string arguments in list context.

With the $key argument, in scalar context this method fetches the first matching query-string arg. In list context it returns all matching args.

See also L</query> for the equivalent, but using L<Apache2::API::Query> instead of L<APR::Body/args>

See also L</query_string> to set or get the query string as a string.

=head2 args_status

    my $int = $req->args_status; # should be 0

Returns the final status code of the query-string parser.

=head2 as_string

Returns the HTTP request as a string by calling L<Apache2::RequestUtil/as_string>

=head2 auth

Returns the C<Authorization> header value if any. This ill have been processed upon object initiation phase.

=head2 auth_headers

    $req->auth_headers;

Setup the output headers so that the client knows how to authenticate itself the next time, if an authentication request failed. This function works only for basic and digest authentication, by calling L<Apache2::Access/note_auth_failure>

This method requires C<AuthType> to be set to C<Basic> or C<Digest>. Depending on the setting it will call either L</auth_headers_basic> or L</auth_headers_digest>.

It does not return anything.

=head2 auth_headers_basic

    $req->auth_headers_basic;

Setup the output headers so that the client knows how to authenticate itself the next time, if an authentication request failed. This function works only for basic authentication.

It does not return anything.

=head2 auth_headers_digest

    $req->auth_headers_digest;

Setup the output headers so that the client knows how to authenticate itself the next time, if an authentication request failed. This function works only for digest authentication.

It does not return anything.

=head2 auth_name

    my $auth_name = $req->auth_name();
    my $auth_name = $req->auth_name( $new_auth_name );

Sets or gets the current Authorization realm, i.e. the per directory configuration directive C<AuthName>

The C<AuthName> directive creates protection realm within the server document space. To quote RFC 1945 "These realms allow the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme ...

The client uses the root URL of the server to determine which authentication credentials to send with each HTTP request. These credentials are tagged with the name of the authentication realm that created them. Then during the authentication stage th...

=head2 auth_type

    my $auth_type = $req->auth_type();
    my $auth_type = $req->auth_type( $new_auth_type );

Sets or gets the type of authorization required for this request, i.e. the per directory configuration directive C<AuthType>

Normally C<AuthType> would be set to C<Basic> to use the basic authentication scheme defined in RFC 1945, Hypertext Transfer Protocol (HTTP/1.0). However, you could set to something else and implement your own authentication scheme.

=head2 authorization

Returns the HTTP C<authorization> header value. This is similar to L</auth>.

See also L<https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization>

=head2 auth_type

Returns the authentication type by calling L<Apache2::RequestRec/auth_type>

    my $auth_type = $req->auth_type; # Basic

=head2 auto_header

Given a boolean value, this enables the auto header or not by calling the method L<Apache2::RequestRec/assbackwards>

If this is disabled, you need to make sure to manually update the counter, such as:

    $req->connection->keepalives( $req->connection->keepalives + 1 );

See L<Apache2::RequestRec> for more information on this.

=head2 basic_auth_passwd

    my( $rc, $passwd ) = $req->basic_auth_pw;

Get the details from the basic authentication, by calling L<Apache2::Access/get_basic_auth_pw>

It returns:

=over 4

=item 1. the value of an Apache constant

This would be C<Apache2::Const::OK> if the password value is set (and assured a correct value in L</user>); otherwise it returns an error code, either C<Apache2::Const::HTTP_INTERNAL_SERVER_ERROR> if things are really confused, C<Apache2::Const::HTTP...

=item 2. the password as set in the headers (decoded)

=back

Note that if C<AuthType> is not set, L<Apache2::Access/get_basic_auth_pw> first sets it to C<Basic>.

=head2 body

Returns an L<APR::Request::Param::Table|APR::Request::Param> object containing the C<POST> data parameters of the L<Apache2::Request> object.

    my $body = $req->body;
    my @body_names = $req->body;

If there is no request body, then this would return C<undef>. So, for example, if you do a C<POST> query without any content, this would return C<undef>

lib/Apache2/API/Request.pm  view on Meta::CPAN

Typical value is an ip address.

=head2 server_admin

Returns the server admin as provided by L<Apache2::ServerRec/server_admin>

=head2 server_hostname

Returns the server host name as provided by L<Apache2::ServerRec/server_hostname>

=head2 server_name

Get the current request's server name as provided by L<Apache2::RequestUtil/get_server_name>

See L<Apache2::RequestUtil> for more information.

=head2 server_port

Get the current server port as provided by L<Apache2::RequestUtil/get_server_port>

See L<Apache2::RequestUtil> for more information.

=head2 server_protocol

This returns the current value for the environment variable C<SERVER_PROTOCOL>, or set its value if an argument is provided.

Typical value is C<HTTP/1.1>

=head2 server_signature

This returns the current value for the environment variable C<SERVER_SIGNATURE>, or set its value if an argument is provided.

The value of this environment variable can be empty if the Apache configuration parameter C<ServerSignature> is set to C<Off>

=head2 server_software

This returns the current value for the environment variable C<SERVER_SOFTWARE>, or set its value if an argument is provided.

This is typically something like C<Apache/2.4.41 (Ubuntu)>

=head2 server_version

This will endeavour to find out the Apache version.

When called multiple times, it will return a cached value and not recompute each time.

It first tries L<Apache2::ServerUtil/get_server_description>

Otherwise, it tries to find the binary C<apxs> on the filesystem, and if found, calls it like:

    apxs -q -v HTTPD_VERSION

If this does not work too, it will try to call the Apache binary (C<apache2> or C<httpd>) like:

    apache2 -v

and extract the version.

It returns the version found as a L<version> object, or an empty string if nothing could be found.

=head2 set_basic_credentials

Provided with a user name and a password, this populates the incoming request headers table (C<headers_in>) with authentication headers for Basic Authorization as if the client has submitted those in first place:

    $req->set_basic_credentials( $username, $password );

See L<Apache2::RequestUtil> for more information.

=head2 set_handlers

Set a list of handlers to be called for a given phase. Any previously set handlers are forgotten.

See L<Apache2::RequestUtil/set_handlers> for more information.

     $ok = $req->set_handlers( $hook_name => \&handler );
     $ok = $req->set_handlers( $hook_name => ['Foo::Bar::handler', \&handler2] );
     $ok = $req->set_handlers( $hook_name => [] );
     $ok = $req->set_handlers( $hook_name => undef );

=head2 slurp_filename

Slurp the contents of C<< $req->filename >>:

This returns a scalar reference instead of the actual string. To get the string, use L</content>

Note that if you assign to C<$req->filename> you need to update its stat record.

=head2 socket

Get or sets the client socket and returns a L<APR::Socket> object.

This calls L<Apache2::Connection/client_socket> package.

=head2 status

    my $status      = $req->status();
    my $prev_status = $req->status( $new_status );

Get or set thes reply status for the client request, which is an integer, by calling L<Apache2::RequestRec/status>

Normally you would use some L<Apache2::Const> constant, e.g. L<Apache2::Const::REDIRECT>.

From the L<Apache2::RequestRec> documentation:

Usually you will set this value indirectly by returning the status code as the handler's function result. However, there are rare instances when you want to trick Apache into thinking that the module returned an C<Apache2::Const:OK> status code, but ...

    $req->status( $some_code );
    return( Apache2::Const::OK );

See also C<< $req->status_line >>, which. if set, overrides C<< $req->status >>.

=head2 status_line

    my $status_line      = $req->status_line();
    my $prev_status_line = $req->status_line( $new_status_line );

Get or sets the response status line. The status line is a string like C<200 Document follows> and it will take precedence over the value specified using the C<< $req->status() >> described above.

According to the L<Apache2::RequestRec> documentation:

When discussing C<< $req->status >> we have mentioned that sometimes a handler runs to a successful completion, but may need to return a different code, which is the case with the proxy server. Assuming that the proxy handler forwards to the client w...

     $req->status_line( $response->code() . ' ' . $response->message() );
     return( Apache2::Const::OK );



( run in 0.352 second using v1.01-cache-2.11-cpan-2b0bae70ee8 )