Learnt something new today.

Was looking for a way to wrap up standalone programs and spinning them up as network services by splicing stdin, stdout and stderr descriptors with the network socket file descriptors. Before ending up reinventing the wheel, I found that xinetd (extended Internet daemon) did what exactly I was looking for.

We have a simple echo server here.

#!/usr/bin/python3
while True:
    print(input())

It reads from stdin and writes whatever has been read to stdout.

Let us first create the configuration file for this service, I would like to call dumbecho

/etc/xinetd.d/dumbecho

service dumbecho
{
    type            = UNLISTED
    socket_type     = stream
    wait            = no
    user            = gtux
    group           = gtux
    server          = /home/gtux/dumbecho.py
    log_on_failure  += USERID HOST
    disable         = no
    port            = 1593
}

user, group, server and port are the parameters which needs to be changed for new TCP services. Rest, we can leave it as such.

You can also specify server_args to specify additional command line options before executing whatever is present in the server field. man pages for xinetd.conf is sure an interesting read.

A simple

systemctl restart xinetd

and then

netstat -nltp

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -                   
tcp        0      0 0.0.0.0:1593            0.0.0.0:*               LISTEN      -                   
tcp        0      0 127.0.0.1:9050          0.0.0.0:*               LISTEN      -                   
tcp6       0      0 :::22                   :::*                    LISTEN      -                   

And voila, our TCP server is online!

For each and every request, a fork is made and dumbecho.py is executed. A painless way of securely running a simple forking TCP server.