Skip to main content

Multiple instances in a single process

Running multiple instances of NanoSSL servers within a single process can be beneficial for handling various services on different ports. This guide outlines the steps necessary to initialize and configure multiple servers to run in the same process namespace.

Initial setup

Before any server instances are launched, it’s crucial to perform the global configuration needed for NanoSSL. This includes calling the SSL_init() function and setting up the SSL_settings, which define the global context for all NanoSSL operations. These steps must be completed by the main thread or process prior to initiating any server threads.

Launching server threads

Once the global context is ready, the application can spawn child threads. Each thread can then create its own listening socket on a distinct port by calling the TCP_ACCEPT_SOCKET function. To handle incoming SSL connections, the threads should invoke SSL_acceptConnection.

Example process

To illustrate, here is a high-level example of starting two NanoSSL server instances listening on ports 1440 and 1441.

  1. Initialize NanoSSL globally:

    SSL_init();
  2. Spawn threads to handle individual server instances:

    for (int i = 0; i < 2; i++) {
        RTOS_createThread(SSL_EXAMPLE_startOneServer, (void*)((usize)ssls_ServerPort + i), SSL_MAIN, &tid);
    }
  3. In the spawned function SSL_EXAMPLE_startOneServer, perform the TCP accept:

    status = TCP_ACCEPT_SOCKET(&socketClient, mListenSocket, &needToDie);
  4. For each accepted connection, spawn a thread to handle the SSL handshake:

    RTOS_createThread(startHttpsThread, (void*)((usize)socketClient), SSL_SERVER_SESSION, &tid);
  5. In the startHttpsThread, establish the SSL connection:

    connectionInstance = SSL_acceptConnection(socketClient, pSslCertStore);

Validation

To ensure the servers are correctly set up, the following commands can be used to check if the specified ports are listening for connections:

lsof -nP -i4TCP:1440 | grep LISTEN
lsof -nP -i4TCP:1441 | grep LISTEN

Connecting to these ports using a browser should result in a successful SSL handshake, indicating the servers are operational.

By following these steps, developers can effectively manage multiple SSL servers within a single process, allowing for efficient resource usage and centralized process management.