Skip to content

Web Server API

The web server library is a fast, compact web server designed for management web applications and serving device data.

The web server does not attempt to offer ALL HTTP features and functions. Rather, it aims to implement only the required core of HTTP/1.1 and thus deliver a tiny, fast, secure embedded web server that is exceptionally good at serving single page web applications and device data.

The web server supports: HTTP/1.0, HTTP/1.1, TLS/SSL, Action routines, user authentication, sessions, cookie management, request logging, and security sandboxing. The web server uses 80K of code and will run in 150K RAM (without TLS).

The core web services include:

  • HTTP/1.1 protocol engine
  • TLS 1.3 support
  • Non-blocking socket communications
  • Multiple listen endpoints
  • Flexible configuration via a web.json5 file
  • Request routing with access control
  • Binding URLs to C functions for dynamic content rendering
  • Serve static files
  • Configurable redirections
  • Transfer encoding filter
  • Session and cookie management
  • Authentication and User management
  • File upload
  • JSON parser and query engine
  • Sandbox limits and timeouts
  • Paralelism via fiber coroutines

Extensions

Web Embedded web server.
WebUpload File upload structure.

Functions

voidwebAddAccessControlHeader(Web *web)
 Add an Access-Control-Allow-Origin response header for the request host name.
voidwebAddAction(WebHost *host, cchar *url, WebProc fn, cchar *role)
 Add an action callback for a URL prefix.
voidwebAddHeader(Web *web, cchar *key, cchar *value, ...)
 Add a header to the request response.
WebHost*webAllocHost(Json *config)
 Allocate a new host object.
boolwebAuthenticate(Web *web)
 Authenticate a user.
ssizewebBufferUntil(Web *web, cchar *until, ssize limit)
 Read data and buffer until a given pattern or limit is reached.
boolwebCan(Web *web, cchar *role)
 Test if a user possesses the required role.
WebSession*webCreateSession(Web *web)
 Create a login session.
char*webDate(char *buf, time_t when)
 Convert a time to a date string.
char*webDecode(char *str)
 Decode a string using punycode.
voidwebDestroySession(Web *web)
 Destroy the web session object.
char*webEncode(cchar *uri)
 Encode a string using punycode.
intwebError(Web *web, int status, cchar *body, ...)
 Respond to the request with an error.
voidwebExtendTimeout(Web *web, Ticks timeout)
 Extend the request timeout.
voidwebFinalize(Web *web)
 Finalize response output.
voidwebFreeHost(WebHost *host)
 Free a host object.
cchar*webGetConfig(cchar *key, cchar *defaultValue)
 Get a configuration value.
boolwebGetConfigBool(cchar *key, cchar *defaultValue)
 Get a configuration value as a boolean.
intwebGetConfigInt(cchar *key, int defaultValue)
 Get a configuration value as an integer.
cchar*webGetDocs(WebHost *host)
 Get the web documents directory for a host.
char*webGetHostName(Web *web)
 Get the host name of the endpoint serving the request.
WebSession*webGetSession(Web *web, int create)
 Get the session state object for the current request.
char*webGetSessionID(Web *web)
 Get the session ID.
cchar*webGetSessionVar(Web *web, cchar *name, cchar *defaultValue)
 Get a session variable.
cchar*webGetStatusMsg(int status)
 Get a status message corresponding to a HTTP status code.
cchar*webGetVar(Web *web, cchar *name, cchar *defaultValue)
 Get a request variable value.
intwebInit(void)
 Initialize the web module.
boolwebIsAuthenticated(Web *web)
 Test if the user has been authenticated.
voidwebLogin(Web *web, cchar *username, cchar *role)
 Login a user by creating session state.
voidwebLogout(Web *web)
 Logout a user and remove the user login session.
intwebNetError(Web *web, cchar *msg, ...)
 Close the current request and issue no response.
char*webNormalizePath(cchar *path)
 Normalize a URL path.
char*webParseCookie(Web *web, char *name)
 Parse a cookie header string and return a cookie value.
intwebParseUrl(Web *web)
 Parse a URL into its components.
ssizewebRead(Web *web, char *buf, ssize bufsize)
 Read request body data.
ssizewebReadUntil(Web *web, cchar *until, char *buf, ssize bufsize)
 Read request body data until a given pattern is reached.
voidwebRedirect(Web *web, int status, cchar *uri)
 Redirect the client to a new URL.
voidwebRemoveSessionVar(Web *web, cchar *name)
 Remove a session variable.
voidwebRemoveVar(Web *web, cchar *name)
 Remove a request variable value.
intwebResponse(Web *web, int status, cchar *fmt, ...)
 Write a response.
ssizewebSendFile(Web *web, int fd)
 Write a file response.
voidwebSetContentLength(Web *web, ssize len)
 Set the content length for the response.
voidwebSetHook(WebHost *host, WebHook hook)
 Define a request hook.
cchar*webSetSessionVar(Web *web, cchar *name, cchar *fmt, ...)
 Set a session variable name value.
voidwebSetStatus(Web *web, int status)
 Set the response HTTP status code.
cchar*webSetVar(Web *web, cchar *name, cchar *value)
 Set a request variable value.
intwebStartHost(WebHost *host)
 Start listening for requests on the host.
voidwebStopHost(WebHost *host)
 Stop listening for requests on the host.
voidwebTerm(void)
 Initialize the web module.
boolwebValidatePath(cchar *uri)
 Validate a URL.
ssizewebWrite(Web *web, cvoid *buf, ssize bufsize)
 Write response data.
ssizewebWriteFmt(Web *web, cchar *fmt, ...)
 Write string response data.
intwebWriteHeaders(Web *web)
 Write request response headers.

Typedefs

WebActionAction function bound to a URL prefix.
WebHookWebHook callback procedure.
WebHostWeb host structure.
WebProcWebAction callback procedure.
WebRouteRouting object to match a request against a path prefix.

Defines

#defineWEB_CHUNK_DATA   2
 Start of chunk data.
#defineWEB_CHUNK_START   1
 Start of a new chunk.

Web

Web

Embedded web server.

Description:
The web server requires the use of fibers from the portable runtime.
API Stability:
Evolving.
Fields:
uintauthChecked Authentication has been checked.
uintauthenticated User authenticated and roleId defined.
char *boundary Upload file boundary.
ssizeboundaryLen Length of the boundary.
uintchunked Receive transfer chunk encoding state.
uintclose Should the connection be closed after the request completes.
uintcomplete Is the request complete.
cchar *contentDisposition Receive content disposition header value.
cchar *contentType Receive content type header value.
cchar *cookie Request cookie string.
uintcreatingHeaders Are headers being created.
Ticksdeadline Timeout deadline for when the next I/O must complete.
char *error Error string for any request errors.
uintexists Does the requested resource exist.
cchar *ext Request URL extension.
uintformBody Is the current request a POSTed form.
WebHost *host Owning host object.
uinthttp10 Is the current request a HTTP/1.0 request.
uintjsonBody Is the current request a POSTed json request.
WebListen *listen Listening endpoint.
cchar *method Request method in upper case.
cchar *mime Request mime type based on the extension.
char *path Path portion of the request url.
cchar *protocol Request HTTP protocol. Set to HTTP/1.0 or HTTP/1.1.
char *query Request URL query portion.
Json *qvars Parsed query variables.
char *redirect Response redirect location. Used to set the Location header.
char *ref Request URL reference portion.
cchar *role Authorized role.
introleId Index into roles for the authorized role.
WebRoute *route Matching route for this request.
RBuf *rx Receive data buffer.
char *rxHeaderBuf Buffer containing the full request.
char *rxHeaders Request received headers.
ssizerxLen Receive content length.
OffsetrxRemaining Receive data remaining in the next chunk.
struct WebSession *session Session state.
intsignature Index into signature definition for this request.
time_tsince Value of the if-modified-since value in seconds since epoch.
Ticksstarted Time when the request started.
uintstatus Request response HTTP status code.
RBuf *tx Write data buffer.
RHash *txHeaders Output headers.
ssizetxLen Transmit content length.
OffsettxRemaining Transmit data remaining to send.
WebUpload *upload Current uploading file.
cchar *uploadDir Directory to place uploaded files.
RHash *uploads Table of uploaded files for this request.
char *url Request url.
cchar *username Username.
Json *vars Parsed request variables.
uintwroteHeaders Have the response headers been written.

void webAddAccessControlHeader (Web *web)

Add an Access-Control-Allow-Origin response header for the request host name.

Parameters:
webWeb object.
API Stability:
Evolving.
See Also:

void webAddAction (WebHost *host, cchar *url, WebProc fn, cchar *role)

Add an action callback for a URL prefix.

Parameters:
hostHost object.
urlURL prefix to associate with this action.
fnFunction to invoke for requests matching this URL.
roleAuthorized role when the action is invoked.
API Stability:
Evolving.
See Also:

void webAddHeader (Web *web, cchar *key, cchar *value, ...)

Add a header to the request response.

Parameters:
webWeb object.
keyHTTP header name.
valueFormat string for the header value.
...Format arguments.
API Stability:
Evolving.
See Also:

WebHost * webAllocHost (Json *config)

Allocate a new host object.

Parameters:
configJSON configuration for the host.
Returns:
A host object.
API Stability:
Evolving.
See Also:

bool webAuthenticate (Web *web)

Authenticate a user.

Description:
The user is authenticated if required by the selected request route.
Parameters:
webWeb request object.
Returns:
True if the route does not require authentication or the user is authenticated successfully.
API Stability:
Evolving.
See Also:

ssize webBufferUntil (Web *web, cchar *until, ssize limit)

Read data and buffer until a given pattern or limit is reached.

Description:
This reads the data into the buffer, but does not return the data or consume it.
Parameters:
webWeb object.
untilPattern to read until. Set to NULL for no pattern.
limitNumber of bytes of data to read. Set to.
Returns:
The number of bytes read into the buffer. Return zero if no bytes read and negative for errors.
API Stability:
Evolving.
See Also:

bool webCan (Web *web, cchar *role)

Test if a user possesses the required role.

Parameters:
webWeb request object.
roleRequired role.
Returns:
True if the user has the required role.
API Stability:
Evolving.
See Also:

char * webDate (char *buf, time_t when)

Convert a time to a date string.

Parameters:
bufBuffer to hold the generated date string.
whenTimestamp to convert.
Returns:
A reference to the buffer.
API Stability:
Evolving.
See Also:

char * webDecode (char *str)

Decode a string using punycode.

Description:
The string is converted in-situ.
Parameters:
strString to decode.
Returns:
The string reference.
API Stability:
Evolving.
See Also:

char * webEncode (cchar *uri)

Encode a string using punycode.

Description:
The string is converted in-situ.
Parameters:
uriUri to encode.
Returns:
An allocated, escaped URI. Caller must free.
API Stability:
Evolving.
See Also:

int webError (Web *web, int status, cchar *body, ...)

Respond to the request with an error.

Description:
This responds to the request with the given HTTP status and body data.
Parameters:
webWeb object.
statusHTTP response status code.
bodyBody data to send as the response. This is a printf style string.
...Body response arguments.
Returns:
Zero if successful.
API Stability:
Evolving.
See Also:

void webExtendTimeout (Web *web, Ticks timeout)

Extend the request timeout.

Description:
Request duration is bounded by the timeouts.request and timeouts.inactivity limits. You can extend the timeout for a long running request via this call.
Parameters:
webWeb object.
timeoutTimeout in milliseconds use for both the request and inactivity timeouts for this request.
API Stability:
Evolving.
See Also:

void webFinalize (Web *web)

Finalize response output.

Description:
This routine will call webWrite(web, NULL, 0);.
Parameters:
webWeb object.
API Stability:
Evolving.
See Also:

void webFreeHost (WebHost *host)

Free a host object.

Parameters:
hostHost object.
API Stability:
Evolving.
See Also:

cchar * webGetConfig (cchar *key, cchar *defaultValue)

Get a configuration value.

Parameters:
keyProperty key value. May use dot separated properties.
defaultValueDefault value to return if the key is not found.
Returns:
The configuration value or the defaultValue if not found. Caller must not free.
API Stability:
Evolving.
See Also:

bool webGetConfigBool (cchar *key, cchar *defaultValue)

Get a configuration value as a boolean.

Parameters:
keyProperty key value. May use dot separated properties.
defaultValueDefault value to return if the key is not found.
Returns:
The configuration value or the defaultValue if not found. Caller must not free.
API Stability:
Evolving.
See Also:

int webGetConfigInt (cchar *key, int defaultValue)

Get a configuration value as an integer.

Parameters:
keyProperty key value. May use dot separated properties.
defaultValueDefault value to return if the key is not found.
Returns:
The configuration value or the defaultValue if not found. Caller must not free.
API Stability:
Evolving.
See Also:

cchar * webGetDocs (WebHost *host)

Get the web documents directory for a host.

Description:
This is configured via the web.documents configuration property.
Parameters:
hostHost object.
Returns:
The web documents directory.
API Stability:
Evolving.
See Also:

char * webGetHostName (Web *web)

Get the host name of the endpoint serving the request.

Description:
This will return the WebHost name if defined, otherwise it will use the listening endpoint. If all else fails, it will use the socket IP address.
Parameters:
webWeb object.
Returns:
Allocated string containing the host name. Caller must free.
API Stability:
Evolving.
See Also:

cchar * webGetStatusMsg (int status)

Get a status message corresponding to a HTTP status code.

Parameters:
statusHTTP status code.
Returns:
A status message. Caller must not free.
API Stability:
Evolving.
See Also:

cchar * webGetVar (Web *web, cchar *name, cchar *defaultValue)

Get a request variable value.

Parameters:
webWeb object.
nameVariable name.
defaultValueDefault value to return if the variable is not defined.
Returns:
The value of the variable or the default value if not defined.
API Stability:
Evolving.
See Also:

int webInit (void )

Initialize the web module.

Description:
Must call before using Web.
API Stability:
Evolving.
See Also:

bool webIsAuthenticated (Web *web)

Test if the user has been authenticated.

Parameters:
webWeb request object.
Returns:
True if the user has been authenticated.
API Stability:
Evolving.
See Also:

void webLogin (Web *web, cchar *username, cchar *role)

Login a user by creating session state.

Assumes the caller has already authenticated and authorized the user
Parameters:
webWeb request object.
usernameUser name.
roleRequested role.
API Stability:
Evolving.
See Also:

void webLogout (Web *web)

Logout a user and remove the user login session.

Parameters:
webWeb request object.
API Stability:
Evolving.
See Also:

int webNetError (Web *web, cchar *msg, ...)

Close the current request and issue no response.

Description:
This closes the request connection and issues no response. It should be used when a request is received that indicates the connection is compromised.
Parameters:
webWeb object.
msgMessage to the error log. This is a printf style string.
...Message response arguments.
Returns:
Zero if successful.
API Stability:
Evolving.
See Also:

char * webNormalizePath (cchar *path)

Normalize a URL path.

Description:
Normalize a path to remove "./", "../" and redundant separators. This does not make an absolute path and does not map separators or change case. This validates the path and expects it to begin with "/".
Parameters:
pathPath string to normalize.
Returns:
An allocated path. Caller must free.
API Stability:
Evolving.
See Also:

char * webParseCookie (Web *web, char *name)

Parse a cookie header string and return a cookie value.

Parameters:
webWeb object.
nameCookie name to extract.
Returns:
The cookie value or NULL if not defined.
API Stability:
Evolving.
See Also:

int webParseUrl (Web *web)

Parse a URL into its components.

Description:
The parsed components are defined in the Web object including the path, extension (ext),.
Parameters:
webWeb object.
Returns:
Zero if successful.
API Stability:
Evolving.
See Also:

ssize webRead (Web *web, char *buf, ssize bufsize)

Read request body data.

Description:
This routine will read the body data and return the number of bytes read. This routine will block the current fiber if necessary. Other fibers continue to run.
Must only be called from a fiber.
Parameters:
webWeb object.
bufData buffer to read into.
bufsizeSize of the buffer.
Returns:
The number of bytes read. Return < 0 for errors and 0 when all the body data has been read.
API Stability:
Evolving.
See Also:

ssize webReadUntil (Web *web, cchar *until, char *buf, ssize bufsize)

Read request body data until a given pattern is reached.

Description:
This routine will read the body data and return the number of bytes read. This routine will block the current fiber if necessary. Other fibers continue to run.
Must only be called from a fiber.
Parameters:
webWeb object.
untilPattern to read until. Set to NULL for no pattern.
bufData buffer to read into.
bufsizeSize of the buffer.
Returns:
The number of bytes read. Return < 0 for errors and 0 when all the body data has been read.
API Stability:
Internal.
See Also:

void webRedirect (Web *web, int status, cchar *uri)

Redirect the client to a new URL.

Must only be called from a fiber.
Parameters:
webWeb object.
statusHTTP status code. Must set to 301 or 302.
uriURL to redirect the client toward.
API Stability:
Evolving.
See Also:

void webRemoveVar (Web *web, cchar *name)

Remove a request variable value.

Parameters:
webWeb object.
nameVariable name.
API Stability:
Evolving.
See Also:

int webResponse (Web *web, int status, cchar *fmt, ...)

Write a response.

Description:
This routine writes a single plain text response in one API. It will block the current fiber if necessary. Other fibers continue to run. This will set the Content-Type header to text/plain.
Must only be called from a fiber.
Parameters:
webWeb object.
statusHTTP status code.
fmtPrintf style message string.
...Format arguments.
Returns:
The number of bytes written.
API Stability:
Evolving.
See Also:

ssize webSendFile (Web *web, int fd)

Write a file response.

Description:
This routine will read the contents of the open file descriptor and send as a response. This routine will block the current fiber if necessary. Other fibers continue to run.
Must only be called from a fiber.
Parameters:
webWeb object.
fdFile descriptor for an open file or pipe.
Returns:
The number of bytes written.
API Stability:
Evolving.
See Also:

void webSetContentLength (Web *web, ssize len)

Set the content length for the response.

Parameters:
webWeb object.
lenContent length.
API Stability:
Evolving.
See Also:

void webSetHook (WebHost *host, WebHook hook)

Define a request hook.

Description:
The request hook will be invoked for important request events during the lifecycle of processing the request.
Parameters:
hostWebHost object.
hookCallback hook function.
API Stability:
Evolving.
See Also:

void webSetStatus (Web *web, int status)

Set the response HTTP status code.

Parameters:
webWeb object.
statusHTTP status code.
API Stability:
Evolving.
See Also:

cchar * webSetVar (Web *web, cchar *name, cchar *value)

Set a request variable value.

Parameters:
webWeb object.
nameVariable name.
valueValue to set.
Returns:
The value defined in the environment. Caller must NOT free the result.
API Stability:
Evolving.
See Also:

int webStartHost (WebHost *host)

Start listening for requests on the host.

Must only be called from a fiber.
Parameters:
hostHost object.
Returns:
Zero if successful.
API Stability:
Evolving.
See Also:

void webStopHost (WebHost *host)

Stop listening for requests on the host.

Must only be called from a fiber.
Parameters:
hostHost object.
API Stability:
Evolving.
See Also:

void webTerm (void )

Initialize the web module.

API Stability:
Evolving.
See Also:

bool webValidatePath (cchar *uri)

Validate a URL.

Description:
Check a url for invalid characters.
Parameters:
uriUrl path.
Returns:
True if the url contains only valid characters.
API Stability:
Evolving.
See Also:

ssize webWrite (Web *web, cvoid *buf, ssize bufsize)

Write response data.

Description:
This routine will block the current fiber if necessary. Other fibers continue to run. Writing a null buffer or zero bufsize indicates there is no more output. The webFinalize API is a convenience call for this purpose.
Must only be called from a fiber.
Parameters:
webWeb object.
bufBuffer of data to write.
bufsizeSize of the buffer to write.
Returns:
The number of bytes written.
API Stability:
Evolving.
See Also:

ssize webWriteFmt (Web *web, cchar *fmt, ...)

Write string response data.

Description:
This routine will block the current fiber if necessary. Other fibers continue to run.
Must only be called from a fiber.
Parameters:
webWeb object.
fmtPrintf style message string.
...Format arguments.
Returns:
The number of bytes written.
API Stability:
Evolving.
See Also:

int webWriteHeaders (Web *web)

Write request response headers.

Description:
This will write the HTTP response headers. This writes the supplied headers and any required headers if not supplied. This routine will block the current fiber if necessary. Other fibers continue to run.
Must only be called from a fiber.
Parameters:
webWeb object.
Returns:
The number of bytes written.
API Stability:
Evolving.
See Also:

WebUpload

WebUpload

File upload structure.

See Also:
Fields:
char *clientFilename Client side name of the file.
char *contentType Content type.
intfd File descriptor used while writing the upload content.
char *filename Local (temp) name of the file.
char *name Symbolic name for the upload supplied by the client.
ssizesize Uploaded file size.

Functions

WebSession * webCreateSession (Web *web)

Create a login session.

Parameters:
webWeb request object.
Returns:
Allocated session object.
API Stability:
Evolving.

void webDestroySession (Web *web)

Destroy the web session object.

Description:
Useful to be called as part of the user logout process.
Parameters:
webWeb request object.
API Stability:
Prototype.

WebSession * webGetSession (Web *web, int create)

Get the session state object for the current request.

Parameters:
webWeb request object.
createSet to true to create a new session if one does not already exist.
Returns:
Session object.
API Stability:
Evolving.

char * webGetSessionID (Web *web)

Get the session ID.

Parameters:
webWeb request object.
Returns:
The session ID if session state storage is defined for this request. Caller must free.
API Stability:
Evolving.

cchar * webGetSessionVar (Web *web, cchar *name, cchar *defaultValue)

Get a session variable.

Parameters:
webWeb request object.
nameSession variable name.
defaultValueDefault value to return if the variable does not exist.
Returns:
Session variable value or default value if it does not exist.
API Stability:
Evolving.

void webRemoveSessionVar (Web *web, cchar *name)

Remove a session variable.

Parameters:
webWeb request object.
nameSession variable name.
API Stability:
Evolving.

cchar * webSetSessionVar (Web *web, cchar *name, cchar *fmt, ...)

Set a session variable name value.

Parameters:
webWeb request object.
nameSession variable name.
fmtFormat string for the value.
...Format args.
Returns:
The value set for the variable. Caller must not free.
API Stability:
Evolving.

Typedefs

typedef void(* WebHook) (struct Web *web, int event).

WebHook callback procedure.

Parameters:
webWeb object.
eventID of the event.
API Stability:
Evolving.
See Also:

typedef void(* WebProc) (struct Web *web).

WebAction callback procedure.

Parameters:
webWeb object.
API Stability:
Evolving.
See Also:

WebAction

Action function bound to a URL prefix.

API Stability:
Evolving.
Fields:
WebProcfn Function to invoke.
char *match Path prefix.
char *role Role to invoke action.

WebHost

Web host structure.

Description:
The web host defines a web server and its configuration. Multiple web hosts can be created.
Fields:
RList *actions Ordered list of configured actions.
Json *config Web server configuration for this host.
ssizeconnections Number of active connections.
boolfreeConfig Config is allocated and must be freed.
intheaders Base ID for headers in config.
WebHookhook Web notification hook.
intinactivityTimeout Timeout for inactivity on a connection.
cchar *index Index file to use for directory requests.
RList *listeners Listening endpoints for this host.
int64maxBody Max size of POST request.
int64maxConnections Max number of connections.
int64maxHeader Max header size.
int64maxSessions Max number of sessions.
int64maxUpload Max size of file upload.
RHash *mimeTypes Mime types indexed by extension.
cchar *name Host name to use in canonical redirects.
intparseTimeout Timeout while parsing a request.
boolremoveUploads Remove uploads when request completes (default).
intrequestTimeout Total request timeout.
introles Base ID of roles in config.
RList *routes Ordered list of configured routes.
cchar *sameSite Cookie same site property.
REventsessionEvent Session timer event.
RHash *sessions Client session state.
intsessionTimeout Inactivity timeout for session state.
cchar *uploadDir Directory to receive uploaded files.
RHash *users Hash table of users.
RList *webs Active web requests for this host.

WebRoute

Routing object to match a request against a path prefix.

API Stability:
Evolving.
Fields:
boolexact Exact match vs prefix match. If trailing "/" in route.
char *match Path prefix.
cchar *redirect Redirection if not authorized.
cchar *role Required user role.