goahead html5,GoAhead API

GoAhead Native API

Extensions

GoAhead request structure.

GoAhead Authentication.

A WebsBuf (ring queue) allows maximum utilization of memory for data storage and is ideal for input/output buffering.

Hash table entry structure.

Request route structure.

GoAhead Web Server Runtime.

Session state storage.

Socket control structure.

File upload structure.

Functions

void

Assure that an assert condition is true.

Add a trailing null to the buffer.

Adjust the endp pointer by the specified size.

Adjust the start (servp) reference.

Compact the data in the buffer and move to the start of the buffer.

intbufCreate(WebsBuf *bp, int increment, int maxsize)

Create a buffer.

Flush all data in the buffer and reset the pointers.

Free allocated storage for the buffer.

Copy a block of from the buffer and adjust the servp.

Return the maximum number of bytes the buffer can provide via a single block copy.

Get a character from the buffer and increment the servp.

Grow the buffer by at least the required amount of room.

Insert a character to the buffer before the servp position and decrement the servp.

Get the length of available data in the buffer.

bufPut(WebsBuf *bp, cchar *fmt, ...) PRINTF_ATTRIBUTE(2

Append a formatted string to the buffer at the endp position and increment the endp.

Put a block to the buffer.

Append a string to the buffer at the endp position and increment the endp.

int

Append a character to the buffer at the endp position and increment the endp.

Reset the buffer pointers to the start of the buffer if empty.

Determine the room available in the buffer.

Get a reference to the start of buffer data.

voiderror(cchar *fmt, ...)

Emit an error message.

char*fmt(char *buf, ssize maxSize, cchar *format, ...)

Format a string into a static buffer.

Create a hash table.

Delete a key by name.

Enter a new key and value into the hash table.

Start walking the hash keys by returning the first key entry in the hash.

Free a hash table.

Lookup a name in the hash table.

Lookup a name in the hash table and return a symbol reference.

Continue walking the hash keys by returning the next key entry in the hash.

Convert a hex string to an integer.

char*itosbuf(char *buf, ssize size, int64 value, int radix)

Convert an integer to a string buffer.

void

Close the log logging module.

Get the log callback.

int

Open the log logging module.

Set a log callback.

Set the filename to save logging output.

voidlogmsgProc(int level, cchar *fmt, ...)

Emit a message to the log.

Compare strings ignoring case.

Compare strings ignoring case.

char*

Clone a string.

Compare strings.

scopy(char *dest, ssize destMax, cchar *src)

Copy a string.

char*sfmt(cchar *format, ...)

Format a string.

char*sfmtv(cchar *format, va_list args)

Format a string with varargs.

Return the length of a string.

char*slower(char *str)

Convert a string to lower case.

Compare strings.

Compare strings ignoring case.

Clone a substring.

Compare strings.

sncopy(char *dest, ssize destMax, cchar *src, ssize count)

Copy characters from a string.

intsocketAddress(struct sockaddr *addr, int addrlen, char *ipbuf, int ipLen, int *port)

Extract the numerical IP address and port for the given socket info.

Determine if an IP address is an IPv6 address.

intsocketAlloc(cchar *host, int port, SocketAccept accept, int flags)

Allocate a socket object.

Close the socket module.

Close a socket connection.

intsocketConnect(cchar *host, int port, int flags)

Connect to a server and create a new socket.

voidsocketCreateHandler(int sid, int mask, SocketHandler handler, void *arg)

Create a socket handler that will be invoked when I/O events occur.

Delete a socket handler created via socketCreateHandler.

Determine if the socket is at end-of-file for input.

void

Free (and close) the socket.

Get the current blocking mode.

Get the error code for the last socket operation on this thread.

Get the underlying socket operating system socket/file handle.

Get the list of sockets.

Get the IP port associated with this socket.

Indicate if the system has a dual IPv4 and IPv6 stack.

Indicate if the system has IPv6 support.

Indicate that the application layer has buffered data for the socket.

intsocketInfo(cchar *ip, int port, int *family, int *protocol, struct sockaddr_storage *addr, Socklen *addrlen)

Get a socket address structure for the specified IP:Port.

Determine if a socket is bound to an IPv6 address.

intsocketListen(cchar *host, int port, SocketAccept accept, int flags)

Open a listening socket.

Open the socket module.

intsocketParseAddress(cchar *ipAddrPort, char **pip, int *pport, int *secure, int defaultPort)

Parse an IP address into its constituent parts.

Process pending socket I/O events.

Return the socket object for the socket ID.

socketRead(int sid, void *buf, ssize len)

Read data from a socket.

void

Register interest in socket I/OEvents.

Request that the socket be reserviced.

intsocketSelect(int sid, int timeout)

Wait for I/O on a socket.

intsocketSetBlock(int sid, int on)

Set the socket blocking mode.

void

Set the error code for the last socket operation on this thread.

Set the socket delay mode.

Wait for a socket I/O event.

socketWrite(int sid, void *buf, ssize len)

Write data to the socket.

void

Close the ssl module.

Free a ssl connection associated with a request.

int

Open the ssl module.

Read data from a secure socket.

Upgrade a request connection to utilize SSL.

WRite data to a secure socket.

char*ssplit(char *str, cchar *delim, char **last)

Split a string at a delimiter.

Test if the string starts with a given pattern.

char*stok(char *str, cchar *delim, char **last)

Tokenize a string.

char*strim(char *str, cchar *set, int where)

Trim a string.

char*supper(char *str)

Convert a string to upper case.

voidtraceProc(int level, cchar *fmt, ...)

Emit a debug trace message to the log.

Free any allocated string in a value.

Create an integer value.

Create an string value.

Create an symbol value containing an object reference.

void*

Allocate a block of the requested size.

int

Allocate a handle from a map.

intwallocObject(void *map, int *max, int size)

Allocate an object in a halloc map.

Close the GoAhead memory allocator.

void*

Duplicate memory.

intwebsAccept(int sid, cchar *ipaddr, int port, int listenSid)

Accept a new connection.

Open the action handler.

Add a role.

Add a route to the routing tables.

Add a user.

intwebsAlloc(int sid)

Allocate a new Webs object.

Test if a user possesses the required ability.

Authenticate a user.

Test if a user possesses the required ability.

Cancel the request timeout.

CGI handler service callback.

Open the CGI handler.

Poll for output from CGI processes and output.

websCheckPassword(cchar *plainTextPassword, cchar *passwordHash)

Check a plain-text password against the defined hashed password.

void

Close the core GoAhead web server module.

Close the authentication module.

Close an open file.

Close the route module.

Compare a request variable.

Compute the abilities for all users by resolving roles into abilities.

Consume input from the request input buffer.

Test if a user possesses the required ability.

char*websCryptPassword(cchar *password, cchar *salt, int rounds)

Encrypt a password using the Blowfish algorithm.

char*

Decode the string using base-64 encoding.

char*websDecode64Block(char *str, ssize *len, int flags)

Decode a block using base-46 encoding.

voidwebsDecodeUrl(char *decoded, char *input, ssize len)

Decode a URL expanding NN encoding.

int

Define an action callback for use with the action handler.

Define a request handler.

Define a Javscript native function.

Destroy the webs session object.

Complete a request.

char*

Encode a string using base-64 encoding.

Encode a block using base-64 encoding.

voidwebsError(Webs *wp, int code, cchar *fmt, ...)

Complete a request with an error response.

Get a message for a HTTP status code.

Escape unsafe characters in a string.

Open and initialize the file handler.

Flush buffered transmit data and compact the transmit buffer to make room for more data.

Free the webs request object.

Free file upload data structures.

Close the file system module.

Open the file system module.

Get the background execution flag.

Get a unique temporary filename for CGI communications.

Get the request cookie if supplied.

Get a date as a string.

Get the debug flag.

Get the base file directory for a request.

Get the GoAhead base documents directory.

Get the request EOF status.

Get the request URI extension.

Get the request filename.

Get the request host.

Get the request interface address.

Get the default index document name.

Get the current trace log level.

Get the request method.

Get the request password.

Set the password store verify callback.

Get the request path.

Get the request TCP/IP port.

Get the request HTTP protocol.

Get the request query component.

int

Get some random data.

Get the roles hash.

Get the server host name.

Get the server IP address.

Get the server IP address with port number.

Get the server host name with port number.

Get the session state object for the current request.

Get the session ID.

Get a session variable.

Get the hash of uploaded files for the request.

Get the request URI.

Get the client User-Agent HTTP header.

Get the request username.

Get the users hash.

Get a request variable.

Open the Javascript module.

intwebsJstWrite(int jid, Webs *wp, int argc, char **argv)

Write data to the response.

Listen on a TCP/IP address endpoint.

Load routing tables from the specified filename.

Login a user by verifying the login credentials.

Logout a user and remove the user login session.

Open the file upload filter.

Lookup if a user exists.

Get an MD5 digest of a string.

Get an MD5 digest of a block and optionally prepend a prefix.

char*websMakePassword(cchar *password, int saltLength, int rounds)

Make a password hash for a plain-text password using the Blowfish algorithm.

Make salt for adding to a password.

Normalize a URI path.

Take not of the request activity and mark the time.

intwebsOpen(cchar *documents, cchar *routes)

Open the web server.

intwebsOpenAuth(int minimal)

Open the authentication module.

intwebsOpenFile(cchar *path, int flags, int mode)

Open the web page document for the current request.

Open the routing module.

Open the options handler.

Close the O/S dependent code.

Open the O/S dependent code.

Close the document page.

Test if the document page for the request corresponds to a directory.

intwebsPageOpen(Webs *wp, int mode, int perms)

Open a web page document for a request.

Read data from the request page document.

voidwebsPageSeek(Webs *wp, Offset offset, int origin)

Seek to a position in the request page document.

Get file status for the current request document.

intwebsParseDateTime(WebsTime *time, cchar *date, struct tm *defaults)

Parse a date/time string.

Process CGI request body data.

Process upload data for form, multipart mime file upload.

Pump the state machine.

websReadFile(int fd, char *buf, ssize size)

Read data from an open file.

Get a password from the terminal console.

Read all the data from a file.

Redirect the client to a new URL.

Redirect the client to a new URI.

Remove a role from the system.

Remove a route from the routing tables.

Remove a session variable.

Remove a user from the system.

voidwebsResponse(Webs *wp, int status, cchar *msg)

Create and send a request response.

voidwebsRestartEvent(int id, int delay)

Restart an event.

Rewrite a request.

Route a request.

Run due events.

Run a request handler.

Close the runtime code.

Open the runtime code.

websSeekFile(int fd, Offset offset, int origin)

Seek to a position in the current request page document.

intwebsServer(cchar *endpoint, cchar *documents)

One line embedding API.

void

Service I/O events until finished.

Set the background processing flag.

Define a background write I/O event callback.

voidwebsSetCookie(Webs *wp, cchar *name, cchar *value, cchar *path, cchar *domain, int lifespan, int flags)

Define a cookie to include in the response.

void

Set the debug processing flag.

Set the web documents directory.

Create the CGI environment variables for the current request.

Create request variables for query and POST body data.

Define the host name for the server.

Create and send a request response.

Define the host IP address.

void

Set the current trace log level.

Define a global memory allocation notifier.

Set the password store verify callback.

Create request variables for query string data.

Set route authentication scheme.

Configure a route by adding matching criteria.

Set a session variable name value.

voidwebsSetStatus(Webs *wp, int status)

Set the response HTTP status code.

Set the response body content length.

Set a password for the user.

Define the set of roles for a user.

Set a request variable to a string value.

Set a request variable to a formatted string value.

intwebsStartEvent(int delay, WebsEventProc proc, void *data)

Start a callback event.

Get file status for a file.

Stop an event.

Create a temporary filename This does not guarantee the filename is unique or that it is not already in use by another application.

Test if a request variable is defined.

Close the date/time parsing module.

Open the date/time parsing module.

Open the file upload filter.

intwebsUrlParse(cchar *url, char **buf, char **protocol, char **host, char **port, char **path, char **ext, char **reference, char **query)

Parse a URL into its components.

Test if a webs object is valid.

Test if a URI is using only valid characters Note this does not test if the URI is fully legal.

Validate a URI path as expected in a HTTP request line.

User password verification routine from a custom password back-end store.

User password verification routine from auth.txt.

Write data to the response.

Write a block of data to the response.

Signify the end of the response headers.

Write data to the open file.

Write a response header.

void

Write a set of standard response headers.

Write a block of data to the network.

voidwfree(void *blk)

Free an allocated block of memory.

intwfreeHandle(void *map, int handle)

Free a handle in the map.

intwopenAlloc(void *buf, int bufsize, int flags)

Initialize the walloc module.

void*wrealloc(void *blk, ssize newsize)

Reallocate a block of memory and grow its size.

Typedefs

Socket accept callback.

Socket I/O callback.

Action callback.

Callback to prompt the user for their password.

Error code list.

Callback function for events.

File information structure.

GoAhead handler object.

GoAhead handler close to release memory prior to shutdown.

GoAhead handler service callback.

Hash table ID returned by hashCreate.

Javascript native function.

Callback for emitting trace log output.

Mime type list.

Callback to parse authentication details submitted with the web request.

Role definition structure.

Compiled Rom Page Index.

File status structure.

System native time type.

User definition structure.

Value union to store primitive value types.

Callback to verify the username and password.

Callback for write I/O events.

Defines

The request has been accepted and processing is continuing.

The server cannot act as a gateway for the given request.

The request HTTP method was not supported by the resource.

The request is malformed.

The server does not support the HTTP protocol version.

The server had a communications error responding to the client.

The request had a conflict in the request headers and URI.

Continue with request, only partial content transmitted.

The request has completed and a new resource was created.

The server cannot satisfy the Expect header requirements.

The request was legal, but the server refuses to process.

The server gateway timed out waiting for the upstream server.

The requested resource is no longer available.

The server has insufficient storage to complete the request.

Server processing or configuration error.

The request did not specify a required content length.

The requested URI has moved permanently to a new location.

The URI has moved temporarily to a new location.

The request has completed and there is no response to send.

The connection was closed with no response to the client.

The requested resource cannot generate the required content.

The request has completed but content may be from another source.

The requested resource was not found.

The server does not recognize the request or method.

The requested resource has changed since the last request.

The request completed successfully.

The request has completed and is returning partial content.

Reserved for future use.

The server cannot satisfy one of the request preconditions.

The request content range does not exist for the resource.

The server timed out waiting for the request to complete.

The request is too large for the server to process.

The request URI is too long for the server to process.

The request has completed with no content.

The requested URI can be found at another URI location.

The server is currently unavailable or overloaded.

The request should be repeated at another URI location.

Authentication for the request has failed.

The request media type is not supported by the server or resource.

The requested resource must be accessed via the location proxy.

#define

Maximum IP address size.

Issue the request again.

Use async connect.

Use blocking I/O.

Message pending on this socket.

Message pending on this socket.

Socket is closing.

Connect in progress.

Socket connection was reset.

#define

Seen end of file.

Interested in exceptions.

Doing SSL handshake.

Call was interrupted.

Invalid.

Socket is server listener.

Network is down.

Disable Nagle algorithm.

Max Port size.

Make socket readable.

Socket needs re-servicing.

Socket has been reset.

Socket would block on I/O.

Make socket writable.

Allocate strings using malloc.

#definevalue_numeric   (t >= byteint && t <= big)

The value is a numeric type.

#definevalue_ok   (t > undefined && t <= symbol)

The value is valid supported type.

#definevalue_str   (t >= string && t <= bytes)

The value is a string type.

TLS connection accepted.

Originated from assert.

Beginning state.

Start of chunk data.

Preparing tx chunk header.

Start of a new chunk.

Data is not transfer-chunk encoded.

Currently chunking output body data.

#define

Close connection.

Connection closed, ready to free.

Mask valid status codes.

Request complete.

Configuration settings trace level.

Ready for body data.

Cookie supplied in request.

Flag for websSetCookie for http cookies (http only).

Flag for websSetCookie for SameSite=Lax.

Flag for websSetCookie for SameSite=Strict.

Flag for websSetCookie for secure cookies (https only).

Decode base 64 blocks up to a NULL or equals.

Standard logging trace levels are 0 to 9 with 0 being the most verbose.

Originated from error.

Output is finalized.

#define

Request is a form (url encoded data).

Headers have been created and buffered.

#define

Request is using HTTP/1.1.

#define

Request has a JSON payload.

HTTP/1.1 keep alive.

Level mask.

#define

Originated from logmsg.

Maximum number of listen endpoints.

Default maximum password.

#define

Don't write error to log.

#define

Raw message output.

Ready to route and start handler.

#define

Restart route matching.

Started tracing the response.

Processing request.

#define

Connection uses SSL.

General small hash size.

Originated from trace.

Flag for strim to trim from both the start and the end of the string.

Flag for strim to trim from the end of the string.

Flag for strim to trim from the start of the string.

#define

Multipart-mime file upload.

Query and body form vars added.

Highest level of trace.

Soft warning trace level.

Webs

Webs

GoAhead request structure.

Fields:char *authDetailsHttp header auth details.

char *authResponseOutgoing auth header.

char *authTypeAuthorization type (Basic/DAA).

char *boundaryMime boundary (static).

ssizeboundaryLenBoundary length.

intcgifdFile handle for CGI program input.

char *cgiStdinFilename for CGI program input.

WebsBufchunkbufPre-chunking data buffer.

char *clientFilenameCurrent file filename.

intcodeResponse status code.

uintconnErrorRequest has a connection error.

char *contentTypeBody content type.

char *cookieRequest cookie string.

WebsUpload *currentFileCurrent file context.

char *decodedQueryDecoded request query.

char *digestPassword digest.

intdocfdFile descriptor for document being served.

intencodedTrue if the password is MD5(username:realm:password).

booleofIf at the end of the request content.

uinterrorRequest has an error.

char *extPath extension.

char *filenameDocument path name.

WebsHashfilesUploaded files.

uintfinalizedRequest has been completed.

intflagsCurrent flags see above.

char *hostRequested host.

charifaddr[ME_MAX_IP]Local interface ipaddress.

WebsBufinputReceive buffer after de-chunking.

charipaddr[ME_MAX_IP]Connecting ipaddress.

ssizelastReadNumber of bytes last read from the socket.

intlistenSidListen Socket id.

char *methodHTTP request method.

WebsBufoutputTransmit buffer after chunking.

char *passwordAuthorization password.

char *pathPath name without query.

This is decoded.

intportRequest port number.

char *protocolProtocol scheme (normally http|https).

char *protoVersionProtocol version (HTTP/1.1).

ssizeputLenBytes read by a PUT request.

char *putnamePUT temporary filename.

char *queryRequest query.

This is decoded.

char *realmRealm field supplied in auth header.

char *referrerThe referring page.

WebsHashresponseCookiesOutgoing cookies.

struct WebsRoute *routeRequest route.

introuteCountRoute count limiter.

WebsBufrxbufRaw receive buffer.

ssizerxChunkSizeRx chunk size.

intrxChunkStateRx chunk encoding state.

char *rxEndpPointer to end of raw data in input beyond endp.

ssizerxLenRx content length.

ssizerxRemainingRemaining content to read from client.

struct WebsSession *sessionSession record.

intsidSocket id (handler).

WebsTimesinceParsed if-modified-since time.

void *sslSSL context.

intstateCurrent state.

inttimeoutTimeout handle.

WebsTimetimestampLast transaction with browser.

ssizetxChunkLenLength of the chunk.

chartxChunkPrefix[16]Transmit chunk prefix.

ssizetxChunkPrefixLenLength of prefix.

char *txChunkPrefixNextCurrent I/O pos in txChunkPrefix.

inttxChunkStateTransmit chunk state.

ssizetxLenTx content length header value.

ssizetxRemainingRemaining content to write.

intupfdUpload file handle.

intuploadStateCurrent file upload state.

char *uploadTmpCurrent temp filename for upload data.

char *uploadVarCurrent upload form variable name.

char *urlFull request url.

This is not decoded.

userUser auth record.

char *userAgentUser agent (browser).

char *usernameAuthorization username.

WebsHashvarsCGI standard variables.

intwidIndex into webs.

WebsWriteProcwriteDataHandler write I/O event callback.

Used by fileHandler.

ssizewrittenBytes actually transferred.

void

sslClose

(void )

Close the ssl module.

API Stability:Stable.

See Also:

void

sslFree

(Webs *wp)

Free a ssl connection associated with a request.

Parameters:wpWebs request object.

API Stability:Stable.

See Also:

int

sslOpen

(void )

Open the ssl module.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

ssize

sslRead

(Webs *wp, void *buf, ssize len)

Read data from a secure socket.

Parameters:wpWebs request object.

bufBuffer into which to read data.

lenSize of buf.

Returns:Count of bytes read if successful, otherwise -1.

API Stability:Stable.

See Also:

int

sslUpgrade

(Webs *wp)

Upgrade a request connection to utilize SSL.

Description:This routine is invoked on a connection received on a secure listening socket.

Parameters:wpWebs request object.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

ssize

sslWrite

(Webs *wp, void *buf, ssize len)

WRite data to a secure socket.

Parameters:wpWebs request object.

bufBuffer from which to write data.

lenSize of buf.

Returns:Count of bytes written if successful, otherwise -1.

API Stability:Stable.

See Also:

int

websAccept

(int sid, cchar *ipaddr, int port, int listenSid)

Accept a new connection.

Parameters:sidSocket ID handle for the newly accepted socket.

ipaddrIP address originating the connection.

portPort number originating the connection.

listenSidSocket ID of the listening socket.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

void

websActionOpen

(void )

Open the action handler.

API Stability:Stable.

See Also:

int

websAlloc

(int sid)

Allocate a new Webs object.

Parameters:sidSocket ID handle for the newly accepted socket.

Returns:The webs[] handle index for the allocated Webs object.

API Stability:Stable.

See Also:

void

websCancelTimeout

(Webs *wp)

Cancel the request timeout.

Description:Handlers may choose to manually manage the request timeout. This routine will disable the centralized management of the timeout for this request.

Parameters:wpWebs request object.

API Stability:Stable.

See Also:

int

websCgiHandler

(Webs *wp)

CGI handler service callback.

Parameters:wpWebs object.

Returns:Returns 1 if the request was handled.

API Stability:Stable.

See Also:

int

websCgiOpen

(void )

Open the CGI handler.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

int

websCgiPoll

(void )

Poll for output from CGI processes and output.

Returns:Time delay till next poll.

API Stability:Stable.

See Also:

void

websClose

(void )

Close the core GoAhead web server module.

Description:Invoked when GoAhead is shutting down.

API Stability:Stable.

See Also:

void

websCloseFile

(int fd)

Close an open file.

Parameters:fdOpen file handle returned by websOpenFile.

API Stability:Stable.

See Also:

int

websCompareVar

(Webs *wp, cchar *var, cchar *value)

Compare a request variable.

Parameters:wpWebs request object.

varVariable name.

valueValue to compare with.

Returns:True if the value matches. Otherwise return 0.

API Stability:Stable.

See Also:

void

websConsumeInput

(Webs *wp, ssize nbytes)

Consume input from the request input buffer.

Description:This is called by handlers when consuming data from the request input buffer. This call updates the input service pointers and compacts the input buffer if required.

Parameters:wpWebs request object.

nbytesNumber of bytes the handler has consumed from the input buffer.

API Stability:Stable.

See Also:

char *

websDecode64

(char *str)

Decode the string using base-64 encoding.

Description:This modifies the original string.

Parameters:strString to decode.

Returns:The original string. Caller must not free.

API Stability:Stable.

See Also:

char *

websDecode64Block

(char *str, ssize *len, int flags)

Decode a block using base-46 encoding.

Parameters:strString to decode. The string must be null terminated.

lenReference to an integer holding the length of the decoded string.

flagsReserved.

Returns:The original string.

API Stability:Stable.

See Also:

void

websDecodeUrl

(char *decoded, char *input, ssize len)

Decode a URL expanding NN encoding.

Description:Supports insitu decoding. i.e. Input and output buffers may be the same.

Parameters:decodedBuffer to hold the decoded URL.

inputInput URL or buffer to decode.

lenLength of the decoded buffer.

API Stability:Stable.

See Also:

int

websDefineAction

(cchar *name, void *fun)

Define an action callback for use with the action handler.

Description:The action handler binds a C function to a URI under "/action".

Parameters:nameURI path suffix. This suffix is added to "/action" to form the bound URI path.

funCallback function. The signature is void (*WebsAction)(Webs *wp);.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

int

websDefineHandler

(cchar *name, WebsHandlerProc match, WebsHandlerProc service, WebsHandlerClose close, int flags)

Define a request handler.

Parameters:nameName of the handler.

matchHandler callback match procedure. Invoked to match the request with the handler. The handler should return true to accept the request.

serviceHandler callback service procedure. Invoked to service each request.

closeHandler callback close procedure. Called when GoAhead is shutting down.

flagsSet to WEBS_LEGACY_HANDLER to support the legacy handler API calling sequence.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

int

websDefineJst

(cchar *name, WebsJstProc fn)

Define a Javscript native function.

Description:This routine binds a C function to a Javascript function. When the Javascript function is called, the C function is invoked.

Parameters:nameJavascript function name.

fnC function to invoke.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

void

websDone

(Webs *wp)

Complete a request.

Description:A handler should call websDone() to complete the request.

Parameters:wpWebs request object.

API Stability:Stable.

See Also:

char *

websEncode64

(char *str)

Encode a string using base-64 encoding.

Description:The string is encoded insitu.

Parameters:strString to encode.

Returns:The original string.

API Stability:Stable.

See Also:

char *

websEncode64Block

(char *str, ssize len)

Encode a block using base-64 encoding.

Description:The string is encoded insitu.

Parameters:strString to encode.

lenLength of string to encode.

Returns:The original string.

API Stability:Stable.

See Also:

void

websError

(Webs *wp, int code, cchar *fmt, ...)

Complete a request with an error response.

Parameters:wpWebs request object.

codeHTTP status code.

fmtMessage printf style format.

...Format args.

API Stability:Stable.

See Also:

cchar *

websErrorMsg

(int code)

Get a message for a HTTP status code.

Parameters:codeHTTP status code.

Returns:Http status message. Caller must not free.

API Stability:Stable.

See Also:

char *

websEscapeHtml

(cchar *str)

Escape unsafe characters in a string.

Parameters:strString to escape.

Returns:An allocated block containing the escaped string. Caller must free.

API Stability:Stable.

See Also:

void

websFileOpen

(void )

Open and initialize the file handler.

API Stability:Stable.

See Also:

int

websFlush

(Webs *wp, bool block)

Flush buffered transmit data and compact the transmit buffer to make room for more data.

Description:This call initiates sending buffered data. If blocking mode is selected via the block parameter, this call will wait until all the data has been sent to the O/S for transmission to the client. If block is false, the flush will be initiated and the call will return immediately without blocking.

Parameters:wpWebs request object.

blockSet to true to wait for all data to be written to the socket. Set to false to write whatever the socket can absorb without blocking.

Returns:-1 for I/O errors. Return zero if there is more data remaining in the buffer. Return 1 if the contents of the transmit buffer are fully written and the buffer is now empty.

API Stability:Stable.

See Also:

void

websFree

(Webs *wp)

Free the webs request object.

Description:Callers should call websDone to complete requests prior to invoking websFree.

Parameters:wpWebs request object.

API Stability:Stable.

See Also:

void

websFreeUpload

(Webs *wp)

Free file upload data structures.

Parameters:wpWebs request object.

API Stability:Stable.

See Also:

void

websFsClose

(void )

Close the file system module.

API Stability:Stable.

See Also:

int

websFsOpen

(void )

Open the file system module.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

int

websGetBackground

(void )

Get the background execution flag.

Description:If GoAhead is invoked with background, it will run as a daemon in the background.

Returns:True if GoAhead is running in the background.

API Stability:Stable.

See Also:

char *

websGetCgiCommName

(void )

Get a unique temporary filename for CGI communications.

Returns:Allocated filename string. Caller must free.

API Stability:Stable.

See Also:

cchar *

websGetCookie

(Webs *wp)

Get the request cookie if supplied.

Parameters:wpWebs request object.

Returns:Cookie string if defined, otherwise null. Caller must not free.

API Stability:Stable.

See Also:

char *

websGetDateString

(WebsFileInfo *sbuf)

Get a date as a string.

Description:If sbuf is supplied, it is used to calculate the date. Otherwise, the current time is used.

Parameters:sbufFile info object.

Returns:An allocated date string. Caller should free.

API Stability:Stable.

See Also:

int

websGetDebug

(void )

Get the debug flag.

Description:If GoAhead is invoked with debugger, the debug flag will be set to true.

Returns:True if GoAhead is running in debug mode.

API Stability:Stable.

See Also:

cchar *

websGetDir

(Webs *wp)

Get the base file directory for a request.

Description:Returns the request route directory if defined, otherwise returns the documents directory.

Parameters:wpWebs request object.

Returns:Path name string. Caller should not free.

API Stability:Stable.

See Also:

char *

websGetDocuments

(void )

Get the GoAhead base documents directory.

Description:The documents directory is defined at build time and may be overridden by the GoAhead command line.

Returns:Path string for the documents directory.

API Stability:Stable.

See Also:

int

websGetEof

(Webs *wp)

Get the request EOF status.

Description:The request EOF status is set to true when all the request body (POST|PUT) data has been received.

Parameters:wpWebs request object.

Returns:True if all the request body data has been received.

API Stability:Stable.

See Also:

cchar *

websGetExt

(Webs *wp)

Get the request URI extension.

Parameters:wpWebs request object.

Returns:The URI filename extension component. Caller should not free.

API Stability:Stable.

See Also:

cchar *

websGetFilename

(Webs *wp)

Get the request filename.

Description:The URI is mapped to a filename by decoding and prepending with the request directory.

Parameters:wpWebs request object.

Returns:Filename string. Caller should not free.

API Stability:Stable.

See Also:

cchar *

websGetHost

(Webs *wp)

Get the request host.

Description:The request host is set to the Host HTTP header value if it is present. Otherwise it is set to the request URI hostname.

Parameters:wpWebs request object.

Returns:Host string. Caller should not free.

API Stability:Stable.

See Also:

cchar *

websGetIfaddr

(Webs *wp)

Get the request interface address.

Parameters:wpWebs request object.

Returns:Network interface string. Caller should not free.

API Stability:Stable.

See Also:

cchar *

websGetIndex

(void )

Get the default index document name.

Description:The default index is "index.html" and can be updated via websSetIndex.

Returns:Index name string. Caller should not free.

API Stability:Stable.

See Also:

int

websGetLogLevel

(void )

Get the current trace log level.

Returns:Number between 0 and 9.

API Stability:Stable.

See Also:

cchar *

websGetMethod

(Webs *wp)

Get the request method.

Parameters:wpWebs request object.

Returns:HTTP method string. Caller should not free.

API Stability:Stable.

See Also:

cchar *

websGetPassword

(Webs *wp)

Get the request password.

Description:The request password may be encoded depending on the authentication scheme. See wp->encoded to test if it is encoded.

Parameters:wpWebs request object.

Returns:Password string. Caller should not free.

API Stability:Stable.

See Also:

cchar *

websGetPath

(Webs *wp)

Get the request path.

Description:The URI path component excludes the http protocol, hostname, port, reference and query components. It always beings with "/".

Parameters:wpWebs request object.

Returns:Request path string. Caller should not free.

API Stability:Stable.

See Also:

int

websGetPort

(Webs *wp)

Get the request TCP/IP port.

Parameters:wpWebs request object.

Returns:TCP/IP Port integer.

API Stability:Stable.

See Also:

cchar *

websGetProtocol

(Webs *wp)

Get the request HTTP protocol.

Description:This will be set to either "http" or "https".

Parameters:wpWebs request object.

Returns:Protocol string. Caller should not free.

API Stability:Stable.

See Also:

cchar *

websGetQuery

(Webs *wp)

Get the request query component.

Parameters:wpWebs request object.

Returns:Request query string. Caller should not free.

API Stability:Stable.

See Also:

cchar *

websGetServer

(void )

Get the server host name.

Returns:Host name string. Caller should not free.

API Stability:Stable.

See Also:

cchar *

websGetServerAddress

(void )

Get the server IP address.

Returns:Server IP address string. Caller should not free.

API Stability:Stable.

See Also:

cchar *

websGetServerAddressUrl

(void )

Get the server IP address with port number.

Returns:Server IP:PORT address string. Caller should not free.

API Stability:Stable.

See Also:

cchar *

websGetServerUrl

(void )

Get the server host name with port number.

Returns:Host name string with port number. Caller should not free.

API Stability:Stable.

See Also:

cchar *

websGetUrl

(Webs *wp)

Get the request URI.

Description:This returns the request URI. This may be modified if the request is rewritten via websRewrite.

Parameters:wpWebs request object.

Returns:URI string. Caller should not free.

API Stability:Stable.

See Also:

cchar *

websGetUserAgent

(Webs *wp)

Get the client User-Agent HTTP header.

Parameters:wpWebs request object.

Returns:User-Agent string. Caller should not free.

API Stability:Stable.

See Also:

cchar *

websGetUsername

(Webs *wp)

Get the request username.

Description:If the request is authenticated, this call returns the username supplied during authentication.

Parameters:wpWebs request object.

Returns:Username string if defined, otherwise null. Caller should not free.

API Stability:Stable.

See Also:

cchar *

websGetVar

(Webs *wp, cchar *name, cchar *defaultValue)

Get a request variable.

Description:Request variables are defined for HTTP headers of the form HTTP_*. Some request handlers also define their own variables. For example: CGI environment variables.

Parameters:wpWebs request object.

nameVariable name.

defaultValueDefault value to return if the variable is not defined.

Returns:Variable value string. Caller should not free.

API Stability:Stable.

See Also:

int

websJstOpen

(void )

Open the Javascript module.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

int

websJstWrite

(int jid, Webs *wp, int argc, char **argv)

Write data to the response.

Parameters:jidJavascript ID handle.

wpWebs request object.

argcCount of arguments.

argvArray arguments.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

int

websListen

(cchar *endpoint)

Listen on a TCP/IP address endpoint.

Description:The URI is mapped to a filename by decoding and prepending with the request directory. For IPv6 addresses, use the format: [aaaa:bbbb:cccc:dddd:eeee:ffff:gggg:hhhh:iiii]:port.

Parameters:endpointIPv4 or IPv6 address on which to listen.

Returns:Positive integer holding a Socket ID handle if successful, otherwise -1.

API Stability:Stable.

See Also:

char *

websMD5

(cchar *str)

Get an MD5 digest of a string.

Parameters:strString to analyze.

Returns:Allocated MD5 checksum. Caller should free.

API Stability:Stable.

See Also:

char *

websMD5Block

(cchar *buf, ssize length, cchar *prefix)

Get an MD5 digest of a block and optionally prepend a prefix.

Parameters:bufBlock to analyze.

lengthLength of block.

prefixOptional prefix to prepend to the MD5 sum.

Returns:Allocated MD5 checksum. Caller should free.

API Stability:Stable.

See Also:

char *

websNormalizeUriPath

(cchar *path)

Normalize a URI path.

Description:This removes "./", "../" and redundant separators.

Parameters:pathURI path to normalize.

Returns:An allocated normalized URI path. Caller must free.

API Stability:Stable.

See Also:

void

websNoteRequestActivity

(Webs *wp)

Take not of the request activity and mark the time.

Description:This is used to defer the request timeout whenever there is request I/O activity.

Parameters:wpWebs request object.

API Stability:Stable.

See Also:

int

websOpen

(cchar *documents, cchar *routes)

Open the web server.

Description:This initializes the web server and defines the documents directory.

Parameters:documentsOptional web documents directory. If set to null, the build time ME_GOAHEAD_DOCUMENTS value is used for the documents directory.

routesOptional filename for a route configuration file to load. Additional route or authentication configuration files can be loaded via websLoad.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

int

websOpenFile

(cchar *path, int flags, int mode)

Open the web page document for the current request.

Parameters:pathFilename path to open.

flagsFile open flags.

modePermissions mask.

Returns:Positive file handle if successful, otherwise -1.

API Stability:Stable.

See Also:

int

websOptionsOpen

(void )

Open the options handler.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

void

websOsClose

(void )

Close the O/S dependent code.

Description:Called from websClose.

See Also:

int

websOsOpen

(void )

Open the O/S dependent code.

Description:Called from websOpen.

Returns:Zero if successful, otherwise -1.

See Also:

void

websPageClose

(Webs *wp)

Close the document page.

Parameters:wpWebs request object.

API Stability:Stable.

See Also:

int

websPageIsDirectory

(Webs *wp)

Test if the document page for the request corresponds to a directory.

Parameters:wpWebs request object.

Returns:True if the filename is a directory.

API Stability:Stable.

See Also:

int

websPageOpen

(Webs *wp, int mode, int perms)

Open a web page document for a request.

Parameters:wpWebs request object.

modeFile open mode. Select from O_RDONLY and O_BINARY. Rom files systems ignore this argument.

permsIgnored.

Returns:File handle if successful, otherwise -1.

API Stability:Stable.

See Also:

ssize

websPageReadData

(Webs *wp, char *buf, ssize size)

Read data from the request page document.

Parameters:wpWebs request object.

bufBuffer for the read data.

sizeSize of buf.

Returns:Count of bytes read if successful, otherwise -1.

API Stability:Stable.

See Also:

void

websPageSeek

(Webs *wp, Offset offset, int origin)

Seek to a position in the request page document.

Parameters:wpWebs request object.

offsetOffset of location in the file to seek to. This is relative to the specified origin.

originSet to SEEK_CUR, SEEK_SET or SEEK_END to position relative to the current position, beginning or end of the document.

API Stability:Stable.

See Also:

int

websPageStat

(Webs *wp, WebsFileInfo *sbuf)

Get file status for the current request document.

Parameters:wpWebs request object.

sbufFile information structure to modify with file status.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

int

websParseDateTime

(WebsTime *time, cchar *date, struct tm *defaults)

Parse a date/time string.

Description:Try to intelligently parse a date. This is a tolerant parser. It is not validating and will do its best to parse any possible date string. Supports the following date/time formats:

ISO dates: 2009-05-21t16:06:05.000z

Date: 07/28/2014, 07/28/08, Jan/28/2014, Jaunuary-28-2014, 28-jan-2014.

Support date order: dd/mm/yy, mm/dd/yy and yyyy/mm/dd

Support separators "/", ".", "-"

Timezones: GMT|UTC[+-]NN[:]NN

Time: 10:52[:23]

Parameters:timeReference to a.

dateDate/time string to parse.

defaultsOptionally supply missing components for the date/time. Set to NULL if not used.

Returns:Zero if successful, otherwise -1.

API Stability:Evolving.

See Also:

bool

websProcessCgiData

(Webs *wp)

Process CGI request body data.

Parameters:wpWebs request object.

Returns:True if processing the request can proceed.

API Stability:Stable.

See Also:

bool

websProcessUploadData

(Webs *wp)

Process upload data for form, multipart mime file upload.

Parameters:wpWebs request object.

Returns:True if processing the request can proceed.

API Stability:Stable.

See Also:

void

websPump

(Webs *wp)

Pump the state machine.

Description:This routine will advance the connection state machine in response to events.

Parameters:wpWebs request object.

API Stability:Stable.

See Also:

ssize

websReadFile

(int fd, char *buf, ssize size)

Read data from an open file.

Parameters:fdOpen file handle returned by websOpenFile.

bufBuffer for the read data.

sizeSize of buf.

Returns:Count of bytes read if successful, otherwise -1.

API Stability:Stable.

See Also:

char *

websReadWholeFile

(cchar *path)

Read all the data from a file.

Parameters:pathFile path to read from.

Returns:An allocated buffer containing the file data with an appended null. Caller must free.

API Stability:Stable.

See Also:

void

websRedirect

(Webs *wp, cchar *url)

Redirect the client to a new URL.

Description:This creates a response to the client with a Location header directing the client to a new location. The response uses a 302 HTTP status code.

Parameters:wpWebs request object.

urlURL to direct the client to.

API Stability:Stable.

See Also:

int

websRedirectByStatus

(Webs *wp, int status)

Redirect the client to a new URI.

Description:The routing configuration file can define redirection routes for various HTTP status codes. This routine will utilize the appropriate route redirection based on the request route and specified status code.

Parameters:wpWebs request object.

statusHTTP status code to use in selecting the route redirection.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

void

websResponse

(Webs *wp, int status, cchar *msg)

Create and send a request response.

Description:This creates a response for the current request using the specified HTTP status code and the supplied message.

Parameters:wpWebs request object.

statusHTTP status code.

msgResponse message body.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

int

websRewriteRequest

(Webs *wp, cchar *url)

Rewrite a request.

Description:Handlers may choose to not process a request but rather rewrite requests and then reroute.

Parameters:wpWebs request object.

urlNew request URL.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

void

websRuntimeClose

(void )

Close the runtime code.

Description:Called from websClose.

See Also:

int

websRuntimeOpen

(void )

Open the runtime code.

Description:Called from websOpen.

Returns:Zero if successful.

See Also:

Offset

websSeekFile

(int fd, Offset offset, int origin)

Seek to a position in the current request page document.

Parameters:fdOpen file handle returned by websOpenFile.

offsetLocation in the file to seek to.

originSet to SEEK_CUR, SEEK_SET or SEEK_END to position relative to the current position, beginning or end of the document.

API Stability:Stable.

See Also:

int

websServer

(cchar *endpoint, cchar *documents)

One line embedding API.

Description:This call will also open auth.txt and route.txt for authentication and routing configuration.

Parameters:endpointIP:PORT address on which to listen.

documentsDirectory containing web documents to serve.

API Stability:Stable.

See Also:

void

websServiceEvents

(int *finished)

Service I/O events until finished.

Description:This will wait for socket events and service those until *finished is set to true.

Parameters:finishedInteger location to test. If set to true, then exit. Note: setting finished will not automatically wake up the service routine.

API Stability:Stable.

See Also:

void

websSetBackground

(int on)

Set the background processing flag.

Parameters:onValue to set the background flag to.

See Also:

void

websSetCookie

(Webs *wp, cchar *name, cchar *value, cchar *path, cchar *domain, int lifespan, int flags)

Define a cookie to include in the response.

Parameters:wpWebs request object.

nameCookie name.

valueCookie value.

pathURI path prefix applicable for this cookie.

domainDomain applicable for this cookie.

lifespanCookie lifespan in seconds.

flagsSet to WEBS_COOKIE_SECURE for https only. Set to WEBS_COOKIE_HTTP for http only. Otherwise the cookie applies to both http and https requests. Or in WEBS_COOKIE_SAME_LAX for SameSite=Lax and WEBS_COOKIE_SAME_STRICT for SameSite=Strict.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

void

websSetDebug

(int on)

Set the debug processing flag.

Parameters:onValue to set the debug flag to.

See Also:

void

websSetDocuments

(cchar *dir)

Set the web documents directory.

Description:The web documents directory is used when resolving request URIs into filenames.

Parameters:dirDirectory path to use.

API Stability:Stable.

See Also:

void

websSetEnv

(Webs *wp)

Create the CGI environment variables for the current request.

Parameters:wpWebs request object.

API Stability:Stable.

See Also:

void

websSetFormVars

(Webs *wp)

Create request variables for query and POST body data.

Description:This creates request variables if the request is a POST form (has a Content-Type of application/x-www-form-urlencoded). The POST body data is consumed from the input buffer.

Parameters:wpWebs request object.

API Stability:Stable.

See Also:

void

websSetHost

(cchar *host)

Define the host name for the server.

Parameters:hostString host name.

API Stability:Stable.

See Also:

void

websSetIndex

(cchar *filename)

Create and send a request response.

Description:This creates a response for the current request using the specified HTTP status code and the supplied message.

Parameters:filenameWeb document name to use as the index. This should not contain any directory components.

API Stability:Stable.

See Also:

void

websSetIpAddr

(cchar *ipaddr)

Define the host IP address.

Parameters:ipaddrHost IP address.

API Stability:Stable.

See Also:

void

websSetLogLevel

(int level)

Set the current trace log level.

Returns:Number between 0 and 9.

API Stability:Prototype.

See Also:

void

websSetQueryVars

(Webs *wp)

Create request variables for query string data.

Parameters:wpWebs request object.

API Stability:Stable.

See Also:

void

websSetStatus

(Webs *wp, int status)

Set the response HTTP status code.

Parameters:wpWebs request object.

statusHTTP status code.

API Stability:Stable.

See Also:

void

websSetTxLength

(Webs *wp, ssize length)

Set the response body content length.

Parameters:wpWebs request object.

lengthLength value to use.

API Stability:Stable.

See Also:

WebsKey *

websSetVar

(Webs *wp, cchar *name, cchar *value)

Set a request variable to a string value.

Description:Request variables are defined for HTTP headers of the form HTTP_*. Some request handlers also define their own variables. For example: CGI environment variables.

Parameters:wpWebs request object.

nameVariable name to set.

valueValue to set.

Returns:The allocated WebsKey.

API Stability:Evolving.

See Also:

WebsKey *

websSetVarFmt

(Webs *wp, cchar *name, cchar *fmt, ...)

Set a request variable to a formatted string value.

Description:Request variables are defined for HTTP headers of the form HTTP_*. Some request handlers also define their own variables. For example: CGI environment variables.

Parameters:wpWebs request object.

nameVariable name to set.

fmtValue format string.

...Args to format.

Returns:The allocated WebsKey.

API Stability:Evolving.

See Also:

int

websStatFile

(cchar *path, WebsFileInfo *sbuf)

Get file status for a file.

Parameters:pathFilename path.

sbufFile information structure to modify with file status.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

char *

websTempFile

(cchar *dir, cchar *prefix)

Create a temporary filename This does not guarantee the filename is unique or that it is not already in use by another application.

Parameters:dirDirectory to locate the temp file. Defaults to the O/S default temporary directory (usually /tmp).

prefixFilename prefix.

Returns:An allocated filename string.

API Stability:Stable.

See Also:

bool

websTestVar

(Webs *wp, cchar *name)

Test if a request variable is defined.

Parameters:wpWebs request object.

nameVariable name.

Returns:True if the variable is defined.

API Stability:Stable.

See Also:

void

websTimeClose

(void )

Close the date/time parsing module.

API Stability:Evolving.

See Also:

int

websTimeOpen

(void )

Open the date/time parsing module.

Returns:Zero if successful, otherwise -1.

API Stability:Evolving.

See Also:

int

websUrlParse

(cchar *url, char **buf, char **protocol, char **host, char **port, char **path, char **ext, char **reference, char **query)

Parse a URL into its components.

Parameters:urlURL to parse.

bufBuffer to hold storage for various parsed components. Caller must free. NOTE: the parsed components may point to locations in this buffer.

protocolParsed URL protocol component.

hostParsed hostname.

portParsed URL port.

pathParsed URL path component.

extParsed URL extension.

referenceParsed URL reference portion (#reference).

queryParsed URL query component.

Returns:Zero if successful, otherwise -1.

API Stability:Evolving.

See Also:

bool

websValid

(Webs *wp)

Test if a webs object is valid.

Description:After calling websDone, the websFree routine will have been called and the memory for the webs object will be released. Call websValid to test a Webs object for validity.

Parameters:wpWebs request object.

Returns:True if the webs object is still valid and the request has not been completed.

API Stability:Stable.

See Also:

char *

websValidateUriPath

(cchar *uri)

Validate a URI path as expected in a HTTP request line.

Description:This expects a URI beginning with "/" and containing only valid URI characters. The URI is decoded, and normalized removing "../" and "." segments. The URI must begin with a "/" both before and after decoding and normalization.

Parameters:uriURI to validate.

Returns:A validated, normalized URI path. Caller must free.

API Stability:Stable.

See Also:

bool

websValidUriChars

(cchar *uri)

Test if a URI is using only valid characters Note this does not test if the URI is fully legal.

Some components of the URI have restricted character sets that this routine does not test. This tests if the URI has only characters valid to use in a URI before decoding. i.e. It will permit NN encodings. The set of valid characters is: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=%"

Parameters:uriUri to test.

Returns:True if the URI string is comprised of legal URI characters.

API Stability:Evolving.

See Also:

ssize

websWrite

(Webs *wp, cchar *fmt, ...)

Write data to the response.

Description:The data is buffered and will be sent to the client when the buffer is full or websFlush is called.

Parameters:wpWebs request object.

fmtPrintf style format string.

...Arguments to the format string.

Returns:Count of bytes written.

API Stability:Stable.

See Also:

ssize

websWriteBlock

(Webs *wp, cchar *buf, ssize size)

Write a block of data to the response.

Description:The data is buffered and will be sent to the client when the buffer is full or websFlush is called. This routine will never return "short", it will always write all the data unless there are errors.

Parameters:wpWebs request object.

bufBuffer of data to write.

sizeLength of buf.

Returns:Count of bytes written or -1. This will always equal size if there are no errors.

API Stability:Stable.

See Also:

void

websWriteEndHeaders

(Webs *wp)

Signify the end of the response headers.

Description:This call concludes the response headers and writes a blank line to the response.

Parameters:wpWebs request object.

API Stability:Stable.

See Also:

ssize

websWriteFile

(int fd, cchar *buf, ssize size)

Write data to the open file.

Parameters:fdOpen file handle returned by websOpenFile.

bufBuffer for the read data.

sizeSize of buf.

Returns:Count of bytes read if successful, otherwise -1.

API Stability:Stable.

See Also:

int

websWriteHeader

(Webs *wp, cchar *key, cchar *fmt, ...)

Write a response header.

Description:This routine writes a response header. It should be invoked after calling websWriteHeaders to write the standard headers and before websWriteEndHeaders. This routine differs from websWrite in that it traces header values to the log.

Parameters:wpWebs request object.

keyHeader key value.

fmtHeader value format string.

...Arguments to the format string.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

void

websWriteHeaders

(Webs *wp, ssize contentLength, cchar *redirect)

Write a set of standard response headers.

Parameters:wpWebs request object.

contentLengthValue for the Content-Length header which describes the length of the response body.

redirectValue for the Location header which redirects the client to a new URL.

API Stability:Stable.

ssize

websWriteSocket

(Webs *wp, cchar *buf, ssize size)

Write a block of data to the network.

Description:This bypassed output buffering and is the lowest level write.

Parameters:wpWebs request object.

bufBuffer of data to write.

sizeLength of buf.

Returns:Count of bytes written. May be less than len if the socket is in non-blocking mode. Returns -1 for errors and if the socket cannot absorb any more data. If the transport is saturated, will return a negative error and errno will be set to EAGAIN or EWOULDBLOCK.

API Stability:Stable.

See Also:

WebsAuth

WebsAuth

GoAhead Authentication.

Fields:

WebsRole *

websAddRole

(cchar *role, WebsHash abilities)

Add a role.

Description:The role is added to the list of roles.

Parameters:roleRole name.

abilitiesHash of abilities for the role.

Returns:The allocated role.

API Stability:Stable.

See Also:

WebsUser *

websAddUser

(cchar *username, cchar *password, cchar *roles)

Add a user.

Description:The user is added to the list of users.

Parameters:usernameUser name.

passwordUser password (encrypted).

rolesSpace separated list of roles. This may also contain abilities.

Returns:User object.

API Stability:Stable.

See Also:

bool

websAuthenticate

(Webs *wp)

Authenticate a user.

Description:The user is authenticated if required by the selected request route.

Parameters:wpWebs request object.

Returns:True if the route does not require authentication or the user is authenticated successfully.

API Stability:Stable.

See Also:

bool

websCan

(Webs *wp, WebsHash ability)

Test if a user possesses the required ability.

Parameters:wpWebs request object.

abilitySet of required abilities.

Returns:True if the user has the required ability.

API Stability:Stable.

See Also:

void

websCloseAuth

(void )

Close the authentication module.

API Stability:Stable.

See Also:

void

websComputeAllUserAbilities

(void )

Compute the abilities for all users by resolving roles into abilities.

API Stability:Stable.

See Also:

WebsVerify

websGetPasswordStoreVerify

(void )

Set the password store verify callback.

Returns:Verify WebsVerify callback function.

API Stability:Stable.

See Also:

WebsHash

websGetRoles

(void )

Get the roles hash.

Returns:The roles hash object.

API Stability:Stable.

See Also:

WebsHash

websGetUsers

(void )

Get the users hash.

Returns:The users hash object.

API Stability:Stable.

See Also:

bool

websLoginUser

(Webs *wp, cchar *username, cchar *password)

Login a user by verifying the login credentials.

Description:This may be called by handlers to manually authenticate a user.

Parameters:wpWebs request object.

usernameUser name.

passwordUser password (encrypted).

Returns:True if the user can be authenticated.

API Stability:Stable.

See Also:

bool

websLogoutUser

(Webs *wp)

Logout a user and remove the user login session.

Parameters:wpWebs request object.

Returns:True if successful.

API Stability:Stable.

See Also:

WebsUser *

websLookupUser

(cchar *username)

Lookup if a user exists.

Parameters:usernameUser name to search for.

Returns:User object or null if the user cannot be found.

API Stability:Stable.

See Also:

int

websOpenAuth

(int minimal)

Open the authentication module.

Parameters:minimalReserved. Set to zero.

Returns:True if the user has the required ability.

API Stability:Stable.

See Also:

int

websRemoveRole

(cchar *role)

Remove a role from the system.

Parameters:roleRole name.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

int

websRemoveUser

(cchar *name)

Remove a user from the system.

Parameters:nameUser name.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

void

websSetPasswordStoreVerify

(WebsVerify verify)

Set the password store verify callback.

Parameters:verifyWebsVerify callback function.

API Stability:Stable.

See Also:

int

websSetUserPassword

(cchar *username, cchar *password)

Set a password for the user.

Parameters:usernameUser name.

passwordNull terminated password string.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

int

websSetUserRoles

(cchar *username, cchar *roles)

Define the set of roles for a user.

Parameters:usernameUser name.

rolesSpace separated list of roles or abilities.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

bool

websVerifyPasswordFromCustom

(Webs *wp)

User password verification routine from a custom password back-end store.

Parameters:wpWebs request object.

Returns:True if the user password verifies.

API Stability:Stable.

See Also:

bool

websVerifyPasswordFromFile

(Webs *wp)

User password verification routine from auth.txt.

Parameters:wpWebs request object.

Returns:True if the user password verifies.

API Stability:Stable.

See Also:

WebsBuf

WebsBuf

A WebsBuf (ring queue) allows maximum utilization of memory for data storage and is ideal for input/output buffering.

Description:This module provides a highly efficient implementation and a vehicle for dynamic strings. WARNING: This is a public implementation and callers have full access to the queue structure and pointers. Change this module very carefully.

This module follows the open/close model.

Operation of a WebsBuf where bp is a pointer to a WebsBuf : bp->buflen contains the size of the buffer.

bp->buf will point to the start of the buffer.

bp->servp will point to the first (un-consumed) data byte.

bp->endp will point to the next free location to which new data is added

bp->endbuf will point to one past the end of the buffer.

Eg. If the WebsBuf contains the data "abcdef", it might look like :

+————————————————————————————————+ | | | | | | | | a | b | c | d | e | f | | | | | +————————————————————————————————+ ^ ^ ^ ^ | | | | bp->buf bp->servp bp->endp bp->enduf

The queue is empty when servp == endp. This means that the queue will hold at most bp->buflen -1 bytes. It is the fillers responsibility to ensure the WebsBuf is never filled such that servp == endp.

It is the fillers responsibility to "wrap" the endp back to point to bp->buf when the pointer steps past the end. Correspondingly it is the consumers responsibility to "wrap" the servp when it steps to bp->endbuf. The bufPutc and bufGetc routines will do this automatically.

API Stability:Stable.

Fields:char *bufHolding buffer for data.

ssizebuflenLength of ring queue.

char *endbufPointer to end of buffer.

char *endpPointer to end of data.

intincrementGrowth increment.

ssizemaxsizeMaximum size.

char *servpPointer to start of data.

void

bufAddNull

(WebsBuf *bp)

Add a trailing null to the buffer.

The end pointer is not changed

Parameters:bpBuffer reference.

API Stability:Stable.

See Also:

void

bufAdjustEnd

(WebsBuf *bp, ssize size)

Adjust the endp pointer by the specified size.

Description:This is useful after manually copying data into the buffer and needing to adjust the end pointer.

Parameters:bpBuffer reference.

sizeSize of adjustment. May be positive or negative value.

API Stability:Stable.

See Also:

void

bufAdjustStart

(WebsBuf *bp, ssize count)

Adjust the start (servp) reference.

Parameters:bpBuffer reference.

countNumber of bytes to adjust.

API Stability:Stable.

See Also:

void

bufCompact

(WebsBuf *bp)

Compact the data in the buffer and move to the start of the buffer.

Parameters:bpBuffer reference.

API Stability:Stable.

See Also:

int

bufCreate

(WebsBuf *bp, int increment, int maxsize)

Create a buffer.

Parameters:bpBuffer reference.

incrementIncremental size to grow the buffer. This will be increased by a power of two each time the buffer grows.

maxsizeMaximum size of the buffer.

Returns:Zero if successful.

API Stability:Stable.

See Also:

void

bufFlush

(WebsBuf *bp)

Flush all data in the buffer and reset the pointers.

Parameters:bpBuffer reference.

API Stability:Stable.

See Also:

void

bufFree

(WebsBuf *bp)

Free allocated storage for the buffer.

Parameters:bpBuffer reference.

Returns:Zero if successful.

API Stability:Stable.

See Also:

ssize

bufGetBlk

(WebsBuf *bp, char *blk, ssize len)

Copy a block of from the buffer and adjust the servp.

Parameters:bpBuffer reference.

blkBlock into which to place the data.

lenLength of the block.

Returns:Number of bytes copied.

API Stability:Stable.

See Also:

ssize

bufGetBlkMax

(WebsBuf *bp)

Return the maximum number of bytes the buffer can provide via a single block copy.

Description:Useful if the user is doing their own data retrieval.

Parameters:bpBuffer reference.

Returns:Number of bytes available for copying.

API Stability:Stable.

See Also:

int

bufGetc

(WebsBuf *bp)

Get a character from the buffer and increment the servp.

Parameters:bpBuffer reference.

Returns:The next character or -1 if the buffer is empty.

API Stability:Stable.

See Also:

bool

bufGrow

(WebsBuf *bp, ssize room)

Grow the buffer by at least the required amount of room.

Parameters:bpBuffer reference.

roomAvailable size required after growing the buffer.

Returns:True if the buffer can be grown to have the required amount of room.

API Stability:Stable.

See Also:

int

bufInsertc

(WebsBuf *bp, char c)

Insert a character to the buffer before the servp position and decrement the servp.

Parameters:bpBuffer reference.

cCharacter to insert.

Returns:Zero if successful.

API Stability:Stable.

See Also:

ssize

bufLen

(WebsBuf *bp)

Get the length of available data in the buffer.

Parameters:bpBuffer reference.

Returns:Size of available data in bytes.

API Stability:Stable.

See Also:

ssize

bufPut

(WebsBuf *bp, cchar *fmt, ...)

Append a formatted string to the buffer at the endp position and increment the endp.

Parameters:bpBuffer reference.

fmtPrintf style format string.

...Variable arguments for the format string.

Returns:Count of characters appended. Returns negative if there is an allocation error.

API Stability:Stable.

See Also:

ssize

bufPutBlk

(WebsBuf *bp, cchar *blk, ssize len)

Put a block to the buffer.

Parameters:bpBuffer reference.

blkBlock to append to the buffer.

lenSize of the block.

Returns:Length of data appended. Should equal len.

API Stability:Stable.

See Also:

int

bufPutc

(WebsBuf *bp, char c)

Append a character to the buffer at the endp position and increment the endp.

Parameters:bpBuffer reference.

cCharacter to append.

Returns:Zero if successful.

API Stability:Stable.

See Also:

ssize ssize

ssize bufPutStr

(WebsBuf *bp, cchar *str)

Append a string to the buffer at the endp position and increment the endp.

Parameters:bpBuffer reference.

strString to append.

Returns:Count of characters appended. Returns negative if there is an allocation error.

API Stability:Stable.

See Also:

void

bufReset

(WebsBuf *bp)

Reset the buffer pointers to the start of the buffer if empty.

Parameters:bpBuffer reference.

API Stability:Stable.

See Also:

ssize

bufRoom

(WebsBuf *bp)

Determine the room available in the buffer.

Description:This returns the maximum number of bytes the buffer can absorb in a single block copy.

Parameters:bpBuffer reference.

Returns:Number of bytes of available space.

API Stability:Stable.

See Also:

char *

bufStart

(WebsBuf *bp)

Get a reference to the start of buffer data.

Parameters:bpBuffer reference.

Returns:A string pointer.

API Stability:Stable.

See Also:

WebsHash

WebsHash

Hash table entry structure.

Description:The hash structure supports growable hash tables with high performance, collision resistant hashes. Each hash entry has a descriptor entry. This is used to manage the hash table link chains.

API Stability:Stable.

Fields:

WebsHash

hashCreate

(int size)

Create a hash table.

Parameters:sizeMinimum size of the hash index.

Returns:Hash table ID. Negative if the hash cannot be created.

API Stability:Stable.

int

hashDelete

(WebsHash id, cchar *name)

Delete a key by name.

Parameters:idHash table id returned by hashCreate.

nameKey name to delete.

Returns:Zero if the delete was successful. Otherwise -1 if the key was not found.

API Stability:Stable.

WebsKey *

hashEnter

(WebsHash id, cchar *name, WebsValue value, int arg)

Enter a new key and value into the hash table.

Parameters:idHash table id returned by hashCreate.

nameKey name to create.

valueKey value to enter.

argOptional extra argument to store with the value.

Returns:Reference to the WebKey object storing the key and value.

API Stability:Stable.

WebsKey *

hashFirst

(WebsHash id)

Start walking the hash keys by returning the first key entry in the hash.

Parameters:idHash table id returned by hashCreate.

Returns:Reference to the first WebKey object. Return null if there are no keys in the hash.

API Stability:Stable.

void

hashFree

(WebsHash id)

Free a hash table.

Parameters:idHash table id returned by hashCreate.

API Stability:Stable.

WebsKey *

hashLookup

(WebsHash id, cchar *name)

Lookup a name in the hash table.

Parameters:idHash table id returned by hashCreate.

nameKey name to search for.

Returns:Reference to the WebKey object storing the key and value.

API Stability:Stable.

void *

hashLookupSymbol

(WebsHash sd, cchar *name)

Lookup a name in the hash table and return a symbol reference.

Parameters:sdHash table id returned by hashCreate.

nameKey name to search for.

Returns:Reference to the symbole.

API Stability:Evolving.

WebsKey *

hashNext

(WebsHash id, WebsKey *last)

Continue walking the hash keys by returning the next key entry in the hash.

Parameters:idHash table id returned by hashCreate.

lastReference to a WebsKey to hold the current traversal key state.

Returns:Reference to the next WebKey object. Returns null if no more keys exist to be traversed.

API Stability:Stable.

WebsRoute

WebsRoute

Request route structure.

Fields:WebsHashabilitiesRequired user abilities.

askLoginRoute path prefix.

char *authTypeAuthentication type.

char *dirFilesystem base directory for route documents.

WebsHashextensionsPermissible URI extensions.

intflagsRoute control flags.

handlerRequest handler to service requests.

WebsHashmethodsSupported HTTP methods.

parseAuthParse authentication details callback.

char *prefixRoute path prefix.

ssizeprefixLenPrefix length.

char *protocolHTTP protocol to use for this route.

WebsHashredirectsResponse redirections.

verifyVerify password callback.

WebsRoute *

websAddRoute

(cchar *uri, cchar *handler, int pos)

Add a route to the routing tables.

Parameters:uriMatching URI prefix.

handlerRequest handler to service routed requests.

posPosition in the list of routes. Zero inserts at the front of the list. A value of -1 will append to the end of the list.

Returns:A route object.

API Stability:Stable.

See Also:

void

websCloseRoute

(void )

Close the route module.

API Stability:Stable.

See Also:

int

websLoad

(cchar *path)

Load routing tables from the specified filename.

Parameters:pathRoute configuration filename.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

int

websOpenRoute

(void )

Open the routing module.

API Stability:Stable.

See Also:

int

websRemoveRoute

(cchar *uri)

Remove a route from the routing tables.

Parameters:uriMatching URI prefix.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

void

websRouteRequest

(Webs *wp)

Route a request.

Description:This routine will select a matching route and will invoke the selected route handler to service the request. In the process, authentication and request rewriting may take place. This routine is called internally by the request pipeline.

Parameters:wpWebs request object.

API Stability:Stable.

See Also:

bool

websRunRequest

(Webs *wp)

Run a request handler.

Description:This routine will run the handler and route selected by websRouteRequest. This routine is called internally by the request pipeline.

Parameters:wpWebs request object.

Returns:True if the handler serviced the request. Return false to test other routes to handle this request. This is for legacy handlers that do not have a match callback.

API Stability:Stable.

See Also:

int

websSetRouteAuth

(WebsRoute *route, cchar *authType)

Set route authentication scheme.

Parameters:routeRoute to modify.

authTypeSet to "basic", "digest" or "form".

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

int

websSetRouteMatch

(WebsRoute *route, cchar *dir, cchar *protocol, WebsHash methods, WebsHash extensions, WebsHash abilities, WebsHash redirects)

Configure a route by adding matching criteria.

Parameters:routeRoute to modify.

dirSet the route documents directory filename.

protocolSet the matching HTTP protocol (http or https).

methodsHash of permissible HTTP methods. (GET, HEAD, POST, PUT).

extensionsHash of permissible URI filename extensions.

abilitiesRequired user abilities. If abilities are required, the user must be authenticated.

redirectsSet of applicable response redirections when completing the request.

Returns:Zero if successful, otherwise -1.

API Stability:Evolving.

See Also:

WebsRuntime

WebsRuntime

GoAhead Web Server Runtime.

Description:GoAhead provides a secure runtime environment for safe string manipulation and to help prevent buffer overflows and other potential security traps.

API Stability:Stable.

Fields:

char *

fmt

(char *buf, ssize maxSize, cchar *format, ...)

Format a string into a static buffer.

Description:This call format a string using printf style formatting arguments. A trailing null will always be appended. The call returns the size of the allocated string excluding the null.

Parameters:bufPointer to the buffer.

maxSizeSize of the buffer.

formatPrintf style format string.

...Variable arguments to format.

Returns:The buffer.

API Stability:Stable.

uint

hextoi

(cchar *str)

Convert a hex string to an integer.

Description:This call converts the supplied string to an integer using base 16.

Parameters:strPointer to the string to parse.

Returns:The integer equivalent value of the string.

API Stability:Stable.

char *

itosbuf

(char *buf, ssize size, int64 value, int radix)

Convert an integer to a string buffer.

Description:This call converts the supplied 64 bit integer into a string formatted into the supplied buffer according to the specified radix.

Parameters:bufPointer to the buffer that will hold the string.

sizeSize of the buffer.

valueInteger value to convert.

radixThe base radix to use when encoding the number.

Returns:Returns a reference to the string.

API Stability:Stable.

int

scaselesscmp

(cchar *s1, cchar *s2)

Compare strings ignoring case.

This is a safe replacement for strcasecmp. It can handle NULL args

Description:Compare two strings ignoring case differences. This call operates similarly to strcmp.

Parameters:s1First string to compare.

s2Second string to compare.

Returns:Returns zero if the strings are equivalent, < 0 if s1 sorts lower than s2 in the collating sequence or > 0 if it sorts higher.

API Stability:Stable.

bool

scaselessmatch

(cchar *s1, cchar *s2)

Compare strings ignoring case.

This is similar to scaselesscmp but it returns a boolean

Description:Compare two strings ignoring case differences.

Parameters:s1First string to compare.

s2Second string to compare.

Returns:Returns true if the strings are equivalent, otherwise false.

API Stability:Stable.

char *

sclone

(cchar *str)

Clone a string.

Description:Copy a string into a newly allocated block.

Parameters:strPointer to the block to duplicate.

Returns:Returns a newly allocated string.

API Stability:Stable.

int

scmp

(cchar *s1, cchar *s2)

Compare strings.

Description:Compare two strings. This is a safe replacement for strcmp. It can handle null args.

Parameters:s1First string to compare.

s2Second string to compare.

Returns:Returns zero if the strings are identical. Return -1 if the first string is less than the second. Return 1 if the first string is greater than the second.

API Stability:Stable.

ssize

scopy

(char *dest, ssize destMax, cchar *src)

Copy a string.

Description:Safe replacement for strcpy. Copy a string and ensure the destination buffer is not overflowed. The call returns the length of the resultant string or an error code if it will not fit into the target string. This is similar to strcpy, but it will enforce a maximum size for the copied string and will ensure it is always terminated with a null.

Parameters:destPointer to a pointer that will hold the address of the allocated block.

destMaxMaximum size of the target string in characters.

srcString to copy.

Returns:The number of characters in the target string.

API Stability:Stable.

char *

sfmt

(cchar *format, ...)

Format a string.

This is a secure version of printf that can handle null args

Description:Format the given arguments according to the printf style format. See fmt() for a full list of the format specifies. This is a secure replacement for sprintf, it can handle null arguments without crashes.

Parameters:formatPrintf style format string.

...Variable arguments for the format string.

Returns:Returns a newly allocated string.

API Stability:Stable.

char *

sfmtv

(cchar *format, va_list args)

Format a string with varargs.

This is a secure version of printf that can handle null args

Description:Format the given arguments according to the printf style format. See fmt() for a full list of the format specifies. This is a secure replacement for sprintf, it can handle null arguments without crashes.

Parameters:formatPrintf style format string.

argsVarargs argument obtained from va_start.

Returns:Returns a newly allocated string.

API Stability:Stable.

ssize

slen

(cchar *str)

Return the length of a string.

Description:Safe replacement for strlen. This call returns the length of a string and tests if the length is less than a given maximum. It will return zero for NULL args.

Parameters:strString to measure.

Returns:The length of the string.

API Stability:Stable.

char *

slower

(char *str)

Convert a string to lower case.

Description:Convert a string to its lower case equivalent.

Parameters:strString to convert. This string is modified.

Returns:Reference to the supplied str. Caller must not free.

API Stability:Stable.

bool

smatch

(cchar *s1, cchar *s2)

Compare strings.

Description:Compare two strings. This is similar to scmp but it returns a boolean.

Parameters:s1First string to compare.

s2Second string to compare.

Returns:Returns true if the strings are equivalent, otherwise false.

API Stability:Stable.

int

sncaselesscmp

(cchar *s1, cchar *s2, ssize len)

Compare strings ignoring case.

Description:Compare two strings ignoring case differences for a given string length. This call operates similarly to strncasecmp.

Parameters:s1First string to compare.

s2Second string to compare.

lenLength of characters to compare.

Returns:Returns zero if the strings are equivalent, < 0 if s1 sorts lower than s2 in the collating sequence or > 0 if it sorts higher.

API Stability:Stable.

char *

snclone

(cchar *str, ssize len)

Clone a substring.

Description:Copy a substring into a newly allocated block.

Parameters:strPointer to the block to duplicate.

lenNumber of bytes to copy. The actual length copied is the minimum of the given length and the length of the supplied string. The result is null terminated.

Returns:Returns a newly allocated string.

API Stability:Stable.

int

sncmp

(cchar *s1, cchar *s2, ssize len)

Compare strings.

Description:Compare two strings for a given string length. This call operates similarly to strncmp.

Parameters:s1First string to compare.

s2Second string to compare.

lenLength of characters to compare.

Returns:Returns zero if the strings are equivalent, < 0 if s1 sorts lower than s2 in the collating sequence or > 0 if it sorts higher.

API Stability:Stable.

ssize

sncopy

(char *dest, ssize destMax, cchar *src, ssize count)

Copy characters from a string.

Description:Safe replacement for strncpy. Copy bytes from a string and ensure the target string is not overflowed. The call returns the length of the resultant string or an error code if it will not fit into the target string. This is similar to strcpy, but it will enforce a maximum size for the copied string and will ensure it is terminated with a null.

Parameters:destPointer to a pointer that will hold the address of the allocated block.

destMaxMaximum size of the target string in characters.

srcString to copy.

countMaximum count of characters to copy.

Returns:Returns a reference to the destination if successful or NULL if the string won't fit.

API Stability:Stable.

char *

ssplit

(char *str, cchar *delim, char **last)

Split a string at a delimiter.

Description:Split a string and return parts. The string is modified. This routiner never returns null. If there are leading delimiters, the empty string will be returned and *last will be set to the portion after the delimiters. If str is null, an empty string will be returned. If there are no characters after the delimiter, then *last will be set to the empty string.

Parameters:strString to tokenize.

delimSet of characters that are used as token separators.

lastReference to the portion after the delimiters. Will return an empty string if is not trailing portion.

Returns:Returns a pointer to the first part before the delimiters. If the string begins with delimiters, the empty string will be returned.

API Stability:Evolving.

char *

stok

(char *str, cchar *delim, char **last)

Tokenize a string.

Description:Split a string into tokens.

Parameters:strString to tokenize.

delimString of characters to use as token separators.

lastLast token pointer.

Returns:Returns a pointer to the next token.

API Stability:Stable.

char *

strim

(char *str, cchar *set, int where)

Trim a string.

Description:Trim leading and trailing characters off a string.

Parameters:strString to trim.

setString of characters to remove.

whereFlags to indicate trim from the start, end or both. Use WEBS_TRIM_START, WEBS_TRIM_END, WEBS_TRIM_BOTH.

Returns:Returns a pointer to the trimmed string. May not equal str.

API Stability:Stable.

char *

supper

(char *str)

Convert a string to upper case.

Description:Convert a string to its upper case equivalent.

Parameters:strString to convert. This string is modified.

Returns:Returns a pointer to the converted string. Will always equal str. Caller must not free.

API Stability:Stable.

int

wallocHandle

(void *map)

Allocate a handle from a map.

Parameters:mapReference to a location holding the map reference. On the first call, the map is allocated.

Returns:Integer handle index. Otherwise return -1 on allocation errors.

API Stability:Stable.

int

wallocObject

(void *map, int *max, int size)

Allocate an object in a halloc map.

Parameters:mapReference to a location holding the map reference. On the first call, the map is allocated.

maxReference to an integer that holds the maximum handle in the map.

sizeSize of the object to allocate.

Returns:Integer handle index. Otherwise return -1 on allocation errors.

API Stability:Stable.

void

websRestartEvent

(int id, int delay)

Restart an event.

Parameters:idEvent id allocated by websStartEvent.

delayDelay in milliseconds till the event next runs.

API Stability:Stable.

int

websStartEvent

(int delay, WebsEventProc proc, void *data)

Start a callback event.

Description:This schedules an event to run once. The event can be rescheduled in the callback by invoking websRestartEvent.

Parameters:delayDelay in milliseconds in which to run the callback.

procCallback procedure function. Signature is: void (*fn)(void *data, int id).

dataData reference to pass to the callback.

Returns:A positive integer event ID.

API Stability:Stable.

void

websStopEvent

(int id)

Stop an event.

Parameters:idEvent id allocated by websStartEvent.

Returns:Integer handle index. Otherwise return -1 on allocation errors.

API Stability:Stable.

int

wfreeHandle

(void *map, int handle)

Free a handle in the map.

Parameters:mapReference to a location to hold the map reference.

handleHandle to free in the map.

Returns:Integer handle index. Otherwise return -1 on allocation errors.

API Stability:Stable.

WebsSession

WebsSession

Session state storage.

Fields:WebsHashcacheCache of session variables.

WebsTimeexpiresWhen the session expires.

char *idSession ID key.

intlifespanSession inactivity timeout (secs).

WebsSession *

websAllocSession

(Webs *wp, cchar *id, int lifespan)

Test if a user possesses the required ability.

Parameters:wpWebs request object.

idSession ID to use. Set to null to allocate a new session ID.

lifespanLifespan of the session in seconds.

Returns:Allocated session object.

API Stability:Stable.

See Also:

WebsSession *

websCreateSession

(Webs *wp)

Test if a user possesses the required ability.

Parameters:wpWebs request object.

Returns:Allocated session object.

API Stability:Stable.

See Also:

void

websDestroySession

(Webs *wp)

Destroy the webs session object.

Description:Useful to be called as part of the user logout process.

Parameters:wpWebs request object.

API Stability:Prototype.

See Also:

WebsSession *

websGetSession

(Webs *wp, int create)

Get the session state object for the current request.

Parameters:wpWebs request object.

createSet to true to create a new session if one does not already exist.

Returns:Session object.

API Stability:Stable.

See Also:

char *

websGetSessionID

(Webs *wp)

Get the session ID.

Parameters:wpWebs request object.

Returns:The session ID if session state storage is defined for this request. Caller must free.

API Stability:Stable.

See Also:

cchar *

websGetSessionVar

(Webs *wp, cchar *name, cchar *defaultValue)

Get a session variable.

Parameters:wpWebs 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:Stable.

See Also:

void

websRemoveSessionVar

(Webs *wp, cchar *name)

Remove a session variable.

Parameters:wpWebs request object.

nameSession variable name.

API Stability:Stable.

See Also:

int

websSetSessionVar

(Webs *wp, cchar *name, cchar *value)

Set a session variable name value.

Parameters:wpWebs request object.

nameSession variable name.

valueValue to set the variable to.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

See Also:

WebsSocket

WebsSocket

Socket control structure.

API Stability:Stable.

Fields:acceptAccept handler.

intcurrentEventsMask of ready events (FD_xx).

interrorLast error.

intfileHandleID of the file handler.

intflagsCurrent state flags.

handlerUser I/O handler.

void *handler_dataUser handler data.

inthandlerMaskHandler events of interest.

inthandshakesNumber of renegotiations.

intinterestEventsMask of events to watch for.

char *ipServer listen address or remote client address.

WebsBuflineBufLine ring queue.

intportPort to listen on.

intsaveMasksaved Mask for socketFlush.

intsecureSocket is using SSL.

intselectEventsEvents being selected.

intsidIndex into socket[].

SocketsockActual socket handle.

int

socketAddress

(struct sockaddr *addr, int addrlen, char *ipbuf, int ipLen, int *port)

Extract the numerical IP address and port for the given socket info.

Parameters:addrReference to the socket address.

addrlenLength of the socket address.

ipbufBuffer to contain the parsed IP address.

ipLenSize of ipbuf.

portReference to an integer to hold the parsed port.

Returns:Zero if successful. Otherwise -1 for parse errors.

API Stability:Stable.

void

socketCreateHandler

(int sid, int mask, SocketHandler handler, void *arg)

Create a socket handler that will be invoked when I/O events occur.

Parameters:sidSocket ID handle returned from socketConnect or socketAccept.

maskMask of events of interest. Set to SOCKET_READABLE | SOCKET_WRITABLE | SOCKET_EXCEPTION.

handlerSocket handler function.

argArbitrary object reference to pass to the SocketHandler callback function.

Returns:True if the address is an IPv6 address.

API Stability:Stable.

void

socketHiddenData

(WebsSocket *sp, ssize len, int dir)

Indicate that the application layer has buffered data for the socket.

Description:This is used by SSL and other network stacks that buffer pending data.

Parameters:spSocket object returned from socketPtr

lenLength of buffered data in bytes.

dirBuffer direction. Set to MPR_READABLE for buffered read data and MPR_WRITABLE for buffered write data.

API Stability:Stable.

int

socketInfo

(cchar *ip, int port, int *family, int *protocol, struct sockaddr_storage *addr, Socklen *addrlen)

Get a socket address structure for the specified IP:Port.

Description:This returns address details in *family, *protocol, *addr, and *addrlen.

Parameters:ipIP address to parse.

portTCP/IP port number.

familyReference to an integer to hold the address family.

protocolReference to an integer to hold the address protocol.

addrReference to an integer to hold the address structure.

addrlenReference to an integer to hold the address structure length.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

int

socketListen

(cchar *host, int port, SocketAccept accept, int flags)

int

socketParseAddress

(cchar *ipAddrPort, char **pip, int *pport, int *secure, int defaultPort)

Parse an IP address into its constituent parts.

Description:Parse the IP address and return the IP address and port components. Handles ipv4 and ipv6 addresses. If the IP portion is absent, pip is set to null. If the port portion is absent, port is set to the defaultPort. If a ":*" port specifier is used, pport is set to -1; When an address contains an ipv6 port it should be written as aaaa:bbbb:cccc:dddd:eeee:ffff:gggg:hhhh:iiii or.

If supplied an IPv6 address, the backets are stripped in the returned IP address

Parameters:ipAddrPortIP address which may contain an optional ":port" component.

pipReturns a reference to an allocated string containing the IP address portion. Caller must free.

pportReference to an integer to hold the port component.

secureReference to an integer to be set to true if the address is using SSL/TLS.

defaultPortDefault port number to use if no port specifier is included in ipAddrPort.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

void

socketReservice

(int sid)

Request that the socket be reserviced.

Description:This routine is useful when upper layers have unprocessed, buffered data for the socket. This routine will cause the socket I/O callback handler to be invoked soon in the future.

Parameters:sidSocket ID handle returned from socketConnect or socketAccept.

API Stability:Stable.

int

socketSelect

(int sid, int timeout)

Wait for I/O on a socket.

Description:This call uses the mask of events of interest defined by socketRegisterInterest. It blocks the caller until a suitable I/O event or timeout occurs.

Parameters:sidSocket ID handle returned from socketConnect or socketAccept.

timeoutTimeout in milliseconds.

Returns:Number of I/O events.

API Stability:Stable.

ssize

socketWrite

(int sid, void *buf, ssize len)

Write data to the socket.

Parameters:sidSocket ID handle returned from socketConnect or socketAccept.

bufBuffer containing data to write.

lenSize of buf.

Returns:Count of bytes written. May be less than len if the socket is in non-blocking mode. Returns -1 for errors and if the socket cannot absorb any more data. If the transport is saturated, will return a negative error and errno will be set to EAGAIN or EWOULDBLOCK.

API Stability:Stable.

WebsUpload

WebsUpload

File upload structure.

Fields:char *clientFilenameClient side name of the file.

char *contentTypeContent type.

char *filenameLocal (temp) name of the file.

ssizesizeUploaded file size.

WebsHash

websGetUpload

(struct Webs *wp)

Get the hash of uploaded files for the request.

Parameters:wpWebs request object.

Returns:Hash table of uploaded files.

API Stability:Stable.

WebsUpload *

websLookupUpload

(struct Webs *wp, cchar *key)

Open the file upload filter.

Parameters:wpWebs request object.

keyForm upload name.

Returns:Upload object for the uploaded file.

API Stability:Stable.

void

websUploadOpen

(void )

Open the file upload filter.

API Stability:Stable.

Functions

void

assert

(bool cond)

Assure that an assert condition is true.

Parameters:condBoolean result of a conditional test.

API Stability:Stable.

void

error

(cchar *fmt, ...)

Emit an error message.

Returns:Zero if successful.

API Stability:Stable.

void

logClose

(void )

Close the log logging module.

WebsLogHandler

logGetHandler

(void )

Get the log callback.

Returns:Handler Callback handler function of type WebsLogHandler.

API Stability:Stable.

void

logmsgProc

(int level, cchar *fmt, ...)

Emit a message to the log.

Description:This emits a message at the specified level. GoAhead filters logging messages by defining a verbosity level at startup. Level 0 is the least verbose where only the most important messages will be output. Level 9 is the Logging support is enabled by the MakeMe setting: "logging: true" which creates the ME_GOAHEAD_LOGGING define in me.h most verbose. Level 2-4 are the most useful for debugging.

Parameters:levelInteger verbosity level (0-9).

fmtPrintf style format string.

...Arguments for the format string.

API Stability:Stable.

int

logOpen

(void )

Open the log logging module.

Returns:Zero if successful.

Set a log callback.

Parameters:handlerCallback handler function of type WebsLogHandler.

Returns:The previous callback function.

API Stability:Stable.

void

logSetPath

(cchar *path)

Set the filename to save logging output.

Parameters:pathFilename path to use.

API Stability:Stable.

bool

sstarts

(cchar *str, cchar *prefix)

Test if the string starts with a given pattern.

Parameters:strString to examine.

prefixPattern to search for.

Returns:Returns TRUE if the pattern was found. Otherwise returns zero.

API Stability:Stable.

void

traceProc

(int level, cchar *fmt, ...)

Emit a debug trace message to the log.

Description:This emits a message at the specified level. GoAhead filters logging messages by defining a verbosity level at startup. Level 0 is the least verbose where only the most important messages will be output. Level 9 is the most verbose. Level 2-4 are the most useful for debugging. Debug trace support is enabled by the MakeMe setting: "tracing: true" which creates the ME_GOAHEAD_TRACING define in me.h.

Parameters:levelInteger verbosity level (0-9).

fmtPrintf style format string.

...Arguments for the format string.

API Stability:Stable.

void

valueFree

(WebsValue *value)

Free any allocated string in a value.

Parameters:valueValue object.

API Stability:Stable.

WebsValue

valueInteger

(long value)

Create an integer value.

Parameters:valueInteger long value.

Returns:Value object containing the integer.

API Stability:Stable.

WebsValue

valueString

(cchar *value, int flags)

Create an string value.

Parameters:valueString long value.

flagsSet to VALUE_ALLOCATE to store a copy of the string reference.

Returns:Value object containing the string.

API Stability:Stable.

WebsValue

valueSymbol

(void *value)

Create an symbol value containing an object reference.

Parameters:valueValue reference.

Returns:Value object containing the symbol reference.

API Stability:Stable.

void *

walloc

(ssize size)

Allocate a block of the requested size.

Parameters:sizeMemory size required.

Returns:A reference to the allocated block.

API Stability:Stable.

void

wcloseAlloc

(void )

Close the GoAhead memory allocator.

API Stability:Stable.

void *

wdup

(cvoid *ptr, ssize usize)

Duplicate memory.

Parameters:ptrOriginal block reference.

usizeSize to allocate.

Returns:Reference to the new memory block.

bool

websCheckPassword

(cchar *plainTextPassword, cchar *passwordHash)

Check a plain-text password against the defined hashed password.

Parameters:plainTextPasswordUser's plain-text-password to check.

passwordHashRequired password in hashed format previously computed by websMakePassword.

Returns:True if the password is correct.

API Stability:Prototype.

char *

websCryptPassword

(cchar *password, cchar *salt, int rounds)

Encrypt a password using the Blowfish algorithm.

Parameters:passwordUser's password to encrypt.

saltSalt text to add to password. Helps to make each user's password unique.

roundsNumber of times to encrypt. More times, makes the routine slower and passwords harder to crack.

Returns:The encrypted password.

API Stability:Prototype.

int

websGetRandomBytes

(char *buf, ssize length, bool block)

Get some random data.

Parameters:bufReference to a buffer to hold the random data.

lengthSize of the buffer.

blockSet to true if it is acceptable to block while accumulating entropy sufficient to provide good random data. Setting to false will cause this API to not block and may return random data of a lower quality.

API Stability:Prototype.

char *

websMakePassword

(cchar *password, int saltLength, int rounds)

Make a password hash for a plain-text password using the Blowfish algorithm.

Parameters:passwordUser's password to encrypt.

saltLengthLength of salt text to add to password. Helps to make each user's password unique.

roundsNumber of times to encrypt. More times, makes the routine slower and passwords harder to crack.

Returns:The encrypted password. Caller must free.

API Stability:Prototype.

char *

websMakeSalt

(ssize size)

Make salt for adding to a password.

Parameters:sizeSize in bytes of the salt text.

Returns:The random salt text. Caller must free.

API Stability:Prototype.

char *

websReadPassword

(cchar *prompt)

Get a password from the terminal console.

Parameters:promptText prompt to display before reading the password.

Returns:The entered password. Caller must free.

API Stability:Prototype.

void

websSetBackgroundWriter

(Webs *wp, WebsWriteProc proc)

Define a background write I/O event callback.

Parameters:wpWebs request object.

procWrite callback.

void

websSetMemNotifier

(WebsMemNotifier cback)

Define a global memory allocation notifier.

Description:The notifier is called if any memory allocation fails. It is called with the requested allocation size as its only parameter.

Parameters:cbackCallback function to invoke for allocation failures.

API Stability:Evolving.

void

wfree

(void *blk)

Free an allocated block of memory.

Parameters:blkReference to the memory block to free.

API Stability:Stable.

int

wopenAlloc

(void *buf, int bufsize, int flags)

Initialize the walloc module.

Description:The wopenAlloc function should be called the very first thing after the application starts and wclose should be called the last thing before exiting. If wopenAlloc is not called, it will be called on the first allocation with default values. "buf" points to memory to use of size "bufsize". If buf is NULL, memory is allocated using malloc. flags may be set to WEBS_USE_MALLOC if using malloc is okay. This routine will allocate * an initial buffer of size bufsize for use by the application.

Parameters:bufOptional user supplied block of memory to use for allocations.

bufsizeSize of buf.

flagsAllocation flags. Set to WEBS_USE_MALLOC to permit the use of malloc() to grow memory.

Returns:Zero if successful, otherwise -1.

API Stability:Stable.

void *

wrealloc

(void *blk, ssize newsize)

Reallocate a block of memory and grow its size.

Description:If the new size is larger than the existing block, a new block will be allocated and the old data will be copied to the new block.

Parameters:blkOriginal block reference.

newsizeSize of the new block.

Returns:Reference to the new memory block.

API Stability:Stable.

Typedefs

typedef int WebsHash.

Hash table ID returned by hashCreate.

typedef void(* WebsLogHandler) (int level, cchar *msg).

Callback for emitting trace log output.

Parameters:levelInteger between 0 and 9. Zero is the lowest trace level used for the most important messages.

msgMessage to log.

Returns:Zero if successful.

typedef struct stat WebsStat.

File status structure.

typedef time_t WebsTime.

System native time type.

This is the time in seconds. This may be 32 or 64 bits and may be signed or unsigned on some systems

typedef void(* WebsWriteProc) (struct Webs *wp).

Callback for write I/O events.

typedef void(* WebsAction) (Webs *wp).

Action callback.

Parameters:wpWebs request object.

API Stability:Stable.

See Also:

typedef void(* WebsAskLogin) (Webs *wp).

Callback to prompt the user for their password.

Parameters:wpWebs request object.

API Stability:Stable.

See Also:

typedef void(* WebsHandlerClose) (void).

GoAhead handler close to release memory prior to shutdown.

Description:This callback is invoked when GoAhead is shutting down.

API Stability:Stable.

See Also:

typedef bool(* WebsHandlerProc) (Webs *wp).

GoAhead handler service callback.

Parameters:wpWebs request object.

Returns:True if the handler serviced the request.

API Stability:Stable.

See Also:

typedef int(* WebsJstProc) (int jid, Webs *wp, int argc, char **argv).

Javascript native function.

Parameters:jidJavaScript engine ID.

wpWebs request object.

argcCount of function arguments.

argvArray of function arguments.

defaultValueDefault value to return if the variable is not defined.

Returns:Return zero if successful, otherwise -1.

API Stability:Stable.

See Also:

typedef bool(* WebsParseAuth) (Webs *wp).

Callback to parse authentication details submitted with the web request.

Parameters:wpWebs request object.

Returns:True if the details can be parsed.

API Stability:Stable.

See Also:

typedef bool(* WebsVerify) (Webs *wp).

Callback to verify the username and password.

Parameters:wpWebs request object.

Returns:True if the password is verified.

API Stability:Stable.

See Also:

typedef void(* WebsEventProc) (void *data, int id).

typedef void(* SocketHandler) (int sid, int mask, void *data).

WebsError

Error code list.

API Stability:Stable.

Fields:intcodeHTTP error code.

char *msgHTTP error message.

WebsFileInfo

File information structure.

API Stability:Stable.

Fields:intisDirSet if directory.

WebsTimemtimeModified time.

ulongsizeFile length.

WebsHandler

GoAhead handler object.

API Stability:Stable.

Fields:closeHandler close callback

intflagsHandler control flags.

matchHandler match callback.

char *nameHandler name.

serviceHandler service callback.

WebsMime

Mime type list.

API Stability:Stable.

Fields:char *extFile extension.

char *typeMime type.

WebsRole

Role definition structure.

API Stability:Stable.

Fields:WebsHashabilitiesResolved role abilities.

WebsRomIndex

Compiled Rom Page Index.

API Stability:Stable.

Fields:uchar *pageWeb page data.

char *pathWeb page URL path.

OffsetposCurrent read position.

intsizeSize of web page in bytes.

WebsUser

User definition structure.

API Stability:Stable.

Fields:WebsHashabilitiesResolved user abilities.

char *nameUser name.

char *passwordUser password (encrypted).

char *rolesUser roles.

WebsValue

Value union to store primitive value types.

Fields:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值