Network Services User's Guide

Table of Contents

1. Overview

The Network Services (NS) Component provides a set of cross-platform libraries that provide common services related to networking.

At its core is the SlNetSock library that insulates users from the differences between network stacks. For example, users can call SlNetSock_socket() to create a network socket, and that will work whether your network stack is the MSP432E4’s NDK, the CC32XX’s WiFi driver, a Linux-based network stack, or some other.

SlNetSock also provides portable TLS APIs, enabling users to create TLS-aware applications that aren’t bound to a particular network stack or security library. Users who want to bring their own TLS-of-choice-on-top, can ignore the TLS-related SlNetSock APIs and configure their own TLS stack to sit above the [non-secure] SlNetSock APIs.

NS also provides a growing number of application layer networking protocols - such as HTTP/MQTT/SNTP clients, and others. These libraries are inherently portable, as they’re built upon the SlNetSock APIs.

2. SlNetSock

The SlNetSock Module was created to provide a portable, familiar network socket API that supports multiple network stacks, as well as encompasses network TLS security.

2.1 API Reference Guide

The detailed description of the SlNetSock APIs can be found in the API Reference Guides:

2.2 Usage

To use the SlNetSock APIs, the application should include its header file as follows:

#include <ti/net/slnetsock.h>

2.3 Examples

Example pseudocode can also be found in the API Reference Guide:

SlNetSock API Reference Guide

3. HTTPServer

The HTTPServer module enables developers to embed a small HTTP server in an application.

Features

Overview

The HTTPServer module provides a small set of functions to manage one or more instances of an HTTP server. The actual functionality corresponding to each client-specified URL is provided through URL Handler modules that implement the URLHandler interface, described below. It is expected that users will write custom URL Handlers for their systems. The httpserver example illustrates the basics needed to handle most HTTP requests.

The basic flow of managing an HTTP server is shown in the pseudo code below. (For clarity, return values are ignored - in a real application, these should be checked for errors.)

#include <arpa/inet.h>
#include <netinet/in.h>

#include <ti/net/http/httpserver.h>
#include <ti/net/http/urlhandler.h>

#define NUM_URL_HANDLERS (1)

URLHandler_Setup handlerTable[] = {
    {
        NULL,
        URLFile_create,
        URLFile_delete,
        URLFile_process,
        NULL,
        NULL
    },
};

void * serverTaskFxn(void *arg0)
{
    HTTPServer_Handle srv;
    struct sockaddr_in addr;

    srv = HTTPServer_create(handlerTable, NUM_URL_HANDLERS, NULL);

    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(80);

    HTTPServer_serveSelect(srv, (struct sockaddr *)&addr, sizeof(addr), BACKLOG);

    HTTPServer_delete(&srv);
}

int main()
{
    HTTPServer_init();

    Task_create(serverTaskFxn, ...);

    BIOS_start();
}

The HTTPServer module functions are blocking, specifically HTTPServer_serveSelect() in the example above. This means the function will not return until it completes, so for typical usage, a task must be created for each HTTP server instance, as shown in main(). The HTTPServer_init() function must be called before using any other HTTPServer functions.

The HTTPServer_serveSelect function will not return until either an error occurs (network outage) or a stop request is made from another thread using HTTPServer_stop(). The return value from the server functions indicates the reason for exiting. After a server instance has returned, it can be deleted using HTTPServer_delete().

A server instance is created using HTTPServer_create() and specifying a table (array) of URL Handlers. You can create a server with no handlers, but then every HTTP client request will result in a 404 - not found error. This can be useful as an initial simple test case.

The HTTPServer_Params structure provides alternate parameter values for the created server’s operation:

After a server instance is created, the actual serving operation is done via:

3.2 URL Handlers

URL Handlers provide the actual processing of client requests. By separating this processing from the base server in the HTTPServer module, applications can decide exactly how much or how little functionality is required - no response policy is provided in the base server. In a typical application, several URL Handlers could be used:

For each client request received, the server internally loops over all URL Handlers until a handler indicates it has “handled” the request. If no match is found, a “404 - not found” error is returned to the client.

for (i = 0; i < numURLHandlers; i++) {
    if (urlhandler[i].process()) {
        break;
    }
}

This means that the ordering of URL Handlers can be important if there are multiple URL Handlers capable of handling certain URLs.

3.2.1 URL Handler Interface

Each URL Handler has the option to implement any of a set of function pointers defined in the urlhandler.h header file.

typedef URLHandler_Handle (*URLHandler_CreateFxn)(void *params,
                                                  URLHandler_Session session);

typedef void (*URLHandler_DeleteFxn)(URLHandler_Handle *u);
typedef int (*URLHandler_ProcessFxn)(URLHandler_Handle u, int method,
                                     const char *url, const char *urlArgs,
                                     int contentLength, int s);
typedef void (*URLHandler_ScanFieldFxn)(URLHandler_Handle u, int method,
                                        const char *url, const char *field);

These function pointers, along with the HTTPServer_Params structure, make up the URLHandler_Setup structure that is passed into the HTTPServer_create() function.

Every time a client connects to an HTTPServer server instance, a new instance of each URL Handler is created by calling each Handler’s corresponding URLHandler_create() function. This instance will persist for the duration of the client session; i.e., as long as the socket connection persists. When the client disconnects (or is disconnected by the server), the server will delete the handler instance by calling the corresponding delete() function.

For many simple URL Handlers, there will be no ‘state’ needed for a client session, so a create function does not need to be provided. If the URL Handler requires state to be stored, a structure of the user’s choosing needs to be provided. The create() function should allocate memory for the structure and take care of any initialization, before casting the structure to a URLHandler_Handle and returning the pointer to the allocated memory. This handle will be passed around to the other user-defined functions: process(), scan(), and send(). It should be casted back to the user-defined type for storing state before being accessed. The delete() function should clean up the storage structure, i.e., freeing any memory allocated for the structure.

URLHandler_Handle MyURLHandler_create(void *params, URLHandler_Session session)
{
    stateStruct *state = malloc(sizeof(stateStruct));

    if (state)
    {
        state->field1 = ...;
        state->field2 = ...;
        .
        .
        .
    }
    return (URLHandler_Handle)state;
}

Some URL Handlers may provide some parameterization at run-time. This is supported through the first argument of the create() function. This void pointer is supplied via the first field of the URLHandler_Setup structure passed to HTTPServer_create(). A URL Handler can define a structure to hold whatever parameters needed. Users then supply their desired values and pass the pointer to the structure via the URLHandler_Setup structure.

The process() function of a URL Handler can differentiate between requests by examining the URL as well as the HTTP method used (GET, POST, PUT, etc.). The behavior thereafter is up to the user. The server’s response can make use of the functions provided in httpserver_send.c.

int MyURLHandler_process(URLHandler_Handle h, int method, const char *url,
                         const char *urlArgs, int contentLength, int ssock) {
    int processingStatus = URLHandler_ENOTHANDLED;
    int httpRetCode;    // Our return code
    char *responseBody; // Our response

    if (strcmp(url, "/index.html") == 0) {
        if (method == URLHandler_GET) {
            // How was this request handled
            processingStatus = URLHandler_EHANDLED;

            // Our response
            responseBody     = "Index Page";

            // HTTP response status code
            httpRetCode      = HTTP_SC_OK;

            // Send the response ()
            HTTPServer_SendResponse(ssock, httpRetCode, NULL, 0,
                                    strlen(responseBody) + 1, responseBody);
        }
        else {
            processingStatus = URLHandler_EERROR_HANDLED;
        }

        return processingStatus;
    }

Server Architecture


The httpserver example provided with your SDK has a more complete demonstration of a URL Handler that returns static strings to a client.