RPC::pServer(3pm)

πŸ“¦
version 0.1005 Β· 2 versions
  • 0.1005 Β· debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking (latest)
  • 0.1005 Β· ubuntu jammy
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

✨ NAME ✨

RPC::pServer β€” Perl extension for writing pRPC servers. πŸ’…

okay bestie, this is the RPC::pServer(3pm) page from the User Contributed Perl Documentation set. part 1, no cap. let's get into it. 🫢


🌸 SYNOPSIS 🌸

use RPC::pServer;

$sock = IO::Socket::INET->new('LocalPort' => 9000,
                              'Proto' => 'tcp',
                              'Listen' = 5,
                              'Reuse' => 1);

$connection = new RPC::pServer('sock' => $sock,
                                    'configFile' => $file,
                                    'funcTable' => $funcTableRef,
                                    # other attributes #
                                   );

while ($running) {
    $connection->Loop();
    if ($connection->error) {
        # Do something
    }
}

πŸ’« DESCRIPTION πŸ’«

pRPC (Perl RPC) is a package that simplifies the writing of Perl based client/server applications. RPC::pServer is the package used on the server side, and you guess what Net::pRPC::Client is for. See Net::pRPC::Client(3) for this part. 😌

pRPC works by defining a set of of functions that may be executed by the client. For example, the server might offer a function "multiply" to the client. Now a function call

@result = $con->Call('multiply', $a, $b);

on the client will be mapped to a corresponding call

multiply($con, $data, $a, $b);

on the server. (See the funcTable description below for $data.) The function call's result will be returned to the client and stored in the array @result. Simple, eh? :-)

πŸ¦‹ Server methods πŸ¦‹

new

The server constructor. Unlike the usual constructors, this one will in general not return immediately, at least not for a server running as a daemon. Instead it will return if a connection is established with a connection object as result. The result will be an error string or the connection object, thus you will typically do a

$con = RPC::pServer->new ( ...);
if (!ref($con)) {
    print "Error $con.\n";
} else {
    # Accept connection
    ...
}

Accept

Deny

After a connection is established, the server should call either of these methods. If he calls Accept(), he should continue with calling the Loop() method for processing the clients requests.

Loop

When a connection is established, the Loop method must be called. It will process the client's requests. If Loop() returns FALSE, an error occurred. It is the main programs task to decide what to do in that case.

Encrypt

This method can be used to get or set the cipher attribute, thus the encryption mode. If the method is passed an argument, the argument will be used as the new encryption mode. ('undef' for no encryption.) In either case the current encryption mode will be returned. Example:

# Get the current encryption mode
$mode = $server->Encrypt();

# Currently disable encryption
$server->Encrypt(undef);

# Switch back to the old mode
$server->Encrypt($mode);

πŸŽ€ Server attributes πŸŽ€

Server attributes will typically be supplied with the "new" constructor.

configFile

RPC::pServer has a builtin authorization mechanism based on a configuration file. If you want to use this mechanism, just supply the name of a configuration file with the attribute configFile and the server will accept or deny connections based on the configuration file.

The authorization scheme is host based, but you may add user based functionality with the user and password attributes. See "CONFIGURATION FILE" below.

client

This attribute is useful in conjunction with the configFile. If the server has authorized a client by using the config file, he will create a hash ref with all the client attributes and store a reference to this hash under the key client. Thus you can easily extend the configuration file for your own purposes, at least as long as host based configuration is sufficient for you.

sock

An object of type IO::Socket, if this program is running as a daemon. An accept() call will be executed on this socket in order to wait for connections. See IO::Socket(3).

An inetd based server should leave this attribute empty: The method will use STDIN and STDOUT instead.

Note: The latter is not yet functionable, I first need to work out how to create an object of type IO::socket for an inetd based server's STDIN and STDOUT. It seems this is currently not supported by IO::Socket.

cipher

This attribute can be used to add encryption quite easily. pRPC is not bound to a certain encryption method, but to a block encryption API. The attribute is an object supporting the methods blocksize, encrypt and decrypt. For example, the modules Crypt::DES and Crypt::IDEA support such an interface.

Do not modify this attribute directly, use the encrypt method instead! However, it is legal to pass the attribute to the constructor.

Example:

use Crypt::DES;
$crypt = DES->new(pack("H*", "0123456789abcdef"));
$client->Encrypt($crypt);

# or, to stop encryption
$client->Encrypt(undef);

You might prefer encryption being client dependent, so there is the additional possibility to setup encryption in the server configuration file. See "CONFIGURATION FILE". Client encryption definitions take precedence over the cipher attribute.

However, you can set or remove encryption on the fly (putting "undef" as attribute value will stop encryption), but you have to be sure, that both sides change the encryption mode.

funcTable

This attribute is a hash reference. The hash keys are the names of methods, that the client may execute on the server. The hash values are hash references (again). The RPC::pServer module will use the key 'code' only: It contains a code reference to the function performing the clients function call. The first argument of the function call will be the connection object itself, the second will be the 'funcTable' value. You are free to use this hash reference in any way you want, the exception being the 'code' key. The function must return a list: In case of errors the results will be the values 0, followed by a textual error message. In case of success, it ought to return nonzero, followed by the result list being sent to the client.

stderr

a value of TRUE will enable logging messages to STDERR, the default is using syslog(); if the stderr attribute is FALSE, you might call openlog() to configure the application name and facility. See Sys::Syslog(3).

debug

this will cause the server to log debugging information about client requests using the Log method. A value of 0 disables debugging.

application

version

user

password

it is part of the pRPC authorization process, that the client must obeye a login procedure where he will pass an application name, a protocol version and optionally a user name and password. These are not used by pRPC, but when the new method returns with a connection object, the main program may use these for additional authorization.

These attributes are read-only.

io

this attribute is a Storable object created for communication with the client. You may use this, for example, when you want to change the encryption mode with Storable::Encrypt(). See Storable(3).


🌈 CONFIGURATION FILE 🌈

The server configuration file is currently not much more than a collection of client names or ip numbers that should be permitted or denied to connect to the server. Any client is represented by a definition like the following:

accept .*\.neckar-alb\.de
    encryption    DES
    key           063fde7982defabc
    encryptModule Crypt::DES

deny .*

In other words a client definition begins with either "accept pattern" or "deny pattern", followed by some client attributes, each of the attributes being on a separate line, followed by the attribute value. The "pattern" is a perl regular expression matching either the clients host name or IP number. In particular this means that you have to escape dots, for example a client with IP number 194.77.118.1 is represented by the pattern "194\.77\.118\.1".

Currently known attributes are:

encryption

key

encryptionModule

These will be used for creating an encryption object which is used for communication with the client, see Storable(3) for details. The object is created with a sequence like

use $encryptionModule;
$cipher = $encryption->new(pack("H*", $key));

encryptionModule defaults to encryption, the reason why we need both is the brain damaged design of the Crypt::IDEA and Crypt::DES modules, which use different module and package names without any obvious reason.

You may add any other attribute you want, thus extending your authorization file. The RPC::pServer module will simply ignore them, but your main program will find them in the client attribute of the RPC::pServer object. This can be used for additional client dependent configuration.

okay so bestie, this is the part where it gets fun πŸ’… β€” the server ships with a whole little toolkit of pre-baked functions so you don't have to hand-roll object plumbing yourself.

✨ PREDEFINED FUNCTIONS ✨

RPC::pServer comes with a handful of predefined methods, and ngl they're designed to make working with objects so much easier. Lowkey the whole point: they let you create objects on the server, hand the client a handle for them, and then work with those handles kind of like they were the real objects. It's giving remote object energy. ✨

Here's the thing though β€” the handle functions all need to share some common data, specifically a hash array where the keys are object handles and the values are the objects. And the real question is: where do you even put that? πŸ‘€ Keeping multithreaded environments in mind, the suggestion is to stash that hash on the stack of the server's main loop. 🫢

So how do the handle functions find it? They peek at the 'handles' attribute of the matching entry in the 'funcTables' hash. (Yeah, see above for the description of that 'funcTables' hash, bestie β€” it's all up there. πŸ‘†)

And there's a whole example of using the handle functions below, don't worry. πŸ’–

NewHandle

This method can be dropped straight into the server's function table. Your client calls it to make objects and get handles back for them. The corresponding entry in the function table must have a classes key: it's a list reference full of class names, and the client is only allowed to create objects from those classes. No sneaking in extras. πŸ™…β€β™€οΈ

NewHandle expects the constructor to return an object when it works out, or 'undef' when it doesn't. Heads up though β€” that is not true in every case. Like, RPC::pServer and Net::pRPC::Client behave differently. In those situations you gotta write your own constructor with special error handling, and StoreHandle (down below πŸ‘‡) is your bestie for that. Constructors that aren't named new are another case where you need StoreHandle directly. πŸŽ€

StoreHandle

So you've made an object on behalf of the client's request, and now you wanna keep it around for later. That's literally StoreHandle's whole job. It hands you back an object handle that you can pass to the client, and the client can then pass the object back to the server to use with CallMethod or UseHandle. 🌸

NewHandle

Yeah, it's back β€” NewHandle is mainly a wrapper around StoreHandle. It creates an object of the given class, passes it to StoreHandle, and returns the result. NewHandle is built for direct use inside the server's function table. πŸ¦‹

UseHandle

The counterpart to StoreHandle, periodt. It takes an object handle that the client passed as an argument and returns the matching object β€” if there is one. If the handle is invalid, you get an 'undef' value back. πŸ’€

CallMethod

This one takes an object handle as an argument plus the name of a method to execute. The method gets invoked on the corresponding object, and the result comes back to you. ✨

There's one special method: 'DESTROY', and it's valid for any object handle. It disposes the object, and the handle becomes invalid. πŸͺ¦

All of the handle functions get shown off in the example that follows. πŸ‘‘


🌈 EXAMPLE 🌈

Enough wasted time β€” spread the example, not the word. :-) Let's write a simple server, like a spreadsheet server. Obviously we do not care about the spreadsheet details (that could totally live in a separate program anyway). The spreadsheet example is chosen because it's obvious that a server like this is dealing with complex data structures. For instance, a "sum" method should be able to add across complete rows, columns, or even rectangular regions of the spreadsheet. And also β€” a spreadsheet could easily be represented by perl data structures: the spreadsheet itself could be a list of lists, and the elements of those inner lists could be hash references, each one describing a column. See? A spreadsheet like that is an ideal object for the Storable(3) class. But now, for something completely different: 🧚

#!/usr/local/bin/perl -wT # Note the -T switch! I mean it!
use 5.0004;               # Yes, this really *is* required.
use strict;               # Always a good choice.

use IO::Socket();
use RPC::pServer;

# Constants
$MY_APPLICATION = "Test Application";
$MY_VERSION = 1.0;

# Functions that the clients may execute; for simplicity
# these aren't designed in an object oriented manner.

# Function returning a simple scalar
sub sum ($$$$$) {
    my($con, $data, $spreadsheet, $from, $to) = @_;
    # Example: $from = A3, $to = B5
    my($sum) = SpreadSheet::Sum($spreadsheet, $from, $to);
    return (1, $sum);
}

# Function returning another spreadsheet, thus a complex object
sub double ($$$$$) {
    my($con, $data, $spreadsheet, $from, $to);
    # Doubles the region given by $from and $to, returns
    # a spreadsheet
    my($newSheet) = SpreadSheet::Double($spreadsheet, $from, $to);
    (1, $newSheet);
}

# Quit function; showing the use of $data
sub quit ($$) {
    my($con, $data) = @_;
    $$data = 0;   # Tell the server's Loop() method, that we
                  # are done.
    (1, "Bye!");
}

# Now we give the handle functions a try. First of all, a
# spreadsheet constructor:
sub spreadsheet ($$$$) {
    my ($con, $data, $rows, $cols) = @_;
    my ($sheet, $handle);
    if (!defined($sheet = SpreadSheet::Empty($rows, $cols))) {
        $con->error = "Cannot create spreadsheet";
        return (0, $con->error);
    }
    if (!defined($handle = StoreHandle($con, $data, $sheet))) {
        return (0, $con->error); # StoreHandle stored error message
    }
    (1, $handle);
}

# Now a similar function to "double", except that a spreadsheet
# is doubled, which is stored locally on the server and not
# remotely on the client
sub rdouble ($$$$$) {
    my($con, $data, $sHandle, $from, $to);
    my($spreadsheet) = UseHandle($con, $data, $sHandle);
    if (!defined($spreadsheet)) {
        return (0, $con->error); # UseHandle stored an error message
    }
    # Doubles the region given by $from and $to, returns
    # a spreadsheet
    my($newSheet) = SpreadSheet::Double($spreadsheet, $from, $to);
    my($handle);
    if (!defined($handle = StoreHandle($con, $data, $newSheet))) {
        return (0, $con->error); # StoreHandle stored error message
    }
    (1, $newSheet);
}

# This function is called for any valid connection to a client
# In a loop it processes the clients requests.
#
# Note, that we are using local data only, thus we should be
# safe in a multithreaded environment. (Of course, no one knows
# about the spreadsheet functions ... ;-)
sub Server ($) {
    my($con) = shift;
    my($con, $configFile, %funcTable);
    my($running) = 1;
    my(%handles) = (); # Note: handle hash is on the local stack

    # First, create the servers function table. Note the
    # references to the handle hash in entries that access
    # the handle functions.
    %funcTable = {
        'sum'         => { 'code' => &sum },
        'double'      => { 'code' => &list },
        'quit'        => { 'code' => &quit,
                           'data' = \$running }
        'spreadsheet' => { 'code' => \&spreadsheet,
                           'handles' => \%handles },
        'rdouble'     => { 'code' => \&rdouble,
                           'handles' = \%handles },

        # An alternative to the 'spreadsheet' entry above;
        'NewHandle'   => { 'code' => \&RPC::pServer::NewHandle,
                           'handles' => \%handles,
                           'classes' => [ 'Spreadsheet' ] },

        # Give client access to *all* (!) spreadsheet methods
        'CallMethod'  => { 'code' => \&RPC::pServer::CallMethod,
                           'handles' => \%handles }
    };

    $con->{'funcTable'} = \%funcTable;

    while($running) {
        if (!$con->Loop()) {
            $con->Log('err', "Exiting.\n"); # Error already logged
            exit 10;
        }
    }
    $con->Log('notice', "Client quits.\n");
    exit 0;
}

# Avoid Zombie ball ...
sub childGone { my $pid = wait; $SIG{CHLD} = \&childGone; }

# Now for main
{
    my ($iAmDaemon, $sock);

    # Process command line arguments ...
    ...

    # If running as daemon: Create a socket object.
    if ($iAmDaemon) {
        $sock = IO::Socket->new('Proto' => 'tcp',
                                'Listen' => SOMAXCONN,
                                'LocalPort' => 'wellKnownPort(42)',
                                'LocalAddr' => Socket::INADDR_ANY
                               );
    } else {
        $sock = undef; # Let RPC::pServer create a sock object
    }

    while (1) {
        # Wait for a client establishing a connection
        my $con = RPC::pServer('sock' => $sock,
                               'configFile' => 'testapp.conf');
        if (!ref($con)) {
            print STDERR "Cannot create server: $con\n";
        } else {
            if ($con->{'application'} ne $MY_APPLICATION) {
                # Whatever this client wants to connect to:
                # It's not us :-)
                $con->Deny("This is a $MY_APPLICATION server. Go away");
            } elsif ($con->{'version'} > $MY_VERSION) {
                # We are running an old version of the protocol :-(
                $con->Deny("Sorry, but this is version $MY_VERSION");
            } elsif (!IsAuthorizedUser($con->{'user'},
                                       $con->{'password'})) {
                $con->Deny("Access denied");
            } else {
                # Ok, we accept the client. Spawn a child and let
                # the child do anything else.
                my $pid = fork();
                if (!defined($pid)) {
                    $con->Deny("Cannot fork: $!");
                } elsif ($pid == 0) {
                    # I am the child
                    $con->Accept("Welcome to the pleasure dome ...");
                    Server();
                }
            }
        }
    }
}

πŸ” SECURITY πŸ”

okay bestie, we have to talk. pRPC based servers are a potential security problem! like, fr fr. I did my best to avoid security problems, but it is more than likely that I missed something. Security was a design goal, but not the design goal. (A well known problem ...) 😭

I highly recommend the following design principles:


πŸ›‘οΈ Protection against "trusted" users

  • perlsec β€” read the perl security FAQ (perldoc perlsec) and use the -T switch. no cap.
  • taintperl β€” use the -T switch. I mean it! πŸ’…
  • Verify data β€” never untaint strings without verification, better verify twice. for example the CallMethod function first checks whether an object handle is in a proper format (currently integer numbers, but don't rely on that, it could change). And if it is? then it will still be verified that an object with the given handle exists. double check energy πŸ‘‘
  • Be restrictive β€” think twice before you give a client access to a function. in particular, think twice before you give a client access to objects via the handle methods: if a client can coerce CallMethod() on an object, he has access to all methods of that object! πŸ’€
  • perlsec β€” and just in case I forgot it: read the perlsec man page. :-) πŸŽ€

🚨 Protection against untrusted users

  • Host based authorization β€” pRPC has a builtin host based authorization scheme; use it! see "CONFIGURATION FILE".
  • User based authorization β€” pRPC has no builtin user based authorization scheme; that doesn't mean that you should not implement one. πŸ™ˆ
  • Encryption β€” using encryption with pRPC is extremely easy. there is absolutely no reason for communicating unencrypted with the clients. even more: I recommend two phase encryption: the first phase is the login phase, where to use a host based key. as soon as the user has authorized, you should switch to a user based key. see the DBD::pNET agent for an example. πŸ”₯

πŸ‘‘ AUTHOR

Jochen Wiedmann, wiedmann@neckar-alb.de


🌈 SEE ALSO

Net::pRPC::Client(3), Storable(3), Sys::Syslog(3)

see DBD::pNET(3) for an example application.


and that's the whole vibe check, bestie πŸ’– this lil page is from perl v5.36.0, dated 2022-12-04, and it's the RPC::pServer(3pm) manual. go forth and taint-check everything πŸ¦‹βœ¨πŸŒΈ

πŸ“¦ where this page comes from