package Net::Shadowsocks;

# ABSTRACT: An asynchronous, non-blocking shadowsocks client and server module.
use 5.006;
use strict;
use warnings;
use Crypt::Random qw( makerandom_octet );



our $VERSION = '0.6.2';



{

    package Net::Shadowsocks::Client;

    # ABSTRACT: Shadowsocks protocol client module.
    use 5.006;
    use strict;
    use warnings;
    use AnyEvent;
    use AnyEvent::Handle;
    use AnyEvent::Socket;
    use Carp;
    use Crypt::Random qw( makerandom_octet );
    use Digest::MD5;
    use IO::Socket::Socks qw(:constants $SOCKS_ERROR ESOCKSPROTO);
    use Mcrypt;
    use Mcrypt qw(:ALGORITHMS);
    use Mcrypt qw(:MODES);
    use Mcrypt qw(:FUNCS);
    use Net::Shadowsocks qw(_EVP_BytesToKey _initialize_cipher);


    sub new($$$$$$)
    {

        my ($class, %args) = @_;
        my $self = bless {
                          map { ($_ => $args{$_}) }
                            qw(local_address local_port password server server_port method),
                         }, $class;
        if ($self->{local_address} eq 'localhost')
        {
            undef $self->{local_address};
        }

        my $tcp_server;
        $tcp_server = AnyEvent::Socket::tcp_server(
            $self->{local_address},
            $self->{local_port},

            sub {
                my ($client_socket, $client_host, $client_port) = @_;

                #carp "Got new client connection: $client_host:$client_port";
                my $addr_to_send = '';
                my $serveriv;
                my $stage = 0;
                my $mode  = 0;
                my ($encryptor, $decryptor, $key, $iv) =
                  Net::Shadowsocks::_initialize_cipher($self->{method},
                                                       $self->{password});

                my $clienthandler;
                my $remotehandler;
                $clienthandler = AnyEvent::Handle->new(
                    autocork  => 1,
                    keepalive => 1,
                    no_delay  => 1,
                    fh        => $client_socket,
                    on_eof    => sub {
                        my $chandler = shift;
                        AE::log info => "Client: Done.";
                        $chandler->destroy();
                    },
                    on_error => sub {
                        my ($chandler, $fatal, $msg) = @_;
                        AE::log error => $msg;
                        $chandler->destroy();
                    },
                    on_read => sub {

                        my $client_buffer = $clienthandler->rbuf();

                        if ($client_buffer eq '')
                        {
                            return;
                        }
                        else
                        {
                            if ($stage == 0)
                            {
                                my $ver = ord(substr($client_buffer, 0, 1));

                                if ($ver != SOCKS5_VER)
                                {
                                    $! = ESOCKSPROTO;
                                    $SOCKS_ERROR->set(ISS_BAD_VERSION,
                                        $@ =
                                          "Socks version should be 5, $ver recieved"
                                    );
                                    return;
                                }
                                my $nmethods =
                                  ord(substr($client_buffer, 1, 1));

                                if ($nmethods == 0)
                                {
                                    $! = ESOCKSPROTO;
                                    $SOCKS_ERROR->set(AUTHMECH_INVALID,
                                                   $@ = "No auth methods sent");
                                    return;
                                }
                                my @methods =
                                  unpack('C' x $nmethods,
                                         substr($client_buffer, 2));

                                $clienthandler->push_write(
                                                     pack('CC', SOCKS5_VER, 0));
                                $stage = 1;

                            }
                            elsif ($stage == 1)
                            {
                                my $cmd = ord(substr($client_buffer, 1, 1));

                                if ($cmd == CMD_CONNECT)
                                {
                                    my $addrtype =
                                      ord(substr($client_buffer, 3, 1));
                                    if (    $addrtype != 1
                                        and $addrtype != 3
                                        and $addrtype != 4)
                                    {
                                        carp 'addrtype not supported';
                                        return;
                                    }
                                    $addr_to_send = substr($client_buffer, 3);

                                    if (!defined($self->{local_address}))
                                    {
                                        $self->{local_address} = 'localhost';
                                    }
                                    my $hlen = length($self->{local_address});
                                    $clienthandler->push_write(
                                              pack('CCCC',
                                                   SOCKS5_VER, 0,
                                                   0,          ADDR_DOMAINNAME)
                                                . pack('C', $hlen)
                                                . $self->{local_address}
                                                . pack('n', $self->{local_port})
                                    );
                                    $stage = 4;

                                    $remotehandler = AnyEvent::Handle->new(
                                        autocork  => 1,
                                        keepalive => 1,
                                        no_delay  => 1,
                                        connect   => [
                                                    $self->{server},
                                                    $self->{server_port}
                                                   ],
                                        on_connect => sub {
                                            my (
                                                $rhandle,  $peerhost,
                                                $peerport, $retry
                                               )
                                              = @_;

                                            unless ($rhandle)
                                            {
                                                carp "couldn't connect: $!";
                                                return;
                                            }
                                        },
                                        on_eof => sub {
                                            my $rhandler = shift;
                                            $rhandler->destroy();
                                            $mode = 0;
                                            AE::log info => "Remote: Done.";
                                        },
                                        on_error => sub {
                                            my ($rhandler, $fatal, $msg) = @_;
                                            AE::log error => $msg;
                                            $mode = 0;
                                            $rhandler->destroy();
                                        },
                                        on_read => sub {

                                            my $incomingdata =
                                              $remotehandler->rbuf();

                                            unless (defined($serveriv))
                                            {
                                                $serveriv =
                                                  substr($incomingdata, 0,
                                                         length($iv));
                                                $incomingdata =
                                                  substr($incomingdata,
                                                         length($iv));
                                                if ($self->{method} eq
                                                    'rc4-md5')
                                                {
                                                    my $md = Digest::MD5->new();
                                                    $md->add($key);
                                                    $md->add($serveriv);
                                                    my $decrypt_rc4_key =
                                                      $md->digest();
                                                    Mcrypt::mcrypt_init(
                                                          $decryptor,
                                                          $decrypt_rc4_key, '');
                                                }
                                                else
                                                {
                                                    Mcrypt::mcrypt_init(
                                                               $decryptor, $key,
                                                               $serveriv);
                                                }
                                            }
                                            my $decrypteddata =
                                              Mcrypt::mcrypt_decrypt($decryptor,
                                                                 $incomingdata);
                                            $clienthandler->push_write(
                                                                $decrypteddata);
                                            $remotehandler->{rbuf} = '';
                                        },
                                    );
                                    $stage = 5;
                                }
                                elsif ($cmd == CMD_BIND)
                                {
                                    carp 'BIND Request not supported';
                                    $stage = 0;
                                    $clienthandler->destroy();
                                    return;
                                }
                                elsif ($cmd == CMD_UDPASSOC)
                                {
                                    carp
                                      'UDP ASSOCIATE request not implemented';
                                    $stage = 0;
                                    $clienthandler->destroy();
                                    return;
                                }

                                else
                                {
                                    carp 'Unknown command';
                                    $stage = 0;
                                    $clienthandler->destroy();
                                    return;
                                }
                            }

                            elsif ($stage == 4 or $stage == 5)
                            {
                                my $plaindata = $client_buffer;
                                if ($addr_to_send ne '')
                                {
                                    $plaindata = $addr_to_send . $client_buffer;
                                    if ($self->{method} eq 'rc4-md5')
                                    {
                                        my $md = Digest::MD5->new();
                                        $md->add($key);
                                        $md->add($iv);
                                        my $encrypt_rc4_key = $md->digest();
                                        Mcrypt::mcrypt_init($encryptor,
                                                          $encrypt_rc4_key, '');
                                    }
                                    else
                                    {
                                        Mcrypt::mcrypt_init($encryptor, $key,
                                                            $iv);
                                    }
                                    $addr_to_send = '';
                                }
                                my $encrypteddata =
                                  Mcrypt::mcrypt_encrypt($encryptor,
                                                         $plaindata);
                                my $datatosend;
                                if ($mode == 0)
                                {
                                    $datatosend = $iv . $encrypteddata;
                                    $mode       = 1;
                                }
                                else
                                {
                                    $datatosend = $encrypteddata;
                                }

                                $remotehandler->push_write($datatosend);

                            }
                        }
                        $clienthandler->{rbuf} = '';
                    },
                );
            }
        );
        my $cv = AE::cv;
        $cv->recv();
        return $self;
    }
}
{

    package Net::Shadowsocks::Server;

    # ABSTRACT: Shadowsocks protocol server module.
    use 5.006;
    use strict;
    use warnings;
    use AnyEvent;
    use AnyEvent::Handle;
    use AnyEvent::Socket;
    use Carp;
    use Crypt::Random qw( makerandom_octet );
    use Digest::MD5;
    use Mcrypt;
    use Mcrypt qw(:ALGORITHMS);
    use Mcrypt qw(:MODES);
    use Mcrypt qw(:FUNCS);
    use Net::Shadowsocks qw(_EVP_BytesToKey _initialize_cipher);



    sub new($$$$$$)
    {

        my ($class, %args) = @_;
        my $self = bless {
                          map { ($_ => $args{$_}) }
                            qw(local_address local_port password server server_port method),
                         }, $class;
        if ($self->{server} eq 'localhost')
        {
            undef $self->{server};
        }

        my $tcp_server;
        $tcp_server = AnyEvent::Socket::tcp_server(
            $self->{server},
            $self->{server_port},
            sub {
                my ($client_socket, $client_host, $client_port) = @_;

                #carp "Got new client connection: $client_host:$client_port";
                my $sent_iv = 0;
                my $clientiv;
                my $mode = 0;

                #say $self->{method};
                # say $self->{password};
                my ($encryptor, $decryptor, $key, $iv) =
                  Net::Shadowsocks::_initialize_cipher($self->{method},
                                                       $self->{password});
                my $clienthandler;
                my $remotehandler;
                $clienthandler = AnyEvent::Handle->new(
                    autocork  => 1,
                    keepalive => 1,
                    no_delay  => 1,
                    fh        => $client_socket,
                    on_eof    => sub {
                        my $chandler = shift;
                        AE::log info => "Client: Done.";
                        $chandler->destroy();
                    },
                    on_error => sub {
                        my ($chandler, $fatal, $msg) = @_;
                        AE::log error => $msg;
                        $chandler->destroy();
                    },
                    on_read => sub {
                        my $client_buffer = $clienthandler->rbuf();

                        if ($client_buffer eq '')
                        {
                            return;
                        }
                        else
                        {
                            my $incomingdata = $client_buffer;
                            my $decrypteddata;

                            if (!defined($clientiv))
                            {
                                $clientiv =
                                  substr($client_buffer, 0, length($iv));
                                $incomingdata =
                                  substr($client_buffer, length($iv));
                                if ($self->{method} eq 'rc4-md5')
                                {
                                    my $md = Digest::MD5->new();
                                    $md->add($key);
                                    $md->add($clientiv);
                                    my $decrypt_rc4_key = $md->digest();
                                    Mcrypt::mcrypt_init($decryptor,
                                                        $decrypt_rc4_key, '');
                                }
                                else
                                {
                                    Mcrypt::mcrypt_init($decryptor, $key,
                                                        $clientiv);
                                }
                                $decrypteddata =
                                  Mcrypt::mcrypt_decrypt($decryptor,
                                                         $incomingdata);
                                my $addrtype =
                                  ord(substr($decrypteddata, 0, 1));
                                if (    $addrtype != 1
                                    and $addrtype != 3
                                    and $addrtype != 4)
                                {
                                    carp 'addrtype not supported';
                                    return;
                                }
                                my $dest_addr;
                                my $dest_port;

                                if ($addrtype == 1)
                                {
                                    if (length($decrypteddata) >= 7)
                                    {
                                        $dest_addr =
                                          format_address(
                                                  substr($decrypteddata, 1, 4));
                                        $dest_port =
                                          unpack('n',
                                                 substr($decrypteddata, 5, 2));
                                        $decrypteddata =
                                          substr($decrypteddata, 7);
                                    }
                                    else
                                    {
                                        last;
                                    }
                                }
                                elsif ($addrtype == 3)
                                {
                                    if (length($decrypteddata) > 2)
                                    {
                                        my $addr_len =
                                          ord(substr($decrypteddata, 1, 1));
                                        if (
                                            length($decrypteddata) >=
                                            2 + $addr_len)
                                        {
                                            $dest_addr =
                                              substr($decrypteddata, 2,
                                                     $addr_len);
                                            $dest_port =
                                              unpack(
                                                     "n",
                                                     substr(
                                                            $decrypteddata,
                                                            2 + $addr_len,
                                                            2
                                                           )
                                                    );
                                            $decrypteddata =
                                              substr($decrypteddata,
                                                     4 + $addr_len);
                                        }
                                        else
                                        {
                                            last;
                                        }
                                    }
                                    else
                                    {
                                        last;
                                    }
                                }
                                elsif ($addrtype == 4)
                                {
                                    if (length($decrypteddata) >= 19)
                                    {
                                        $dest_addr =
                                          format_address(
                                                 substr($decrypteddata, 1, 16));
                                        $dest_port =
                                          unpack("n",
                                                 substr($decrypteddata, 17, 2));
                                        $decrypteddata =
                                          substr($decrypteddata, 19);
                                    }
                                    else
                                    {
                                        last;
                                    }
                                }

                                if ($dest_addr eq '')
                                {
                                    last;
                                }
                                $remotehandler = AnyEvent::Handle->new(
                                    autocork   => 1,
                                    keepalive  => 1,
                                    no_delay   => 1,
                                    connect    => [$dest_addr, $dest_port],
                                    on_connect => sub {
                                        my (
                                            $rhandle,  $peerhost,
                                            $peerport, $retry
                                           )
                                          = @_;

                                        unless ($rhandle)
                                        {
                                            carp "couldn't connect: $!";
                                            return;
                                        }
                                    },
                                    on_eof => sub {
                                        my $rhandler = shift;
                                        AE::log info => "Remote: Done.";
                                        $mode = 0;
                                        $rhandler->destroy();
                                    },
                                    on_error => sub {
                                        my ($rhandler, $fatal, $msg) = @_;
                                        AE::log error => $msg;
                                        $mode = 0;
                                        $rhandler->destroy();
                                    },
                                    on_read => sub {
                                        my $remote_buffer =
                                          $remotehandler->rbuf();
                                        my $plaindata = $remote_buffer;
                                        if ($sent_iv == 0)
                                        {
                                            if ($self->{method} eq 'rc4-md5')
                                            {
                                                my $md = Digest::MD5->new();
                                                $md->add($key);
                                                $md->add($iv);
                                                my $encrypt_rc4_key =
                                                  $md->digest();
                                                Mcrypt::mcrypt_init($encryptor,
                                                          $encrypt_rc4_key, '');
                                            }
                                            else
                                            {
                                                Mcrypt::mcrypt_init($encryptor,
                                                                    $key, $iv);
                                            }
                                            $sent_iv = 1;
                                        }
                                        my $encrypteddata =
                                          Mcrypt::mcrypt_encrypt($encryptor,
                                                                 $plaindata);
                                        my $datatosend;
                                        if ($mode == 0)
                                        {
                                            $datatosend = $iv . $encrypteddata;
                                            $mode       = 1;
                                        }
                                        else
                                        {
                                            $datatosend = $encrypteddata;
                                        }
                                        $clienthandler->push_write($datatosend);
                                        $remotehandler->{rbuf} = '';
                                    }
                                );
                            }
                            else
                            {
                                $decrypteddata =
                                  Mcrypt::mcrypt_decrypt($decryptor,
                                                         $incomingdata);
                            }
                            $remotehandler->push_write($decrypteddata);
                            $clienthandler->{rbuf} = '';
                        }
                    }
                );
            },
        );
        my $cv = AE::cv;
        $cv->recv();
        return $self;
    }
}


sub _EVP_BytesToKey($$$$$)
{
    my ($key_len, $iv_len, $salt, $data, $count) = @_;
    my $md_buf = '';
    my $key    = '';
    if ($data eq '')
    {
        return $key;
    }
    my $addmd = 0;

    my $md;
    $md = Digest::MD5->new;
    if ($addmd++ > 0)
    {
        $md->add($md_buf);
    }
    $md->add($data);
    if ($salt ne '')
    {
        $md->add_bits($salt, 64);
    }
    $md_buf = $md->digest();
    for (my $i = 1 ; $i < $count ; $i++)
    {
        $md->reset();
        $md->add($md_buf);
        $md_buf = $md->digest();
    }

    $key = substr($md_buf, 0, $key_len);
    $md_buf = '';
    return $key;
}

sub _initialize_cipher($$)
{
    my $method   = shift;
    my $password = shift;

    #say $method;
    #say $password;
    my $encryptor;
    my $decryptor;
    my $key;
    my $iv;
    if ($method eq 'rc4-md5')
    {
        $encryptor =
          Mcrypt::mcrypt_load(Mcrypt::ARCFOUR, '', Mcrypt::STREAM, '');
        $decryptor =
          Mcrypt::mcrypt_load(Mcrypt::ARCFOUR, '', Mcrypt::STREAM, '');
        $key = Net::Shadowsocks::_EVP_BytesToKey(16, 16, '', $password, 1);
        $iv = makerandom_octet(Length => 16);
    }
    elsif ($method eq 'des-cfb')
    {
        $encryptor = Mcrypt::mcrypt_load(Mcrypt::DES, '', Mcrypt::CFB, '');
        $decryptor = Mcrypt::mcrypt_load(Mcrypt::DES, '', Mcrypt::CFB, '');
        $key = Net::Shadowsocks::_EVP_BytesToKey(8, 8, '', $password, 1);
        $iv = makerandom_octet(Length => 8);
    }
    return $encryptor, $decryptor, $key, $iv;
}


1;    # End of Net::Shadowsocks

__END__

=pod

=encoding UTF-8

=head1 NAME

Net::Shadowsocks - An asynchronous, non-blocking shadowsocks client and server module.

=head1 VERSION

version 0.6.2

=head1 SYNOPSIS

Shadowsocks protocol server module.

=head1 SYNOPSIS

    Shadowsocks protocol client module.

=head1 DESCRIPTION

Net::Shadowsocks is a Perl implementation of the shadowsocks (Chinese: 影梭) 
protocol client and server , Shadowsocks is a secure transport protocol based on 
SOCKS Protocol Version 5 (RFC 1928 ). Currently the only encryption method 
supported is RC4-MD5 which is introduced into shadowsocks Python version 2.2. 

Project website https://osdn.net/projects/ssperl/

Net::Shadowsocks

=head1 VERSION

Version 0.6.2

=head1 SUBROUTINES/METHODS

=head2 new

The C<new> constructor lets you create a new B<Net::Shadowsocks::Client> object.

So no big surprises there...

Returns a new B<Net::Shadowsocks::Client> or dies on error.

example use:

 use Net::Shadowsocks::Client;

    my $foo = Net::Shadowsocks::Client->new(
    local_address => 'localhost',
    local_port => 1491,
    password => '49923641',
    server => 'jp.ssip.club',
    server_port => 23333
    );

This is all you need to do. Take a look at client.pl under eg directory for a compelete example on how to 
use the client module.

=head1 NAME

Net::Shadowsocks::Server

=head1 METHODS

=head2 new

The C<new> constructor lets you create a new B<Net::Shadowsocks::Server> object.

So no big surprises there...

Returns a new B<Net::Shadowsocks::Server> or dies on error.

example use:

    use Net::Shadowsocks::Server;

    my $foo = Net::Shadowsocks::Server->new(
    local_address => 'localhost',
    local_port => 1491,
    password => '49923641',
    server => 'jp.ssip.club',
    server_port => 23333
    );

This is all you need to do. Take a look at server.pl under eg directory for a compelete example on how to 
use the server module.

=head1 AUTHOR

Li ZHOU, C<< <lzh at cpan.org> >>

=head1 BUGS

Please report any bugs or feature requests to C<bug-net-shadowsocks at rt.cpan.org>, or through
the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Net-Shadowsocks>.  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::Shadowsocks

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-Shadowsocks>

=item * AnnoCPAN: Annotated CPAN documentation

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

=item * CPAN Ratings

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

=item * Search CPAN

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

=back

=head1 ACKNOWLEDGEMENTS

=head1 LICENSE AND COPYRIGHT

Copyright 2017 Li ZHOU.

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 AUTHOR

Li ZHOU <lzh@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2017 by Li ZHOU.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
