<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">package GLPI::Agent::HTTP::Server;

use strict;
use warnings;

use UNIVERSAL::require;
use English qw(-no_match_vars);
use File::Basename;
use HTTP::Daemon;
use IO::Handle;
use Net::IP;
use Text::Template;
use File::Glob;
use URI;
use Socket;
use URI::Escape;

use GLPI::Agent::Version;
use GLPI::Agent::Logger;
use GLPI::Agent::Tools;
use GLPI::Agent::Tools::Network;

# Limit maximum requests number handled in a keep-alive connection
use constant MaxKeepAlive =&gt; 8;

my $log_prefix = "[http server] ";

sub new {
    my ($class, %params) = @_;

    my $self = {
        logger    =&gt; $params{logger} ||
                     GLPI::Agent::Logger-&gt;new(),
        agent     =&gt; $params{agent},
        htmldir   =&gt; $params{htmldir},
        ip        =&gt; $params{ip},
        port      =&gt; $params{port} || 62354,
        listeners =&gt; {},
    };
    bless $self, $class;

    $self-&gt;setTrustedAddresses(%params);

    # Load any Server sub-module as plugin
    my @plugins = ();
    my ($sub_modules_path) = $INC{module2file(__PACKAGE__)} =~ /(.*)\.pm/;
    foreach my $file (File::Glob::bsd_glob("$sub_modules_path/*.pm")) {
        if ($OSNAME eq 'MSWin32') {
            $file =~ s{\\}{/}g;
            $sub_modules_path =~ s{\\}{/}g;
        }

        my ($name) = $file =~ m{$sub_modules_path/(\S+)\.pm$};
        next unless $name;

        # Don't load Plugin base class
        next if $name eq "Plugin";

        $self-&gt;{logger}-&gt;debug($log_prefix . "Trying to load $name Server plugin");

        my $module = __PACKAGE__ . "::" . $name;
        $module-&gt;require();
        if ($EVAL_ERROR) {
            $self-&gt;{logger}-&gt;debug($log_prefix . "Failed to load $name Server plugin: $EVAL_ERROR");
            next;
        }

        my $plugin = $module-&gt;new(server =&gt; $self)
            or next;

        $plugin-&gt;init();
        if ($plugin-&gt;disabled()) {
            $self-&gt;{logger}-&gt;debug($log_prefix . "HTTPD $name Server plugin loaded but disabled");
        } else {
            $self-&gt;{logger}-&gt;info($log_prefix . "HTTPD $name Server plugin loaded");
        }

        push @plugins, $plugin;
    }

    # Sort and store loaded plugins
    @plugins = sort { $b-&gt;priority() &lt;=&gt; $a-&gt;priority() } @plugins
        if @plugins &gt; 1;
    $self-&gt;{_plugins} = \@plugins;

    return $self;
}

sub setTrustedAddresses {
    my ($self, %params) = @_;

    # compute addresses allowed for push requests
    foreach my $target ($self-&gt;{agent}-&gt;getTargets()) {
        next unless $target-&gt;isType('server');
        my $url  = $target-&gt;getUrl();
        my $host = URI-&gt;new($url)-&gt;host();
        my @addresses = compile($host, $self-&gt;{logger});
        $self-&gt;{trust}-&gt;{$url} = \@addresses;
        $self-&gt;{logger}-&gt;debug("Trusted target ip: ".join(", ",map { $_-&gt;print() } @addresses));
    }
    if ($params{trust}) {
        foreach my $string (@{$params{trust}}) {
            my @addresses = compile($string, $self-&gt;{logger})
                or next;
            $self-&gt;{trust}-&gt;{$string} = \@addresses;
            $self-&gt;{logger}-&gt;debug("Trusted client ip: ".join(", ",map { $_-&gt;print() } @addresses));
        }
    }
}

sub _handle {
    my ($self, $client, $request, $clientIp, $maxKeepAlive) = @_;

    my $logger = $self-&gt;{logger};

    if (!$request) {
        $client-&gt;close();
        return;
    }

    my $path = $request-&gt;uri()-&gt;path();
    my $method = $request-&gt;method();
    $logger-&gt;debug($log_prefix . "$method request $path from client $clientIp");

    my $keepalive = ($request-&gt;header('connection') // '') =~ /keep-alive/i;
    my $status = 400;
    my $error_400 = $log_prefix . "invalid request type: $method";

    SWITCH: {
        # root request
        if ($path eq '/') {
            last SWITCH if $method ne 'GET';
            $status = $self-&gt;_handle_root($client, $request, $clientIp);
            last SWITCH;
        }

        # deploy request
        if ($path =~ m{^/deploy/getFile/./../([\w\d/-]+)$}) {
            last SWITCH if $method ne 'GET';
            $status = $self-&gt;_handle_deploy($client, $request, $clientIp, $1);
            last SWITCH;
        }

        # plugins request
        foreach my $plugin (@{$self-&gt;{_plugins}}) {
            next if $plugin-&gt;disabled();
            if ($plugin-&gt;urlMatch($path)) {
                undef $error_400;
                last SWITCH unless $plugin-&gt;supported_method($method);
                $status = $plugin-&gt;handle($client, $request, $clientIp);
                last SWITCH if $status;
            }
        }

        # now request
        if ($path =~ m{^/now(?:/\S*)?$}) {
            last SWITCH if $method ne 'GET';
            $status = $self-&gt;_handle_now($client, $request, $clientIp);
            last SWITCH;
        }

        # status request
        if ($path eq '/status') {
            last SWITCH if $method ne 'GET';
            $status = $self-&gt;_handle_status($client, $request, $clientIp);
            last SWITCH;
        }

        # static content request
        if ($path =~ m{^/(logo.png|site.css|favicon.ico)$}) {
            my $file = $1;
            last SWITCH if $method ne 'GET';
            $client-&gt;send_file_response("$self-&gt;{htmldir}/$file");
            $status = 200;
            last SWITCH;
        }

        $error_400 = $log_prefix . "unknown path: $path";
    }

    if ($status == 400) {
        $logger-&gt;error($error_400) if $error_400;
        $client-&gt;send_error(400)
    }

    $logger-&gt;debug($log_prefix . "response status $status") unless $status == 1;

    if ($status == 200 &amp;&amp; $keepalive &amp;&amp; --$maxKeepAlive) {
        # Looking for another request
        $request = $client-&gt;get_request();
        $self-&gt;_handle($client, $request, $clientIp, $maxKeepAlive) if $request;
    }

    $client-&gt;close();
}

sub _handle_plugins {
    my ($self, $client, $request, $clientIp, $plugins, $maxKeepAlive) = @_;

    my $logger = $self-&gt;{logger};

    if (!$request) {
        $client-&gt;close();
        return;
    }

    my $path = $request-&gt;uri()-&gt;path();
    my $method = $request-&gt;method();
    my $keepalive = $request-&gt;header('connection') =~ /keep-alive/i;
    $logger-&gt;debug($log_prefix . "$method request $path from client $clientIp via plugin");
    my $status = 400;
    my $match  = 0;

    foreach my $plugin (@{$plugins}) {
        next if $plugin-&gt;disabled();
        if ($plugin-&gt;urlMatch($path)) {
            $match = 1;
            last unless ($plugin-&gt;supported_method($method));
            $status = $plugin-&gt;handle($client, $request, $clientIp);
            $self-&gt;{_timer_event} = time+10
                if ($self-&gt;{_timer_event} &gt; time+10);
            last if $status;
        }
    }

    if ($status == 400) {
        $logger-&gt;error($log_prefix . "unknown path: $path") unless $match;
        $client-&gt;send_error(400);
        $status = 400;
    }

    # Don't log status if we forked
    $logger-&gt;debug($log_prefix . "response status $status") unless $status == 1;

    if ($status == 200 &amp;&amp; $keepalive &amp;&amp; --$maxKeepAlive) {
        # Looking for another request
        $request = $client-&gt;get_request();
        $self-&gt;_handle_plugins($client, $request, $clientIp, $plugins, $maxKeepAlive) if $request;
    }

    $client-&gt;close();
}

sub _handle_root {
    my ($self, $client, $request, $clientIp) = @_;

    my $logger = $self-&gt;{logger};

    my $template = Text::Template-&gt;new(
        TYPE =&gt; 'FILE', SOURCE =&gt; "$self-&gt;{htmldir}/index.tpl"
    );
    if (!$template) {
        $logger-&gt;error(
            $log_prefix . "Template access failed: $Text::Template::ERROR"
        );

        my $response = HTTP::Response-&gt;new(
            500,
            'KO',
            HTTP::Headers-&gt;new('Content-Type' =&gt; 'text/html'),
            "No template"
        );

        $client-&gt;send_response($response);
        return 500;
    }

    my @server_targets =
        map { { name =&gt; $_-&gt;getUrl(), date =&gt; $_-&gt;getFormatedNextRunDate() } }
        grep { $_-&gt;isType('server') }
        $self-&gt;{agent}-&gt;getTargets();

    my @local_targets =
        map { { name =&gt; $_-&gt;getPath(), date =&gt; $_-&gt;getFormatedNextRunDate() } }
        grep { $_-&gt;isType('local') }
        $self-&gt;{agent}-&gt;getTargets();

    my @httpd_plugins = map { @{$_-&gt;{plugins}} } values(%{$self-&gt;{listeners}});
    push @httpd_plugins, @{$self-&gt;{_plugins}};
    my @listening_plugins =
        map { { port =&gt; $_-&gt;config('port') || $self-&gt;{port}, name =&gt; $_-&gt;name() } }
            grep { ! $_-&gt;disabled() }
                @httpd_plugins;

    my @sessions = ();
    if ($logger &amp;&amp; $logger-&gt;debug_level() &gt; 1) {
        GLPI::Agent::Target::Listener-&gt;require();
        if ($EVAL_ERROR) {
            $self-&gt;{logger}-&gt;debug($log_prefix . "Failed to load Listener target module: $EVAL_ERROR");
        } else {
            my $listener = GLPI::Agent::Target::Listener-&gt;new(
                logger     =&gt; $self-&gt;{logger},
                basevardir =&gt; $self-&gt;{agent}-&gt;{config}-&gt;{vardir},
            );
            my $sessions = $listener-&gt;sessions();
            foreach my $sid (sort { $a cmp $b } keys(%{$sessions})) {
                push @sessions, $sessions-&gt;{$sid}-&gt;info();
            }
        }
    }

    my $hash = {
        version        =&gt; $GLPI::Agent::Version::VERSION,
        trust          =&gt; $self-&gt;_isTrusted($clientIp),
        status         =&gt; $self-&gt;{agent}-&gt;getStatus(),
        httpd_plugins  =&gt; \@listening_plugins,
        server_targets =&gt; \@server_targets,
        local_targets  =&gt; \@local_targets,
        sessions       =&gt; \@sessions,
    };

    my $response = HTTP::Response-&gt;new(
        200,
        'OK',
        HTTP::Headers-&gt;new('Content-Type' =&gt; 'text/html'),
        $template-&gt;fill_in(HASH =&gt; $hash)
    );

    $client-&gt;send_response($response);
    return 200;
}

sub _handle_deploy {
    my ($self, $client, $request, $clientIp, $sha512) = @_;

    return unless $sha512 =~ /^(.)(.)(.{6})/;
    my $subFilePath = $1.'/'.$2.'/'.$3;

    my $logger = $self-&gt;{logger};

    Digest::SHA-&gt;require();
    if ($EVAL_ERROR) {
        $logger-&gt;error("Failed to load Digest::SHA: $EVAL_ERROR");
        # Return 501 (Not Implemented) to client with reason
        $client-&gt;send_error(501, 'Digest::SHA perl library is missing');
        return 501;
    }

    my $path;
    my $count = 0;
    LOOP: foreach my $target ($self-&gt;{agent}-&gt;getTargets()) {
        foreach (File::Glob::bsd_glob($target-&gt;{storage}-&gt;getDirectory() . "/deploy/fileparts/shared/*")) {
            next unless -f $_.'/'.$subFilePath;

            $count ++;

            my $sha = Digest::SHA-&gt;new('512');
            $sha-&gt;addfile($_.'/'.$subFilePath, 'b');
            next unless $sha-&gt;hexdigest eq $sha512;

            $path = $_.'/'.$subFilePath;
            last LOOP;
        }
    }
    if ($path) {
        $client-&gt;send_file_response($path);
        return 200;
    } else {
        if ($count) {
            $client-&gt;send_error(404);
        } else {
            # Report this agent as nothing to share
            $client-&gt;send_error(404, 'Nothing found');
        }
        return 404;
    }
}

sub _handle_now {
    my ($self, $client, $request, $clientIp) = @_;

    my $logger = $self-&gt;{logger};

    my ($code, $message) = qw( 200 OK );
    my $trace;

    my @targets;
    foreach my $target ($self-&gt;{agent}-&gt;getTargets()) {
        next unless $target-&gt;isType('server');
        my $url       = $target-&gt;getUrl();
        my $addresses = $self-&gt;{trust}-&gt;{$url};
        next unless isPartOf($clientIp, $addresses, $logger);
        $trace = "rescheduling next contact for target $url right now";
        push @targets, $target;
        last;
    }

    push @targets, $self-&gt;{agent}-&gt;getTargets()
        if !@targets &amp;&amp; $self-&gt;_isTrusted($clientIp);

    if (@targets) {
        my $query = uri_unescape($request-&gt;uri()-&gt;query());
        if ($query) {
            my %event = map { /^([^=]+)=(.*)$/ } grep { /[^=]=/ } split('&amp;', $query);
            foreach my $target (@targets) {
                if (my $event = $target-&gt;addEvent(\%event)) {
                    $logger-&gt;debug($log_prefix."$event-&gt;{name} triggering event on ".$target-&gt;id());
                } else {
                    $logger-&gt;debug($log_prefix."unsupported target event: $query");
                }
            }
        } else {
            map { $_-&gt;setNextRunDateFromNow() } @targets;
            $trace = "rescheduling next contact for all targets right now";
        }
    } else {
        $code    = 403;
        $message = "Access denied";
        $trace   = "invalid request (untrusted address)";
    }

    my $template = Text::Template-&gt;new(
        TYPE =&gt; 'FILE', SOURCE =&gt; "$self-&gt;{htmldir}/now.tpl"
    );

    my $hash = {
        message =&gt; $message
    };

    my $response = HTTP::Response-&gt;new(
        $code,
        'OK',
        HTTP::Headers-&gt;new('Content-Type' =&gt; 'text/html'),
        $template-&gt;fill_in(HASH =&gt; $hash)
    );

    $client-&gt;send_response($response);
    $logger-&gt;debug($log_prefix . $trace) if $trace;
    return $code;
}

sub _handle_status {
    my ($self, $client, $request, $clientIp) = @_;

    my $status = $self-&gt;{agent}-&gt;getStatus();
    my $response = HTTP::Response-&gt;new(
        200,
        'OK',
        HTTP::Headers-&gt;new('Content-Type' =&gt; 'text/plain'),
       "status: ".$status
    );
    $client-&gt;send_response($response);
    return 200;
}

sub _isTrusted {
    my ($self, $address) = @_;

    foreach my $trusted_addresses (values %{$self-&gt;{trust}}) {
        return 1
            if isPartOf(
                $address,
                $trusted_addresses,
                $self-&gt;{logger}
            );
    }

    return 0;
}

sub init {
    my ($self) = @_;

    my $logger = $self-&gt;{logger};

    $self-&gt;{listener} = HTTP::Daemon-&gt;new(
        LocalAddr =&gt; $self-&gt;{ip},
        LocalPort =&gt; $self-&gt;{port},
        ReuseAddr =&gt; 1,
        ReusePort =&gt; $OSNAME ne 'MSWin32',
        Timeout   =&gt; 1,
        Blocking  =&gt; 0
    );

    if (!$self-&gt;{listener}) {
        $logger-&gt;error($log_prefix . "failed to start the HTTPD service");
        return;
    }

    my $io_poller;

    IO::Poll-&gt;require();
    if ($EVAL_ERROR) {
        $logger-&gt;debug("Can't use IO::Poll to optimize HTTP requests handling: $!");
    } else {
        $io_poller = IO::Poll-&gt;new();
        $io_poller-&gt;mask($self-&gt;{listener} =&gt; IO::Poll::POLLIN);
        $self-&gt;{_poller} = $io_poller;
    }

    $logger-&gt;info(
        $log_prefix . "HTTPD service started on port $self-&gt;{port}"
    );

    # Load any plugin configuration and fix plugins list handled on main port
    my %plugins = map { $_-&gt;name() =&gt; $_ } @{$self-&gt;{_plugins}};
    foreach my $plugin (@{$self-&gt;{_plugins}}) {

        next if $plugin-&gt;disabled();

        # We handle SSL Plugin differently
        if ($plugin-&gt;name() eq 'SSL') {
            my $ports = $plugin-&gt;config('ports');
            foreach my $port (@{$ports}) {
                # Handle SSL case on default port
                if (!$port || $port == $self-&gt;{port}) {
                    $self-&gt;{_ssl} = $plugin;
                    $logger-&gt;info($log_prefix . "HTTPD SSL Server plugin enabled on default port");
                    next;
                }
                if (!$self-&gt;{listeners}-&gt;{$port}) {
                    my $listener = HTTP::Daemon-&gt;new(
                            LocalAddr =&gt; $self-&gt;{ip},
                            LocalPort =&gt; $port,
                            ReuseAddr =&gt; 1,
                            ReusePort =&gt; $OSNAME ne 'MSWin32',
                            Timeout   =&gt; 1,
                            Blocking  =&gt; 0
                    );
                    unless ($listener) {
                        $logger-&gt;error($log_prefix . "failed to start the HTTPD service on port $port for SSL plugin");
                        next;
                    }
                    $self-&gt;{listeners}-&gt;{$port} = {
                        ssl         =&gt; $plugin,
                        listener    =&gt; $listener,
                        plugins     =&gt; [],
                    };
                    if ($io_poller) {
                        $io_poller = IO::Poll-&gt;new();
                        $io_poller-&gt;mask($listener =&gt; IO::Poll::POLLIN);
                        $self-&gt;{_pollers}-&gt;{$port} = $io_poller;
                    }
                } else {
                    $self-&gt;{listeners}-&gt;{$port}-&gt;{ssl} = $plugin;
                }
                $logger-&gt;info($log_prefix . "HTTPD SSL Server plugin enabled on port $port");
            }
            delete $plugins{$plugin-&gt;name()};
            next;
        }

        # Add a port listener if a plugin uses a dedicated port
        my $port = $plugin-&gt;port();
        if ($port &amp;&amp; $port != $self-&gt;{port}) {
            if ($self-&gt;{listeners}-&gt;{$port}) {
                push @{$self-&gt;{listeners}-&gt;{$port}-&gt;{plugins}}, $plugin;
                $logger-&gt;info($log_prefix . "HTTPD ".$plugin-&gt;name()." Server plugin also used on port $port");
            } else {
                my $listener = HTTP::Daemon-&gt;new(
                        LocalAddr =&gt; $self-&gt;{ip},
                        LocalPort =&gt; $port,
                        ReuseAddr =&gt; 1,
                        ReusePort =&gt; $OSNAME ne 'MSWin32',
                        Timeout   =&gt; 1,
                        Blocking  =&gt; 0
                );
                if (!$listener) {
                    $logger-&gt;error($log_prefix . "failed to start the HTTPD service on port $port for ".$plugin-&gt;name()." plugin");
                    $plugin-&gt;disable();
                } else {
                    $self-&gt;{listeners}-&gt;{$port} = {
                        listener    =&gt; $listener,
                        plugins     =&gt; [ $plugin ],
                    };
                    $logger-&gt;info($log_prefix . "HTTPD ".$plugin-&gt;name()." Server plugin also started on port $port");
                    if ($io_poller) {
                        $io_poller = IO::Poll-&gt;new();
                        $io_poller-&gt;mask($listener =&gt; IO::Poll::POLLIN);
                        $self-&gt;{_pollers}-&gt;{$port} = $io_poller;
                    }
                }
            }
            delete $plugins{$plugin-&gt;name()};
        } elsif ($port) {
            $logger-&gt;info($log_prefix . "HTTPD ".$plugin-&gt;name()." Server plugin also used on main port $self-&gt;{port}");
        }
    }
    $self-&gt;{_plugins} = [ values(%plugins) ];

    return 1;
}

sub plugins_list {
    my ($self) = @_;

    my @plugins = @{$self-&gt;{_plugins}};
    map {
        push @plugins, @{$self-&gt;{listeners}-&gt;{$_}-&gt;{plugins}};
        # Add SSL plugin if it was enabled on a dedicated port
        push @plugins, $self-&gt;{listeners}-&gt;{$_}-&gt;{ssl} if $self-&gt;{listeners}-&gt;{$_}-&gt;{ssl};
    } grep {
        $self-&gt;{listeners}-&gt;{$_}-&gt;{plugins}
    } keys(%{$self-&gt;{listeners}}) if $self-&gt;{listeners};

    return {
        map {
            my $plugin = $_;
            lc($plugin-&gt;name()) =&gt; $plugin-&gt;disabled ? "disabled" : {
                map { $_ =&gt; $plugin-&gt;config($_) } keys(%{$plugin-&gt;defaults()})
            }
        } @plugins
    };
}

sub needToRestart {
    my ($self, %params) = @_;

    # If no httpd daemon was started, we need to really start it
    return 1 unless $self-&gt;{listener};

    # Restart httpd daemon if ip or port changed
    return 1 if ($params{ip} &amp;&amp; (!$self-&gt;{ip} || $params{ip} ne $self-&gt;{ip}));
    return 1 if ($params{port} &amp;&amp; (!$self-&gt;{port} || $params{port} ne $self-&gt;{port}));

    # Reload any plugin configuration and check if port or status has changed
    foreach my $plugin (@{$self-&gt;{_plugins}}) {
        my $port = $plugin-&gt;port();
        my $disabled = $plugin-&gt;disabled();
        $plugin-&gt;init();
        return 1 if $port != $plugin-&gt;port();
        return 1 if $disabled != $plugin-&gt;disabled();
    }

    # Logger may have changed, but then resetting logger ref is sufficient
    $self-&gt;{logger} = $params{logger};
    $self-&gt;{logger}-&gt;debug2(
        $log_prefix . "HTTPD service still listening on port $self-&gt;{port}"
    );

    # Be sure to reset computed trusted addresses
    delete $self-&gt;{trust};
    $self-&gt;setTrustedAddresses(%params);

    return 0;
}

sub stop {
    my ($self) = @_;

    return unless $self-&gt;{listener};

    foreach my $port (keys(%{$self-&gt;{listeners}})) {
        $self-&gt;{listeners}-&gt;{$port}-&gt;{listener}-&gt;shutdown(2);
        delete $self-&gt;{listeners}-&gt;{$port};
    }
    $self-&gt;{listener}-&gt;shutdown(2);

    $self-&gt;{logger}-&gt;debug($log_prefix . "HTTPD service stopped");

    delete $self-&gt;{_plugins};
    delete $self-&gt;{listener};
}

sub handleRequests {
    my ($self) = @_;

    return unless $self-&gt;{listener}; # init() call failed

    # Avoid an error as Socket::VERSION may contain underscore
    my ($SocketVersion) = split('_',$Socket::VERSION);

    # Handle any timer event on plugins and set next time expected to handle events
    unless ($self-&gt;{_timer_event} &amp;&amp; $self-&gt;{_timer_event} &gt; time) {
        my @enabled_plugins = grep { ! $_-&gt;disabled() } @{$self-&gt;{_plugins}};
        my ($timeout) = sort grep { $_ } map { $_-&gt;timer_event() } @enabled_plugins;
        $self-&gt;{_timer_event} = ($timeout &amp;&amp; $timeout &gt; time) ? $timeout : time + 60;
    }

    # First try to handle plugin requests on dedicated ports
    my $got_connection = 0;
    foreach my $port (keys(%{$self-&gt;{listeners}})) {
        next if $self-&gt;{_pollers} &amp;&amp; $self-&gt;{_pollers}-&gt;{$port} &amp;&amp;
            ! $self-&gt;{_pollers}-&gt;{$port}-&gt;poll(0);
        my ($client, $socket) = $self-&gt;{listeners}-&gt;{$port}-&gt;{listener}-&gt;accept();
        next unless $socket;

        $got_connection++;

        # Upgrade to SSL if required
        my $ssl = $self-&gt;{listeners}-&gt;{$port}-&gt;{ssl};
        if ($ssl &amp;&amp; !$ssl-&gt;upgrade_SSL($client)) {
            $self-&gt;{logger}-&gt;debug($log_prefix . "HTTPD can't start SSL session");
            next;
        }

        my $family = sockaddr_family($socket);
        my $iaddr  = $family == AF_INET  ? unpack_sockaddr_in($socket)  :
                     $family == AF_INET6 ? unpack_sockaddr_in6($socket) :
                     INADDR_ANY;
        my $clientIp;
        # Compatibility: Socket::inet_ntop() is only available since perl 5.12 introducing Socket v1.87
        if ($SocketVersion &gt;= 1.87) {
            $clientIp = Socket::inet_ntop($family, $iaddr);
        } else {
            my (undef, $iaddr) = sockaddr_in($socket);
            $clientIp = inet_ntoa($iaddr);
        }
        my $request = $client-&gt;get_request();
        $self-&gt;_handle_plugins($client, $request, $clientIp, $self-&gt;{listeners}-&gt;{$port}-&gt;{plugins}, MaxKeepAlive);
    }

    return unless $self-&gt;{listener}; # in case of config reload()

    return $got_connection if $self-&gt;{_poller} &amp;&amp; ! $self-&gt;{_poller}-&gt;poll(0);

    my ($client, $socket) = $self-&gt;{listener}-&gt;accept();
    return $got_connection unless $socket;

    $got_connection++;

    # Upgrade to SSL if required
    if ($self-&gt;{_ssl} &amp;&amp; !$self-&gt;{_ssl}-&gt;upgrade_SSL($client)) {
        $self-&gt;{logger}-&gt;debug($log_prefix . "HTTPD can't start SSL session");
        return $got_connection;
    }

    my $family = sockaddr_family($socket);
    my $iaddr  = $family == AF_INET  ? unpack_sockaddr_in($socket)  :
                 $family == AF_INET6 ? unpack_sockaddr_in6($socket) :
                 INADDR_ANY;
    my $clientIp;
    # Compatibility: Socket::inet_ntop() is only available since perl 5.12 introducing Socket v1.87
    if ($SocketVersion &gt;= 1.87) {
        $clientIp = Socket::inet_ntop($family, $iaddr);
    } else {
        my (undef, $iaddr) = sockaddr_in($socket);
        $clientIp = inet_ntoa($iaddr);
    }
    my $request = $client-&gt;get_request();
    $self-&gt;_handle($client, $request, $clientIp, MaxKeepAlive);

    $self-&gt;{_timer_event} = time+10
        if ($self-&gt;{_timer_event} &gt; time+10);

    return $got_connection;
}

1;
__END__

=head1 NAME

GLPI::Agent::HTTP::Server - An embedded HTTP server

=head1 DESCRIPTION

This is the server used by the agent to listen on the network for messages sent
by OCS or GLPI servers.

It is an HTTP server listening on port 62354 (by default). The following
requests are accepted:

=over

=item /status

=item /deploy

=item /now

=back

Authentication is based on connection source address: trusted requests are
accepted, other are rejected.

=head1 CLASS METHODS

=head2 new(%params)

The constructor. The following parameters are allowed, as keys of the %params
hash:

=over

=item I&lt;logger&gt;

the logger object to use

=item I&lt;htmldir&gt;

the directory where HTML templates and static files are stored

=item I&lt;ip&gt;

the network address to listen to (default: all)

=item I&lt;port&gt;

the network port to listen to

=item I&lt;trust&gt;

an IP address or an IP address range from which to trust incoming requests
(default: none)

=back

=head1 INSTANCE METHODS

=head2 $server-&gt;init()

Start the server internal listener.

=head2 $server-&gt;handleRequests()

Check if there any incoming request, and honours it if needed. Returns the number
of handled connections.
</pre></body></html>