Local Socket#

This protocol carries the messages over a unix domain socket, for a client on the same machine as the game. It bypasses the network stack, so a client that makes many calls in quick succession completes more of them per physics update. A client that makes one call and then waits runs at the game’s update rate either way.

Note

If a client library is available for your language, you do not need to implement this protocol.

Note

Unix domain sockets are available on Linux, macOS, and Windows 10 1803 and Windows Server 2019 or later.

Connecting#

To use this protocol, add a server in the server window and select Protobuf over local socket as its protocol. The window shows the socket path, which defaults to the path under Default Socket Path.

Open a unix domain socket to that path. Then send the connection handshake. The framing and the rest of the connection are the same as for TCP/IP.

Default Socket Path#

The server and its clients each compute the default path for themselves, by the same rule:

  1. If XDG_RUNTIME_DIR is set and not empty, the path is krpc.sock inside it. On Windows LOCALAPPDATA is read instead, as there is no runtime directory there.

  2. Otherwise the path is krpc-<user>.sock inside /tmp, where <user> is the name of the account running the process. /tmp is fixed, as TMPDIR is set per process. Windows always names a directory in LOCALAPPDATA, and so never reaches this step.

The user name comes from the account database, as USER is unset in a process started without a login shell. A client whose language offers only the environment, and finds no user name there, reports an error.

Path Length and Permissions#

A socket path is limited to 100 bytes, as the operating system copies the address into a fixed size structure. The limit counts bytes rather than characters, so a path using multi-byte characters reaches it sooner.

The permissions on the socket and on the directory holding it control access to the server. XDG_RUNTIME_DIR and LOCALAPPDATA are private to the account they belong to, so a socket placed there is reachable only by that user.

The /tmp fallback socket sits directly in /tmp. Its permissions follow the process umask, which can leave the socket open to the user’s group. Set XDG_RUNTIME_DIR or configure the path where that matters.

Example#

Note

This example shows the protocol, and omits much of the behavior a client library needs, such as handling errors and failed connections. A client library should implement the client specification in its entirety.

The example uses the POSIX socket API, so it runs on Linux and macOS. On Windows, Python’s socket module lacks the address family, and the socket is opened through winsock instead.

The following script connects to the server over a local socket with the name “Example”, calls KRPC.GetStatus and prints the server version. It then ends the connection:

import getpass
import os
import socket

from google.protobuf.internal.decoder import _DecodeVarint
from google.protobuf.internal.encoder import _VarintEncoder

from krpc.schema import KRPC_pb2 as KRPC


def encode_varint(value):
    """Encode an int as a protobuf varint"""
    data = []
    _VarintEncoder()(data.append, value, False)
    return b"".join(data)


def decode_varint(data):
    """Decode a protobuf varint to an int"""
    return _DecodeVarint(data, 0)[0]


def decode_string(data):
    """Decode a string: its length as a varint, then its UTF-8 bytes"""
    size, position = _DecodeVarint(data, 0)
    return data[position : position + size].decode("utf-8")


def send_message(conn, msg):
    """Send a message, prefixed with its size, to a unix domain socket"""
    data = msg.SerializeToString()
    size = encode_varint(len(data))
    conn.sendall(size + data)


def recv_message(conn):
    """Receive a size-prefixed Message from a unix domain socket"""
    # Receive the size of the message data
    data = b""
    while True:
        try:
            data += conn.recv(1)
            size = decode_varint(data)
            break
        except IndexError:
            pass
    # Receive the message data
    data = b""
    while len(data) < size:
        data += conn.recv(size - len(data))
    # Decode the message
    msg = KRPC.Message()
    msg.ParseFromString(data)
    return msg


def default_path():
    """The path the server listens on by default"""
    directory = os.environ.get("XDG_RUNTIME_DIR")
    if directory:
        return os.path.join(directory, "krpc.sock")
    return os.path.join("/tmp", "krpc-" + getpass.getuser() + ".sock")


# Open a unix domain socket to the server
conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
conn.connect(default_path())

# Send a connection request
message = KRPC.Message()
message.connection_request.protocol_version = 2
message.connection_request.client_name = "Example"
send_message(conn, message)

# Receive the connection response
response = recv_message(conn).connection_response

# Check the connection was successful
if response.status != KRPC.ConnectionResponse.OK:
    raise RuntimeError("Connection failed: " + response.message)
if response.protocol_version != 2:
    raise RuntimeError("The server does not support protocol version 2")
print("Connected to the server")

# Invoke the KRPC.GetStatus RPC, in a request with the id 1
message = KRPC.Message()
message.request.id = 1
call = message.request.calls.add()
call.service = "KRPC"
call.procedure = "GetStatus"
send_message(conn, message)

# Receive the response, which carries the id of the request it answers
response = recv_message(conn).response
assert response.id == 1

# Check for an error in the response
if response.HasField("error"):
    raise RuntimeError("ERROR: " + str(response.error))

# Check for an error in the results
assert len(response.results) == 1
if response.results[0].HasField("error"):
    raise RuntimeError("ERROR: " + str(response.results[0].error))

# Decode the return value, a ServerStatus structure sent as a Tuple of its
# fields
status = KRPC.Tuple.FromString(response.results[0].value)

# Print out the server version, the first field
print(decode_string(status.items[0]))

# End the connection with a disconnect, then close the write side
disconnect = KRPC.Disconnect(reason=KRPC.Disconnect.CLOSED)
send_message(conn, KRPC.Message(disconnect=disconnect))
conn.shutdown(socket.SHUT_WR)

# Discard anything still arriving until the server closes its side, or a
# second passes with nothing
conn.settimeout(1)
try:
    while conn.recv(4096):
        pass
except TimeoutError:
    pass
conn.close()