package Net::SNTP::Server;

## Validate the version of Perl

BEGIN { die 'Perl version 5.6.0 or greater is required' if ($] < 5.006); }

use strict;
use warnings;

=head1 NAME

Net::SNTP::Server - Perl Module SNTP Server based on L<RFC4330|https://tools.ietf.org/html/rfc4330>

=head1 VERSION

Version 0.02

=cut

## Version of the Net::SNTP::Server module

our $VERSION = '0.02';
$VERSION = eval $VERSION;

use IO::Socket::INET;
use Time::HiRes qw( gettimeofday CLOCK_REALTIME clock_getres );

## Handle importing/exporting of symbols

use Exporter 5.57 qw( import ); # Because I am using an earlier version of Perl 5.8.2 
our @EXPORT_OK = qw( basicSNTPSetup );  # symbols to export on request

=head1 SYNOPSIS

The Net::SNTP::Server - Perl module has the ability to retrieve the
 time from the local internal clock of the OS. The module has been 
 tested on LinuxOS but it should be compatible with MacOS and WindowsOS.
 When the server is activated, it will enter while state mode and wait
 for client requests. The SNTP server uses the local time in seconds and 
 nano seconds accuracy based on the OS accuracy ability. The server will
 encode a message format based on RFC4330 that will be send to the client 
 in-order to calculate the round-trip delay d and system clock offset.

    use Net::SNTP::Server;

    my ( $error , $hashRefOutput ) = basicSNTPSetup( %hashInput );
    ...

=head1 ABSTRACT

The module receives and sends a UDP packet formated according to
 L<RFC4330|https://tools.ietf.org/html/rfc4330> message format.
 The server expects an SNTP packet from the client which will reply 
 back to him. The received packet, gets decoded into a human readable
 form. As a second step the server extracts and adds the needed
 data to create the packet. Before the message to be sent to the client
 it gets encoded and transmitted back to the recipient.


=head1 DESCRIPTION

This module exports a single method (basicSNTPSetup) and returns
 an associative hash based on the user input and a string in case
 of an error. The response from the SNTP server is been encoded
 to a human readable format. The obtained information received
 from the server on the client side can be used into further processing
 or manipulation according to the user needs. Maximum accuracy down
 to nano seconds can only be achieved based on different OS.

=head2 EXPORT

  my %hashInput = (
      -ip      => $ip,    # IP
      -port    => $port,  # default NTP port 123 
      );

  my ( $error , $hashRefOutput ) = basicSNTPSetup( %hashInput );

=over 4

=item * IP

    -ip: Is not a mandatory for the method key to operate correctly.
    By default the module will assign the localhost IP ("127.0.0.1"),
    but this will restrict the server to localhost communications (only
    internally it can receive and transmit data).


=item * PORT

    -port: Is a mandatory key, that the user must define. By default the
    port is not set. The user has to specify the port. We can not use the
    default 123 NTP due to permission. The user has to choose a port number
    identical to port that the client will use client to communicate with
    the server (e.g. -port => 123456).

=back

=head1 SUBROUTINES/METHODS

  my ( $error , $hashRefOutput ) = basicSNTPSetup( %hashInput );


=cut

## Define constands

use constant {
    TRUE                  => 1,
    FALSE                 => 0,
    MAXBYTES              => 512,
    ARGUMENTS             => 1,
    UNIX_EPOCH            => 2208988800,
    MIN_UDP_PORT          => 1,
    MAX_UDP_PORT          => 65535,
    DEFAULT_LOCAL_HOST_IP => "127.0.0.1",
};

sub basicSNTPSetup {
    my $error = undef;
    my $rcvSntpPacket = undef;
    my ( $rcv_sntp_packet ,  $server_precision );

    my %moduleInput = @_;
    my %moduleOutput = ();

    return ($error = "Not defined IP", \%moduleInput) if (!$moduleInput{-ip});
    return ($error = "Not defined Port", \%moduleInput) if (!$moduleInput{-port});
    return ($error = "Not defined key(s)", \%moduleInput) if (checkHashKeys(%moduleInput));
    return ($error = "Not correct port number", \%moduleInput) if (verify_port($moduleInput{-port}));
    
    my ( @array_IP ) = ( $moduleInput{-ip} =~ /(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/ );
    return ($error = "Not correct input IP syntax", \%moduleInput) 
	if ( (!defined $array_IP[0]) || 
	     (!defined $array_IP[1]) || 
	     (!defined $array_IP[2]) || 
	     (!defined $array_IP[3]) );

    # Convert IP
    my $server_reference_identifier_hex .= dec_2_hex( @array_IP );

    my $server_socket;
    eval {
	$server_socket = IO::Socket::INET->new(
	    LocalAddr  => $moduleInput{-ip} || DEFAULT_LOCAL_HOST_IP,
	    LocalPort  => $moduleInput{-port}, # Mandatory, we can't use NTP default 123
	    Proto      => 'udp',
	    Type       => SOCK_DGRAM,
	    Broadcast  => 1 ) or die "Error Creating Socket"; 
    };
    return ($error = "Problem While Creating Socket '$!'", \%moduleInput) if ( $@ && $@ =~ /Error Creating Socket/ );
    
    print "\n[Server $0 listens at PORT: ".$moduleInput{-port}." and IP: ".$moduleInput{-ip}."]\n\n";

    while ( TRUE ) {
	# Reference Timestamp: This field is the time the system clock was last
	# set or corrected, in 64-bit timestamp format. (assumption of time synchronization)
	my ( $server_reference_timestamp_sec,
	     $server_reference_timestamp_microsec ) = gettimeofday();

	my $peer_address = $server_socket->peerhost();
	my $peer_port = $server_socket->peerport();
	
	if ( $peer_address ) { print "Peer address: ".$peer_address."\n" };
	if ( $peer_port ) { print "Peer port: ".$peer_port."\n" };
	
	eval {
	    $server_socket->recv( $rcv_sntp_packet , MAXBYTES )
		or die "Error Receiving";
	};
	return ($error = "Problem While Receiving '$!'", \%moduleInput) if ( $@ && $@ =~ /Error Receiving/ );
	
	# $server_rcv_timestamp_sec (originate time rcv by server sec) # 32 bit
	# $server_rcv_timestamp_microsec (originate time rcv by server microsec) # 32 bit
	my ( $server_rcv_timestamp_sec, 
	     $server_rcv_timestamp_microsec ) = gettimeofday();

	my @arrayRcvSntpPacket = unpack( "B8 C3 N11" , $rcv_sntp_packet );

	my ( $client_li_vn_mode,
	     $client_stratum,
	     $client_poll,
	     $client_precision,
	     $client_root_delay,
	     $client_dispersion,
	     $client_reference_identifier,
	     $client_reference_timestamp_sec,
	     $client_reference_timestamp_microsec,
	     $client_originate_timestamp_sec,
	     $client_originate_timestamp_microsec,
	     $client_receive_timestamp_sec,
	     $client_receive_timestamp_microsec,
	     $client_transmit_sec,
	     $client_transmit_microsec ) = @arrayRcvSntpPacket;
	
        # Server data preparing message
	# $li = 00 2 bit = value 0 no warning
	# $vn = 100 3 bit = Value 4 IPV4
	# $mode = 100 3 bit = Value 4 server mode
	my $server_li_vn_mode = '00100100';
	my $server_stratum = '00000010'; # Stratum is 3 because
	my $server_poll_interval = 3; # Poll interval is 6

	# The precission size on the RFC is 8 bits, anything lower
	# than 1e-03 (0.001) it can not fit on 8 bits. In such cases
	# we round to clossest digit. Never the less the value is so
	# small not even worth mentioning it.

	if ( $^O eq 'MSWin32' ) {
	    ( undef , undef ,  $server_precision , undef , undef ) = POSIX::times() ;
	}
	else {
	    $server_precision = clock_getres( CLOCK_REALTIME );
	}

	my $server_root_delay_sec = '0'; # 16 bit
	my $server_root_delay_microsec = '0'; # 16 bit
	my $server_dispersion_sec = '0'; # 16 bit
	my $server_dispersion_microsec = '0'; # 16 bit

	$server_reference_timestamp_sec += UNIX_EPOCH;
	$server_rcv_timestamp_sec += UNIX_EPOCH;

	# $server_transmit_timestamp_sec (originate time rcv by server sec) # 32 bit
	# $server_transmit_timestamp_microsec (originate time rcv by server microsec) # 32 bit
	my ( $server_transmit_timestamp_sec,
	     $server_transmit_timestamp_microsec ) = gettimeofday();

	$server_transmit_timestamp_sec += UNIX_EPOCH;

	my @arraySendSntpPacket = ( $server_li_vn_mode,
				    $server_stratum,
				    $server_poll_interval,
				    $server_precision,
				    $server_root_delay_sec, 
				    $server_root_delay_microsec,
				    $server_dispersion_sec,
				    $server_dispersion_microsec,
				    $server_reference_identifier_hex,
				    $server_reference_timestamp_sec,
				    $server_reference_timestamp_microsec,
				    $client_transmit_sec,
				    $client_transmit_microsec,
				    $server_rcv_timestamp_sec,
				    $server_rcv_timestamp_microsec,
				    $server_transmit_timestamp_sec,
				    $server_transmit_timestamp_microsec );
	
	my $send_sntp_packet = pack( "B8 C3 n B16 n B16 H8 N8" , @arraySendSntpPacket );

	eval {
	    $server_socket->send( $send_sntp_packet )
		or die "Error Sending";
	};
	return ($error = "Problem While Sending '$!'", \%moduleInput) if ( $@ && $@ =~ /Error Sending/ );

    } # End of while(TRUE) loop

    $server_socket->close(); # Close socket

    return $error, \%moduleOutput;
}

sub dec_2_hex {
    my ( @decimal_IP ) = @_;
    my $hex = join(
	'', map { sprintf '%02X', $_ } $decimal_IP[0], $decimal_IP[1], $decimal_IP[2], $decimal_IP[3]);
    return ( uc( $hex ) );
}

sub checkHashKeys {
    my @keysToCompare = ( "-ip", "-port" );
    my %hashInputToCompare = @_;
    my @hashInputKeysToCompare = keys %hashInputToCompare;

    local *keyDifference = sub {
	my %hashdiff = map{ $_ => 1 } @{$_[1]}; 
	return grep { !defined $hashdiff{$_} }  @{$_[0]};
    };
    my @differendKeys = keyDifference(\@hashInputKeysToCompare, \@keysToCompare);
    
    # c - style if condition
    return TRUE ? @differendKeys : return FALSE;
    # Or if (@differendKeys) { return TRUE } else { return FALSE };
}

sub verify_port {
    my $port = shift;
    if ( defined $port && $port =~ /^[0-9]+$/ ) {
	if ( $port >= MIN_UDP_PORT && MAX_UDP_PORT >= $port ) {
	    return FALSE;
	}
    }
    return TRUE;
}

=head1 EXAMPLE

This example starts a remote NTP server based on RFC4330 message format. 
 The IP and Port that the user will provide based on his criteria.

We use the L<Data::Dumper|http://search.cpan.org/~ilyam/Data-Dumper-2.121/Dumper.pm>
 module to print the output if needed. The module does not require
 to printout the output. It should be used only for initialization 
 purposes to assist the user with debugging in case of an error. 
 The $error string it is also optional that will assist the user
 to identify the root that can cause a faulty initialization.


  #!/usr/bin/perl
  use strict;
  use warnings;
  use Data::Dumper;

  use Net::SNTP::Server qw(basicSNTPSetup);

  my %hashInput = (
      -ip      => "127.0.0.1",
      -port    => 12345,
      );

  my ( $error , $hashRefOutput ) = basicSNTPSetup( %hashInput );

  print Dumper $hashRefOutput;
  print "Error: $error\n" if ($error);


=head1 AUTHOR

Athanasios Garyfalos, C<< <garyfalos at cpan.org> >>

=head1 BUGS

Please report any bugs or feature requests to C<bug-net-sntp-server at rt.cpan.org>, or through
the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Net-SNTP-Server>. I will be notified, and then you'll
automatically be notified of progress on your bug as I make changes.




=head1 SUPPORT

You can find documentation for this module with the perldoc command.

    perldoc Net::SNTP::Server


You can also look for information at:

=over 4

=item * RT: CPAN's request tracker (report bugs here)

L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Net-SNTP-Server>

=item * AnnoCPAN: Annotated CPAN documentation

L<http://annocpan.org/dist/Net-SNTP-Server>

=item * CPAN Ratings

L<http://cpanratings.perl.org/d/Net-SNTP-Server>

=item * Search CPAN

L<http://search.cpan.org/dist/Net-SNTP-Server/>

=back


=head1 ACKNOWLEDGEMENTS

I want to say thank you to L<Perl Monks The Monastery Gates|http://www.perlmonks.org/> 
 for their guidance and assistance when ever I had a problem with
 the implementation process of module.

=head1 LICENSE AND COPYRIGHT

Copyright 2015 Athanasios Garyfalos.

This program is free software; you can redistribute it and/or modify it
under the terms of the the Artistic License (2.0). You may obtain a
copy of the full license at:

L<http://www.perlfoundation.org/artistic_license_2_0>

Any use, modification, and distribution of the Standard or Modified
Versions is governed by this Artistic License. By using, modifying or
distributing the Package, you accept this license. Do not use, modify,
or distribute the Package, if you do not accept this license.

If your Modified Version has been derived from a Modified Version made
by someone other than you, you are nevertheless required to ensure that
your Modified Version complies with the requirements of this license.

This license does not grant you the right to use any trademark, service
mark, tradename, or logo of the Copyright Holder.

This license includes the non-exclusive, worldwide, free-of-charge
patent license to make, have made, use, offer to sell, sell, import and
otherwise transfer the Package with respect to any patent claims
licensable by the Copyright Holder that are necessarily infringed by the
Package. If you institute patent litigation (including a cross-claim or
counterclaim) against any party alleging that the Package constitutes
direct or contributory patent infringement, then this Artistic License
to you shall terminate on the date that such litigation is filed.

Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=head1 CHANGE LOG

$Log: Server.pm,v $
Revision 2.0  2015/07/21 16:32:31  Thanos


=cut

1; # End of Net::SNTP::Server
