GoAhead API

Function Index

ssizeappendWinArg(char *dp, cchar *arg)
 Emit one CRT-correctly-quoted argv element into the destination buffer.
voidassert(bool cond)
 Assure that an assert condition is true.
voidbufAddNull(WebsBuf *bp)
 Add a trailing null to the buffer.
voidbufAdjustEnd(WebsBuf *bp, ssize size)
 Adjust the endp pointer by the specified size.
voidbufAdjustStart(WebsBuf *bp, ssize count)
 Adjust the start (servp) reference.
voidbufCompact(WebsBuf *bp)
 Compact the data in the buffer and move to the start of the buffer.
intbufCreate(WebsBuf *bp, int increment, int maxsize)
 Create and initialize a buffer.
voidbufFlush(WebsBuf *bp)
 Flush all data in the buffer and reset the pointers.
voidbufFree(WebsBuf *bp)
 Free allocated storage for the buffer.
ssizebufGetBlk(WebsBuf *bp, char *blk, ssize len)
 Copy a block of from the buffer and adjust the servp.
ssizebufGetBlkMax(WebsBuf *bp)
 Return the maximum number of bytes the buffer can provide via a single block copy.
intbufGetc(WebsBuf *bp)
 Get a character from the buffer and increment the servp.
boolbufGrow(WebsBuf *bp, ssize room)
 Grow the buffer by at least the required amount of room.
intbufInsertc(WebsBuf *bp, char c)
 Insert a character to the buffer before the servp position and decrement the servp.
ssizebufLen(WebsBuf *bp)
 Get the length of available data in the buffer.
ssizebufPut(WebsBuf *bp, cchar *fmt, ...) PRINTF_ATTRIBUTE(2
 Append a formatted string to the buffer at the endp position and increment the endp.
ssizebufPutBlk(WebsBuf *bp, cchar *blk, ssize len)
 Put a block to the buffer.
ssize ssizebufPutStr(WebsBuf *bp, cchar *str)
 Append a string to the buffer at the endp position and increment the endp.
intbufPutc(WebsBuf *bp, char c)
 Append a character to the buffer at the endp position and increment the endp.
voidbufReset(WebsBuf *bp)
 Reset the buffer pointers to the start of the buffer if empty.
ssizebufRoom(WebsBuf *bp)
 Determine the room available in the buffer.
char *bufStart(WebsBuf *bp)
 Get a reference to the start of buffer data.
ssizebuildWinCmdLine(char **argp, char *out)
 Build a Windows lpCommandLine string from a NULL-terminated argv array.
voiderror(cchar *fmt, ...)
 Emit an error message.
char *fmt(char *buf, ssize maxSize, cchar *format, ...)
 GoAhead Web Server Runtime.
WebsHashhashCreate(int size)
 Create a hash table.
inthashDelete(WebsHash id, cchar *name)
 Delete a key by name.
WebsKey *hashEnter(WebsHash id, cchar *name, WebsValue value, int arg)
 Enter a new key and value into the hash table.
WebsKey *hashFirst(WebsHash id)
 Start walking the hash keys by returning the first key entry in the hash.
voidhashFree(WebsHash id)
 Free a hash table.
WebsKey *hashLookup(WebsHash id, cchar *name)
 Lookup a name in the hash table.
void *hashLookupSymbol(WebsHash sd, cchar *name)
 Lookup a name in the hash table and return a symbol reference.
WebsKey *hashNext(WebsHash id, WebsKey *last)
 Continue walking the hash keys by returning the next key entry in the hash.
uinthextoi(cchar *str)
 Convert a hex string to an integer.
boolisCgiExeOnWindows(cchar *cgiPath)
 Test whether a CGI path is admissible as a Windows CGI target.
char *itosbuf(char *buf, ssize size, int64 value, int radix)
 Convert an integer to a string buffer.
voidlogClose(void)
 Close the log logging module.
WebsLogHandlerlogGetHandler(void)
 Get the log callback.
intlogOpen(void)
 Open the log logging module.
WebsLogHandlerlogSetHandler(WebsLogHandler handler)
 Set a log callback.
voidlogSetPath(cchar *path)
 Set the filename to save logging output.
voidlogmsgProc(int level, cchar *fmt, ...)
 Emit a message to the log.
intscaselesscmp(cchar *s1, cchar *s2)
 Compare strings ignoring case.
boolscaselessmatch(cchar *s1, cchar *s2)
 Compare strings ignoring case.
char *sclone(cchar *str)
 Clone a string.
intscmp(cchar *s1, cchar *s2)
 Compare strings.
ssizescopy(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.
ssizeslen(cchar *str)
 Return the length of a string.
char *slower(char *str)
 Convert a string to lower case.
boolsmatch(cchar *s1, cchar *s2)
 Compare strings.
intsncaselesscmp(cchar *s1, cchar *s2, ssize len)
 Compare strings ignoring case.
char *snclone(cchar *str, ssize len)
 Clone a substring.
intsncmp(cchar *s1, cchar *s2, ssize len)
 Compare strings.
ssizesncopy(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.
boolsocketAddressIsV6(cchar *ip)
 Determine if an IP address is an IPv6 address.
intsocketAlloc(cchar *host, int port, SocketAccept accept, int flags)
 Allocate a socket object.
voidsocketClose(void)
 Close the socket module.
voidsocketCloseConnection(int sid)
 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.
voidsocketDeleteHandler(int sid)
 Delete a socket handler created via socketCreateHandler.
boolsocketEof(int sid)
 Determine if the socket is at end-of-file for input.
voidsocketFree(int sid)
 Free (and close) the socket.
intsocketGetBlock(int sid)
 Get the current blocking mode.
intsocketGetError(int sid)
 Get the error code for the last socket operation on this thread.
SocketsocketGetHandle(int sid)
 Get the underlying socket operating system socket/file handle.
WebsSocket **socketGetList(void)
 Get the list of sockets.
intsocketGetPort(int sid)
 Get the IP port associated with this socket.
boolsocketHasDualNetworkStack(void)
 Indicate if the system has a dual IPv4 and IPv6 stack.
boolsocketHasIPv6(void)
 Indicate if the system has IPv6 support.
voidsocketHiddenData(WebsSocket *sp, ssize len, int dir)
 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.
boolsocketIsV6(int sid)
 Determine if a socket is bound to an IPv6 address.
intsocketListen(cchar *host, int port, SocketAccept accept, int flags)
 Open a listening socket.
intsocketOpen(void)
 Open the socket module.
intsocketParseAddress(cchar *ipAddrPort, char **pip, int *pport, int *secure, int defaultPort)
 Parse an IP address into its constituent parts.
voidsocketProcess(void)
 Process pending socket I/O events.
WebsSocket *socketPtr(int sid)
 Return the socket object for the socket ID.
ssizesocketRead(int sid, void *buf, ssize len)
 Read data from a socket.
voidsocketRegisterInterest(int sid, int mask)
 Register interest in socket I/OEvents.
voidsocketReservice(int sid)
 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.
voidsocketSetError(int error)
 Set the error code for the last socket operation on this thread.
intsocketSetNoDelay(int sid, bool on)
 Set the socket delay mode.
intsocketWaitForEvent(WebsSocket *sp, int mask)
 Wait for a socket I/O event.
ssizesocketWrite(int sid, void *buf, ssize len)
 Write data to the socket.
voidsslClose(void)
 Close the ssl module.
voidsslFree(Webs *wp)
 Free a ssl connection associated with a request.
intsslOpen(void)
 Open the ssl module.
ssizesslRead(Webs *wp, void *buf, ssize len)
 Read data from a secure socket.
intsslUpgrade(Webs *wp)
 Upgrade a request connection to utilize SSL.
ssizesslWrite(Webs *wp, void *buf, ssize len)
 WRite data to a secure socket.
char *ssplit(char *str, cchar *delim, char **last)
 Split a string at a delimiter.
boolsstarts(cchar *str, cchar *prefix)
 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.
voidvalueFree(WebsValue *value)
 Free any allocated string in a value.
WebsValuevalueInteger(long value)
 Create an integer value.
WebsValuevalueString(cchar *value, int flags)
 Create an string value.
WebsValuevalueSymbol(void *value)
 Create an symbol value containing an object reference.
void *walloc(ssize size)
 Allocate a block of the requested size.
intwallocHandle(void *map)
 Allocate a handle from a map.
intwallocObject(void *map, int *max, int size)
 Allocate an object in a halloc map.
voidwcloseAlloc(void)
 Close the GoAhead memory allocator.
void *wdup(cvoid *ptr, ssize usize)
 Duplicate memory.
intwebsAccept(int sid, cchar *ipaddr, int port, int listenSid)
 Accept a new connection.
voidwebsActionOpen(void)
 Open the action handler.
WebsRole *websAddRole(cchar *role, WebsHash abilities)
 Add a role.
WebsRoute *websAddRoute(cchar *uri, cchar *handler, int pos)
 Add a route to the routing tables.
WebsUser *websAddUser(cchar *username, cchar *password, cchar *roles)
 Add a user.
intwebsAlloc(int sid)
 Allocate a new Webs object.
WebsSession *websAllocSession(Webs *wp, cchar *id, int lifespan)
 Test if a user possesses the required ability.
boolwebsAuthenticate(Webs *wp)
 Authenticate a user for the current request.
boolwebsCan(Webs *wp, WebsHash ability)
 Test if a user possesses the required ability.
voidwebsCancelTimeout(Webs *wp)
 Cancel the request timeout.
intwebsCgiHandler(Webs *wp)
 CGI handler service callback.
intwebsCgiOpen(void)
 Open the CGI handler.
intwebsCgiPoll(void)
 Poll for output from CGI processes and output.
boolwebsCheckPassword(cchar *plainTextPassword, cchar *passwordHash)
 Check a plain-text password against the defined hashed password.
voidwebsClose(void)
 Close the core GoAhead web server module.
voidwebsCloseAuth(void)
 Close the authentication module.
voidwebsCloseFile(int fd)
 Close an open file.
voidwebsCloseRoute(void)
 Close the route module.
intwebsCompareVar(Webs *wp, cchar *var, cchar *value)
 Compare a request variable.
voidwebsComputeAllUserAbilities(void)
 Compute the abilities for all users by resolving roles into abilities.
voidwebsConsumeInput(Webs *wp, ssize nbytes)
 Consume input from the request input buffer.
WebsSession *websCreateSession(Webs *wp)
 Test if a user possesses the required ability.
char *websCryptPassword(cchar *password, cchar *salt, int rounds)
 Encrypt a password using the Blowfish algorithm.
char *websDecode64(char *str)
 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.
intwebsDefineAction(cchar *name, void *fun)
 Define an action callback for use with the action handler.
intwebsDefineHandler(cchar *name, WebsHandlerProc match, WebsHandlerProc service, WebsHandlerClose close, int flags)
 Define a custom request handler.
intwebsDefineJst(cchar *name, WebsJstProc fn)
 Define a Javscript native function.
voidwebsDestroySession(Webs *wp)
 Destroy the webs session object.
voidwebsDone(Webs *wp)
 Complete a request.
char *websEncode64(char *str)
 Encode a string using base-64 encoding.
char *websEncode64Block(char *str, ssize len)
 Encode a block using base-64 encoding.
voidwebsError(Webs *wp, int code, cchar *fmt, ...)
 Complete a request with an error response.
cchar *websErrorMsg(int code)
 Get a message for a HTTP status code.
char *websEscapeHtml(cchar *str)
 Escape unsafe characters in a string.
char *websEscapeUri(cchar *str)
 Escape unsafe URI characters in a string using CC substitution.
voidwebsFileOpen(void)
 Open and initialize the file handler.
intwebsFlush(Webs *wp, bool block)
 Flush buffered transmit data and compact the transmit buffer to make room for more data.
voidwebsFree(Webs *wp)
 Free the webs request object.
voidwebsFreeUpload(Webs *wp)
 Free file upload data structures.
voidwebsFsClose(void)
 Close the file system module.
intwebsFsOpen(void)
 Open the file system module.
intwebsGetBackground(void)
 Get the background execution flag.
char *websGetCgiCommName(void)
 Get a unique temporary filename for CGI communications.
cchar *websGetCookie(Webs *wp)
 Get the request cookie if supplied.
char *websGetDateString(WebsFileInfo *sbuf)
 Get a date as a string.
intwebsGetDebug(void)
 Get the debug flag.
cchar *websGetDir(Webs *wp)
 Get the base file directory for a request.
char *websGetDocuments(void)
 Get the GoAhead base documents directory.
intwebsGetEof(Webs *wp)
 Get the request EOF status.
cchar *websGetExt(Webs *wp)
 Get the request URI extension.
cchar *websGetFilename(Webs *wp)
 Get the request filename.
cchar *websGetHost(Webs *wp)
 Get the request host.
cchar *websGetIfaddr(Webs *wp)
 Get the request interface address.
cchar *websGetIndex(void)
 Get the default index document name.
intwebsGetLogLevel(void)
 Get the current trace log level.
cchar *websGetMethod(Webs *wp)
 Get the request method.
cchar *websGetPassword(Webs *wp)
 Get the request password.
WebsVerifywebsGetPasswordStoreVerify(void)
 Set the password store verify callback.
cchar *websGetPath(Webs *wp)
 Get the request path.
intwebsGetPort(Webs *wp)
 Get the request TCP/IP port.
cchar *websGetProtocol(Webs *wp)
 Get the request HTTP protocol.
cchar *websGetQuery(Webs *wp)
 Get the request query component.
intwebsGetRandomBytes(char *buf, ssize length, bool block)
 Get some random data.
WebsHashwebsGetRoles(void)
 Get the roles hash.
cchar *websGetServer(void)
 Get the server host name.
cchar *websGetServerAddress(void)
 Get the server IP address.
cchar *websGetServerAddressUrl(void)
 Get the server IP address with port number.
cchar *websGetServerUrl(void)
 Get the server host name with port number.
WebsSession *websGetSession(Webs *wp, int create)
 Get the session state object for the current request.
char *websGetSessionID(Webs *wp)
 Get the session ID.
cchar *websGetSessionVar(Webs *wp, cchar *name, cchar *defaultValue)
 Get a session variable.
WebsHashwebsGetUpload(struct Webs *wp)
 Get the hash of uploaded files for the request.
cchar *websGetUrl(Webs *wp)
 Get the request URI.
cchar *websGetUserAgent(Webs *wp)
 Get the client User-Agent HTTP header.
cchar *websGetUsername(Webs *wp)
 Get the request username.
WebsHashwebsGetUsers(void)
 Get the users hash.
cchar *websGetVar(Webs *wp, cchar *name, cchar *defaultValue)
 Get a request variable.
intwebsJstOpen(void)
 Open the Javascript module.
intwebsJstWrite(int jid, Webs *wp, int argc, char **argv)
 Write data to the response.
intwebsListen(cchar *endpoint)
 Listen on a TCP/IP address endpoint.
intwebsLoad(cchar *path)
 Load routing tables from the specified filename.
boolwebsLoginUser(Webs *wp, cchar *username, cchar *password)
 Login a user by verifying the login credentials.
boolwebsLogoutUser(Webs *wp)
 Logout a user and remove the user login session.
WebsUpload *websLookupUpload(struct Webs *wp, cchar *key)
 Open the file upload filter.
WebsUser *websLookupUser(cchar *username)
 Lookup if a user exists.
char *websMD5(cchar *str)
 Get an MD5 digest of a string.
char *websMD5Block(cchar *buf, ssize length, cchar *prefix)
 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.
char *websMakeSalt(ssize size)
 Make salt for adding to a password.
char *websNormalizeUriPath(cchar *path)
 Normalize a URI path.
voidwebsNoteRequestActivity(Webs *wp)
 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.
intwebsOpenRoute(void)
 Open the routing module.
intwebsOptionsOpen(void)
 Open the options handler.
voidwebsOsClose(void)
 Close the O/S dependent code.
intwebsOsOpen(void)
 Open the O/S dependent code.
voidwebsPageClose(Webs *wp)
 Close the document page.
intwebsPageIsDirectory(Webs *wp)
 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.
ssizewebsPageReadData(Webs *wp, char *buf, ssize size)
 Read data from the request page document.
voidwebsPageSeek(Webs *wp, Offset offset, int origin)
 Seek to a position in the request page document.
intwebsPageStat(Webs *wp, WebsFileInfo *sbuf)
 Get file status for the current request document.
intwebsParseArgs(char *args, char **argv, int maxArgc)
 Parse a command line string into arguments.
intwebsParseDateTime(WebsTime *time, cchar *date, struct tm *defaults)
 Parse a date/time string.
boolwebsProcessCgiData(Webs *wp)
 Process CGI request body data.
boolwebsProcessUploadData(Webs *wp)
 Process upload data for form, multipart mime file upload.
voidwebsPump(Webs *wp)
 Pump the state machine.
ssizewebsReadFile(int fd, char *buf, ssize size)
 Read data from an open file.
char *websReadPassword(cchar *prompt)
 Get a password from the terminal console.
char *websReadWholeFile(cchar *path)
 Read all the data from a file.
voidwebsRedirect(Webs *wp, cchar *url)
 Redirect the client to a new URL.
intwebsRedirectByStatus(Webs *wp, int status)
 Redirect the client to a new URI.
intwebsRemoveRole(cchar *role)
 Remove a role from the system.
intwebsRemoveRoute(cchar *uri)
 Remove a route from the routing tables.
voidwebsRemoveSessionVar(Webs *wp, cchar *name)
 Remove a session variable.
intwebsRemoveUser(cchar *name)
 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.
intwebsRewriteRequest(Webs *wp, cchar *url)
 Rewrite a request.
voidwebsRouteRequest(Webs *wp)
 Route a request.
intwebsRunEvents(void)
 Run due events.
boolwebsRunRequest(Webs *wp)
 Run a request handler.
voidwebsRuntimeClose(void)
 Close the runtime code.
intwebsRuntimeOpen(void)
 Open the runtime code.
OffsetwebsSeekFile(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.
voidwebsServiceEvents(int *finished)
 Service I/O events until finished.
voidwebsSetBackground(int on)
 Set the background processing flag.
voidwebsSetBackgroundWriter(Webs *wp, WebsWriteProc proc)
 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.
voidwebsSetDebug(int on)
 Set the debug processing flag.
voidwebsSetDocuments(cchar *dir)
 Set the web documents directory.
voidwebsSetEnv(Webs *wp)
 Create CGI environment variables for the current request.
voidwebsSetFormVars(Webs *wp)
 Create request variables for query and POST body data.
voidwebsSetHost(cchar *host)
 Define the host name for the server.
voidwebsSetIndex(cchar *filename)
 Set the default index document filename.
voidwebsSetIpAddr(cchar *ipaddr)
 Define the host IP address.
voidwebsSetLogLevel(int level)
 Set the current trace log level.
voidwebsSetMemNotifier(WebsMemNotifier cback)
 Define a global memory allocation notifier.
voidwebsSetPasswordStoreVerify(WebsVerify verify)
 Set the password store verify callback.
voidwebsSetPostLimit(ssize limit)
 Override the runtime POST body size cap.
voidwebsSetQueryVars(Webs *wp)
 Create request variables for query string data.
intwebsSetRouteAuth(WebsRoute *route, cchar *authType)
 Set route authentication scheme.
intwebsSetRouteMatch(WebsRoute *route, cchar *dir, cchar *protocol, WebsHash methods, WebsHash extensions, WebsHash abilities, WebsHash redirects)
 Configure a route by adding matching criteria.
intwebsSetSessionVar(Webs *wp, cchar *name, cchar *value)
 Set a session variable name value.
voidwebsSetSslCertFile(cchar *path)
 Override the server SSL certificate path at runtime.
voidwebsSetSslKeyFile(cchar *path)
 Override the server SSL private key path at runtime.
voidwebsSetStatus(Webs *wp, int status)
 Set the response HTTP status code.
voidwebsSetTxLength(Webs *wp, ssize length)
 Set the response body content length.
intwebsSetUserPassword(cchar *username, cchar *password)
 Set a password for the user.
intwebsSetUserRoles(cchar *username, cchar *roles)
 Define the set of roles for a user.
WebsKey *websSetVar(Webs *wp, cchar *name, cchar *value)
 Set a request variable to a string value.
WebsKey *websSetVarFmt(Webs *wp, cchar *name, cchar *fmt, ...)
 Set a request variable to a formatted string value.
intwebsStartEvent(int delay, WebsEventProc proc, void *data)
 Start a callback event.
intwebsStatFile(cchar *path, WebsFileInfo *sbuf)
 Get file status for a file.
voidwebsStopEvent(int id)
 Stop an event.
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.
boolwebsTestVar(Webs *wp, cchar *name)
 Test if a request variable is defined.
voidwebsTimeClose(void)
 Close the date/time parsing module.
intwebsTimeOpen(void)
 Open the date/time parsing module.
voidwebsUploadOpen(void)
 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.
boolwebsValid(Webs *wp)
 Test if a webs object is valid.
boolwebsValidUriChars(cchar *uri)
 Test if a URI is using only valid characters Note this does not test if the URI is fully legal.
char *websValidateUriPath(cchar *uri)
 Validate a URI path as expected in a HTTP request line.
boolwebsVerifyPasswordFromCustom(Webs *wp)
 User password verification routine from a custom password back-end store.
boolwebsVerifyPasswordFromFile(Webs *wp)
 User password verification routine from auth.txt.
ssizewebsWrite(Webs *wp, cchar *fmt, ...)
 Write formatted data to the response.
ssizewebsWriteBlock(Webs *wp, cchar *buf, ssize size)
 Write a block of data to the response.
voidwebsWriteEndHeaders(Webs *wp)
 Signify the end of the response headers.
ssizewebsWriteFile(int fd, cchar *buf, ssize size)
 Write data to the open file.
intwebsWriteHeader(Webs *wp, cchar *key, cchar *fmt, ...)
 Write a response header.
voidwebsWriteHeaders(Webs *wp, ssize contentLength, cchar *redirect)
 Write a set of standard response headers.
ssizewebsWriteSocket(Webs *wp, cchar *buf, ssize size)
 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.

Typedef Index

SocketAcceptSocket accept callback.
SocketHandlerSocket I/O callback.
WebsGoAhead HTTP request/response structure.
WebsActionAction callback.
WebsAskLoginCallback to prompt the user for their password.
WebsBufDynamic buffer (ring queue) for efficient I/O operations.
WebsErrorError code list.
WebsEventProcCallback function for events.
WebsFileInfoFile information structure.
WebsHandlerGoAhead handler object.
WebsHandlerCloseGoAhead handler close to release memory prior to shutdown.
WebsHandlerProcGoAhead handler service callback.
WebsHashHash table ID returned by hashCreate.
WebsJstProcJavascript native function.
WebsKeyHash table key-value entry structure.
WebsLogHandlerCallback for emitting trace log output.
WebsMimeMime type list.
WebsParseAuthCallback to parse authentication details submitted with the web request.
WebsRoleRole definition structure.
WebsRomIndexCompiled Rom Page Index.
WebsRouteRequest route structure.
WebsSessionSession state storage.
WebsSocketSocket control structure for network I/O management.
WebsStatFile status structure.
WebsTimeSystem native time type.
WebsUploadFile upload structure.
WebsUserGoAhead Authentication.
WebsValueValue union to store primitive value types.
WebsVerifyCallback to verify the username and password.
WebsWriteProcCallback for write I/O events.

Defines

#defineHTTP_CODE_ACCEPTED   202
 The request has been accepted and processing is continuing.
#defineHTTP_CODE_BAD_GATEWAY   502
 The server cannot act as a gateway for the given request.
#defineHTTP_CODE_BAD_METHOD   405
 The request HTTP method was not supported by the resource.
#defineHTTP_CODE_BAD_REQUEST   400
 The request is malformed.
#defineHTTP_CODE_BAD_VERSION   505
 The server does not support the HTTP protocol version.
#defineHTTP_CODE_COMMS_ERROR   550
 The server had a communications error responding to the client.
#defineHTTP_CODE_CONFLICT   409
 The request had a conflict in the request headers and URI.
#defineHTTP_CODE_CONTINUE   100
 Standard HTTP/1.1 status codes and GoAhead-specific extensions.
#defineHTTP_CODE_CREATED   201
 The request has completed and a new resource was created.
#defineHTTP_CODE_EXPECTATION_FAILED   417
 The server cannot satisfy the Expect header requirements.
#defineHTTP_CODE_FORBIDDEN   403
 The request was legal, but the server refuses to process.
#defineHTTP_CODE_GATEWAY_TIMEOUT   504
 The server gateway timed out waiting for the upstream server.
#defineHTTP_CODE_GONE   410
 The requested resource is no longer available.
#defineHTTP_CODE_INSUFFICIENT_STORAGE   507
 The server has insufficient storage to complete the request.
#defineHTTP_CODE_INTERNAL_SERVER_ERROR   500
 Server processing or configuration error.
#defineHTTP_CODE_LENGTH_REQUIRED   411
 The request did not specify a required content length.
#defineHTTP_CODE_MOVED_PERMANENTLY   301
 The requested URI has moved permanently to a new location.
#defineHTTP_CODE_MOVED_TEMPORARILY   302
 The URI has moved temporarily to a new location.
#defineHTTP_CODE_NO_CONTENT   204
 The request has completed and there is no response to send.
#defineHTTP_CODE_NO_RESPONSE   444
 The connection was closed with no response to the client.
#defineHTTP_CODE_NOT_ACCEPTABLE   406
 The requested resource cannot generate the required content.
#defineHTTP_CODE_NOT_AUTHORITATIVE   203
 The request has completed but content may be from another source.
#defineHTTP_CODE_NOT_FOUND   404
 The requested resource was not found.
#defineHTTP_CODE_NOT_IMPLEMENTED   501
 The server does not recognize the request or method.
#defineHTTP_CODE_NOT_MODIFIED   304
 The requested resource has not changed since the last request.
#defineHTTP_CODE_OK   200
 The request completed successfully.
#defineHTTP_CODE_PARTIAL   206
 The request has completed and is returning partial content.
#defineHTTP_CODE_PAYMENT_REQUIRED   402
 Reserved for future use.
#defineHTTP_CODE_PRECOND_FAILED   412
 The server cannot satisfy one of the request preconditions.
#defineHTTP_CODE_RANGE_NOT_SATISFIABLE   416
 The request content range does not exist for the resource.
#defineHTTP_CODE_REQUEST_TIMEOUT   408
 The server timed out waiting for the request to complete.
#defineHTTP_CODE_REQUEST_TOO_LARGE   413
 The request is too large for the server to process.
#defineHTTP_CODE_REQUEST_URL_TOO_LARGE   414
 The request URI is too long for the server to process.
#defineHTTP_CODE_RESET   205
 The request has completed with no content.
#defineHTTP_CODE_SEE_OTHER   303
 The requested URI can be found at another URI location.
#defineHTTP_CODE_SERVICE_UNAVAILABLE   503
 The server is currently unavailable or overloaded.
#defineHTTP_CODE_TEMPORARY_REDIRECT   307
 The request should be repeated at another URI location.
#defineHTTP_CODE_UNAUTHORIZED   401
 Authentication for the request has failed.
#defineHTTP_CODE_UNSUPPORTED_MEDIA_TYPE   415
 The request media type is not supported by the server or resource.
#defineHTTP_CODE_USE_PROXY   305
 The requested resource must be accessed via the location proxy.
#defineME_MAX_IP   64
 Maximum IP address size.
#defineSOCKET_AGAIN   4
 Issue the request again.
#defineSOCKET_ASYNC   0x8
 Use async connect.
#defineSOCKET_BLOCK   0x10
 Use blocking I/O.
#defineSOCKET_BUFFERED_READ   0x200
 Message pending on this socket.
#defineSOCKET_BUFFERED_WRITE   0x400
 Message pending on this socket.
#defineSOCKET_CLOSING   0x40
 Socket is closing.
#defineSOCKET_CONNECTING   0x2
 Connect in progress.
#defineSOCKET_CONNRESET   0x80
 Socket connection was reset.
#defineSOCKET_EOF   0x1
 Seen end of file.
#defineSOCKET_EXCEPTION   0x8
 Interested in exceptions.
#defineSOCKET_HANDSHAKING   0x100
 Doing SSL handshake.
#defineSOCKET_INTR   5
 Call was interrupted.
#defineSOCKET_INVAL   6
 Invalid.
#defineSOCKET_LISTENING   0x20
 Socket is server listener.
#defineSOCKET_NETDOWN   3
 Network is down.
#defineSOCKET_NODELAY   0x800
 Disable Nagle algorithm.
#defineSOCKET_PORT_MAX   0xffff
 Max Port size.
#defineSOCKET_READABLE   0x2
 Make socket readable.
#defineSOCKET_RESERVICE   0x4
 Socket needs re-servicing.
#defineSOCKET_RESET   2
 Socket has been reset.
#defineSOCKET_WOULDBLOCK   1
 Socket would block on I/O.
#defineSOCKET_WRITABLE   0x4
 Make socket writable.
#defineVALUE_ALLOCATE   0x1
 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.
#defineWEBS_ASSERT_MSG   0x10
 Originated from assert.
#defineWEBS_BEGIN   0
 States that track the progression of HTTP request processing through GoAhead's request handling pipeline.
#defineWEBS_CHUNK_DATA   3
 Processing chunk data content.
#defineWEBS_CHUNK_HEADER   2
 Preparing to transmit chunk header.
#defineWEBS_CHUNK_START   1
 At the start of a new chunk.
#defineWEBS_CHUNK_UNCHUNKED   0
 States used to track HTTP chunked transfer encoding processing.
#defineWEBS_CLOSE   0x20000
 Close connection.
#defineWEBS_CODE_MASK   0xFFFF
 Mask valid status codes.
#defineWEBS_COMPLETE   4
 Request processing has been completed.
#defineWEBS_CONFIG   2
 Configuration settings trace level.
#defineWEBS_CONTENT   1
 Ready to receive request body data.
#defineWEBS_COOKIE_HTTP   0x2
 Flag for websSetCookie for http cookies (http only).
#defineWEBS_COOKIE_SAME_LAX   0x4
 Flag for websSetCookie for SameSite=Lax.
#defineWEBS_COOKIE_SAME_STRICT   0x8
 Flag for websSetCookie for SameSite=Strict.
#defineWEBS_COOKIE_SECURE   0x1
 Flag for websSetCookie for secure cookies (https only).
#defineWEBS_DECODE_TOKEQ   1
 Decode base 64 blocks up to a NULL or equals.
#defineWEBS_ERROR   1
 Standard logging trace levels are 0 to 9 with 0 being the most verbose.
#defineWEBS_ERROR_MSG   0x20
 Originated from error.
#defineWEBS_HASH_INIT   67
 Initial hash table size for form variables (prime number).
#defineWEBS_LEVEL_MASK   0xF
 Level mask.
#defineWEBS_LOG_MSG   0x100
 Originated from logmsg.
#defineWEBS_MAX_LISTEN   8
 Compile-time configuration constants that control various limits and behaviors in GoAhead.
#defineWEBS_MAX_PASSWORD   ME_GOAHEAD_LIMIT_PASSWORD
 Maximum plaintext password length accepted from clients.
#defineWEBS_MAX_PASSWORD_BUFFER   ((WEBS_MAX_PASSWORD * 3) + 3)
 Buffer size for "username:realm:password" passed to crypt primitives.
#defineWEBS_MAX_PORT_LEN   16
 Maximum number of digits in a port number string.
#defineWEBS_NOLOG   0x40000
 Don't write error to log.
#defineWEBS_RAW_MSG   0x200
 Raw message output.
#defineWEBS_READY   2
 Ready to route and start appropriate handler.
#defineWEBS_RUNNING   3
 Actively processing the request.
#defineWEBS_SESSION_HASH   31
 Hash table size for session storage (prime number).
#defineWEBS_SESSION_PRUNE   (60 * 1000)
 Session pruning interval in milliseconds (1 minute).
#defineWEBS_SMALL_HASH   31
 Default size for small hash tables (should be prime number for good distribution).
#defineWEBS_TRACE_MSG   0x400
 Originated from trace.
#defineWEBS_TRIM_BOTH   0x3
 Flag for strim to trim from both the start and the end of the string.
#defineWEBS_TRIM_END   0x2
 Flag for strim to trim from the end of the string.
#defineWEBS_TRIM_START   0x1
 Flag for strim to trim from the start of the string.
#defineWEBS_VERBOSE   9
 Highest level of trace.
#defineWEBS_WARN   2
 Soft warning trace level.

Typedefs

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

Socket accept callback.

Parameters:
sidSocket ID handle for the newly accepted socket.
ipaddrIP address of the connecting client.
portPort of the connecting client.
listenSidSocket ID for the listening socket.
API Stability:
Stable.
typedef void(* SocketHandler) (int sid, int mask, void *data)

Socket I/O callback.

Parameters:
sidSocket ID handle returned from socketConnect or when a new socket is passed to a SocketAccept callback.
maskMask of events of interest. Set to SOCKET_READABLE | SOCKET_WRITABLE | SOCKET_EXCEPTION.
dataData argument to pass to the callback function.
API Stability:
Stable.
typedef void(* WebsAction) (Webs *wp)

Action callback.

Parameters:
wpWebs request object.
API Stability:
Stable.
typedef void(* WebsAskLogin) (Webs *wp)

Callback to prompt the user for their password.

Parameters:
wpWebs request object.
API Stability:
Stable.
typedef void(* WebsEventProc) (void *data, int id)

Callback function for events.

Parameters:
dataOpaque data argument.
idEvent ID.
API Stability:
Stable.
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.
typedef bool(* WebsHandlerProc) (Webs *wp)

GoAhead handler service callback.

Parameters:
wpWebs request object.
Returns:
True if the handler serviced the request.
API Stability:
Stable.
typedef int WebsHash

Hash table ID returned by hashCreate.

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.
Returns:
Return zero if successful, otherwise -1.
API Stability:
Stable.
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 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.
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 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.
typedef void(* WebsWriteProc) (struct Webs *wp)

Callback for write I/O events.

WebsRole

Role definition structure.

API Stability:
Stable.
Fields:
WebsHashabilities Resolved role abilities.
WebsUser

GoAhead Authentication.

API Stability:
Stable.
Fields:
WebsHashabilities Resolved user abilities.
char *name User name.
char *password User password (encrypted).
char *roles User roles.
WebsFileInfo

File information structure.

API Stability:
Stable.
Fields:
intisDir Set if directory.
WebsTimemtime Modified time.
ulongsize File length.
WebsSession

Session state storage.

Fields:
WebsHashcache Cache of session variables.
WebsTimeexpires When the session expires.
char *id Session ID key.
intlifespan Session inactivity timeout (secs).
WebsUpload

File upload structure.

Fields:
char *clientFilename Client side name of the file.
char *contentType Content type.
char *filename Local (temp) name of the file.
ssizesize Uploaded file size.
WebsSocket

Socket control structure for network I/O management.

Description:
This structure represents a network socket connection and contains all the state needed to manage network I/O operations. GoAhead uses an event-driven, non-blocking I/O model where multiple connections can be efficiently handled by a single thread. Each socket has associated buffers, event handlers, and connection state.
Fields:
SocketAcceptaccept Accept handler.
intcurrentEvents Mask of ready events (FD_xx).
interror Last error.
intfileHandle ID of the file handler.
intflags Current state flags.
SocketHandlerhandler User I/O handler.
void *handler_data User handler data.
inthandlerMask Handler events of interest.
inthandshakes Number of renegotiations.
intinterestEvents Mask of events to watch for.
char *ip Server listen address or remote client address.
WebsBuflineBuf Line ring queue.
intport Port to listen on.
intsaveMask Reserved. Not currently used.
intsecure Socket is using SSL.
intselectEvents Events being selected.
intsid Index into socket[].
Socketsock Actual socket handle.
This structure should be considered opaque. Use the socket API functions rather than accessing fields directly.
API Stability:
Stable.
WebsBuf

Dynamic buffer (ring queue) for efficient I/O operations.

Description:
WebsBuf provides a highly efficient ring buffer implementation optimized for I/O operations and dynamic string handling. It allows maximum memory utilization by reusing buffer space and minimizing memory allocations. The buffer automatically grows as needed and supports both queue-like operations and string building.
Fields:
char *buf Holding buffer for data.
ssizebuflen Length of ring queue.
char *endbuf Pointer to end of buffer.
char *endp Pointer to end of data.
intincrement Growth increment.
ssizemaxsize Maximum size.
char *servp Pointer to start of data.
This structure exposes internal pointers for performance. Handle with care and prefer using the provided APIs over direct field access.
API Stability:
Stable.
WebsError

Error code list.

API Stability:
Stable.
Fields:
intcode HTTP error code.
char *msg HTTP error message.
WebsHandler

GoAhead handler object.

API Stability:
Stable.
Fields:
WebsHandlerCloseclose Handler close callback
intflags Handler control flags.
WebsHandlerProcmatch Handler match callback.
char *name Handler name.
WebsHandlerProcservice Handler service callback.
WebsRoute

Request route structure.

Fields:
WebsHashabilities Required user abilities.
WebsAskLoginaskLogin Route path prefix.
char *authType Authentication type.
char *dir Filesystem base directory for route documents.
WebsHashextensions Permissible URI extensions.
intflags Route control flags.
WebsHandler *handler Request handler to service requests.
WebsHashmethods Supported HTTP methods.
WebsParseAuthparseAuth Parse authentication details callback.
char *prefix Route path prefix.
ssizeprefixLen Prefix length.
char *protocol HTTP protocol to use for this route.
WebsHashredirects Response redirections.
WebsVerifyverify Verify password callback.
Webs

GoAhead HTTP request/response structure.

Description:
This is the primary structure representing an HTTP request and its associated response. Each active client connection has its own Webs structure containing all the request state, response buffers, and connection information. This structure is passed to all request handlers and contains everything needed to process HTTP requests and generate responses.
Fields:
char *authDetails Http header auth details.
char *authResponse Outgoing auth header.
char *authType Authorization type (Basic/DAA).
char *boundary Mime boundary (static).
ssizeboundaryLen Boundary length.
intcgifd File handle for CGI program input.
char *cgiStdin Filename for CGI program input.
WebsBufchunkbuf Pre-chunking data buffer.
char *clientFilename Current file filename.
intcode Response status code.
uintconnError Request has a connection error.
char *contentType Body content type.
char *cookie Request cookie string.
WebsUpload *currentFile Current file context.
char *decodedQuery Decoded request query.
char *digest Password digest.
intdocfd File descriptor for document being served.
intencoded True if the password is MD5(username:realm:password).
booleof If at the end of the request content.
uinterror Request has an error.
char *ext Path extension.
char *filename Document path name.
WebsHashfiles Uploaded files.
uintfinalized Request has been completed.
intflags Current flags see above.
char *host Requested host.
charifaddr[ME_MAX_IP] Local interface ipaddress.
WebsBufinput Receive buffer after de-chunking.
charipaddr[ME_MAX_IP] Connecting ipaddress.
ssizelastRead Number of bytes last read from the socket.
intlistenSid Listen Socket id.
char *method HTTP request method.
WebsBufoutput Transmit buffer after chunking.
char *password Authorization password.
char *path Path name without query. This is decoded.
intport Request port number.
char *protocol Protocol scheme (normally http|https).
char *protoVersion Protocol version (HTTP/1.1).
ssizeputLen Bytes read by a PUT request.
char *putname PUT temporary filename.
char *query Request query. This is decoded.
char *realm Realm field supplied in auth header.
char *referrer The referring page.
WebsHashresponseCookies Outgoing cookies.
struct WebsRoute *route Request route.
introuteCount Route count limiter.
WebsBufrxbuf Raw receive buffer.
ssizerxBytes Cumulative decoded request body bytes received (chunked framing).
ssizerxChunkSize Rx chunk size.
intrxChunkState Rx chunk encoding state.
char *rxEndp Pointer to end of raw data in input beyond endp.
ssizerxLen Rx content length.
ssizerxRemaining Remaining content to read from client.
struct WebsSession *session Session record.
intsid Socket id (handler).
WebsTimesince Parsed if-modified-since time.
void *ssl SSL context.
intstate Current state.
inttimeout Timeout handle.
WebsTimetimestamp Last transaction with browser.
ssizetxChunkLen Length of the chunk.
chartxChunkPrefix[16] Transmit chunk prefix.
ssizetxChunkPrefixLen Length of prefix.
char *txChunkPrefixNext Current I/O pos in txChunkPrefix.
inttxChunkState Transmit chunk state.
ssizetxLen Tx content length header value.
ssizetxRemaining Remaining content to write.
intupfd Upload file handle.
intuploadState Current file upload state.
char *uploadTmp Current temp filename for upload data.
char *uploadVar Current upload form variable name.
char *url Full request url. This is not decoded.
struct WebsUser *user User auth record.
char *userAgent User agent (browser).
char *username Authorization username.
WebsHashvars CGI standard variables.
intwid Index into webs.
WebsWriteProcwriteData Handler write I/O event callback. Used by fileHandler.
ssizewritten Bytes actually transferred.
This structure should be treated as opaque by user code. Use the provided APIs to access and manipulate request/response data rather than accessing fields directly.
API Stability:
Stable.
WebsValue

Value union to store primitive value types.

Fields:
WebsRomIndex

Compiled Rom Page Index.

API Stability:
Stable.
Fields:
uchar *page Web page data.
char *path Web page URL path.
Offsetpos Current read position.
intsize Size of web page in bytes.
WebsMime

Mime type list.

API Stability:
Stable.
Fields:
char *ext File extension.
char *type Mime type.
WebsKey

Hash table key-value entry structure.

Description:
Represents a single key-value pair stored in a GoAhead hash table. Hash tables in GoAhead provide fast O(1) average-case lookup, insertion, and deletion operations. Each entry contains both a key name and associated value, along with internal linking for collision resolution.
Fields:
Applications should not access this structure directly. Use the hash table API functions to manipulate hash entries safely.
API Stability:
Stable.

Functions

ssize appendWinArg (char *dp, cchar *arg)

Emit one CRT-correctly-quoted argv element into the destination buffer.

Description:
Implements the Microsoft-documented CommandLineToArgvW quoting rules. NULL or empty arg emits "" (two double-quote bytes) so the CRT recovers a zero-length argv element rather than nothing. Strings containing no space, tab, or double-quote pass through verbatim. Otherwise the string is wrapped in double-quotes, embedded quotes are escaped by doubling preceding backslash runs and prepending a backslash to the quote (the 2N+1 rule), and trailing backslash runs that abut the closing quote are doubled (the 2N rule). Destination buffer must hold at least 2 * slen(arg) + 3 bytes. Exposed for unit testing the quoting algorithm on non-Windows hosts.
Parameters:
dpDestination buffer; caller-allocated; must be large enough per the worst-case formula.
argThe argv element to quote. May be NULL or empty.
Returns:
Bytes written to dp. Does not null-terminate.
API Stability:
Internal.
void assert (bool cond)

Assure that an assert condition is true.

Parameters:
condBoolean result of a conditional test.
API Stability:
Stable.
void bufAddNull (WebsBuf *bp)

Add a trailing null to the buffer.

The end pointer is not changed
Parameters:
bpBuffer reference.
API Stability:
Stable.
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.
void bufAdjustStart (WebsBuf *bp, ssize count)

Adjust the start (servp) reference.

Parameters:
bpBuffer reference.
countNumber of bytes to adjust.
API Stability:
Stable.
void bufCompact (WebsBuf *bp)

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

Parameters:
bpBuffer reference.
API Stability:
Stable.
int bufCreate (WebsBuf *bp, int increment, int maxsize)

Create and initialize a buffer.

Description:
Initializes a WebsBuf structure for dynamic buffer operations. The buffer will automatically grow as needed up to the specified maximum size. Growth occurs in increments that double each time to minimize frequent reallocations.
WebsBuf provides efficient ring buffer functionality ideal for:
  • HTTP request/response buffering
  • Dynamic string building
  • I/O buffering and queuing
  • Memory-efficient data streaming bpPointer to an allocated WebsBuf structure to initialize incrementInitial increment size for buffer growth (bytes). Must be > 0. maxsizeMaximum size the buffer can grow to (bytes). Use -1 for unlimited growth. Zero if successful, -1 on error (invalid parameters or memory allocation failure) API Stability:Stable
void bufFlush (WebsBuf *bp)

Flush all data in the buffer and reset the pointers.

Parameters:
bpBuffer reference.
API Stability:
Stable.
void bufFree (WebsBuf *bp)

Free allocated storage for the buffer.

Parameters:
bpBuffer reference.
API Stability:
Stable.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
void bufReset (WebsBuf *bp)

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

Parameters:
bpBuffer reference.
API Stability:
Stable.
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.
char * bufStart (WebsBuf *bp)

Get a reference to the start of buffer data.

Parameters:
bpBuffer reference.
Returns:
A string pointer.
API Stability:
Stable.
ssize buildWinCmdLine (char **argp, char *out)

Build a Windows lpCommandLine string from a NULL-terminated argv array.

Description:
Walks argp, calls appendWinArg per element, separates elements with a single space, and null-terminates out. NULL argp or NULL out returns 0 with no write. Caller is responsible for pre-allocating out to the worst-case size, computed as the sum of 2 * slen(argp[i]) + 3 per element plus one separator per gap plus one null terminator. Exposed for unit testing the cmdLine builder on non-Windows hosts.
Parameters:
argpNULL-terminated argv array. NULL argp[i] is treated as an empty argv element.
outCaller-allocated buffer of sufficient worst-case size.
Returns:
Total bytes written excluding the null terminator.
API Stability:
Internal.
void error (cchar *fmt, ...)

Emit an error message.

Returns:
Zero if successful.
API Stability:
Stable.
char * fmt (char *buf, ssize maxSize, cchar *format, ...)

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 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.
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:
Stable.
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.
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.
bool isCgiExeOnWindows (cchar *cgiPath)

Test whether a CGI path is admissible as a Windows CGI target.

Description:
Returns true iff cgiPath is non-NULL and ends with .exe (case-insensitive). Used by the Windows extension gate to refuse .bat/.cmd and other non-.exe extensions that would otherwise be transparently routed through cmd.exe by kernel32's CreateProcess. Exposed for unit testing the gate logic on non-Windows hosts.
Parameters:
cgiPathServer-resolved path to the CGI program.
Returns:
True if the path is .exe-suffixed; false on NULL, too-short input, or other suffix.
API Stability:
Internal.
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.
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 most verbose. Level 2-4 are the most useful for debugging. Logging support is enabled by the ME_GOAHEAD_LOGGING define, which defaults to 1 in this header and may be overridden by the build.
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.
WebsLogHandler logSetHandler (WebsLogHandler handler)

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.
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.
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.
bool socketAddressIsV6 (cchar *ip)

Determine if an IP address is an IPv6 address.

Parameters:
ipString IP address.
Returns:
True if the address is an IPv6 address.
API Stability:
Stable.
int socketAlloc (cchar *host, int port, SocketAccept accept, int flags)

Allocate a socket object.

Parameters:
hostString host IP address.
portSocket port.
acceptOptional SocketAccept accept callback function.
flagsControl flags.
Returns:
Socket ID handle to use with other APIs.
API Stability:
Stable.
void socketClose (void )

Close the socket module.

API Stability:
Stable.
void socketCloseConnection (int sid)

Close a socket connection.

Parameters:
sidSocket ID handle returned from socketConnect or socketAccept.
API Stability:
Stable.
int socketConnect (cchar *host, int port, int flags)

Connect to a server and create a new socket.

Parameters:
hostHost IP address.
portPort number to connect to.
flagsSet to SOCKET_BLOCK for blocking I/O. Otherwise non-blocking I/O is used.
Returns:
True if the address is an IPv6 address.
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.
API Stability:
Stable.
void socketDeleteHandler (int sid)

Delete a socket handler created via socketCreateHandler.

Parameters:
sidSocket ID handle returned from socketConnect or socketAccept.
API Stability:
Stable.
bool socketEof (int sid)

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

Parameters:
sidSocket ID handle returned from socketConnect or socketAccept.
Returns:
True if the address is at EOF.
API Stability:
Stable.
void socketFree (int sid)

Free (and close) the socket.

Parameters:
sidSocket ID handle returned from socketConnect or socketAccept.
API Stability:
Stable.
int socketGetBlock (int sid)

Get the current blocking mode.

Parameters:
sidSocket ID handle returned from socketConnect or socketAccept.
Returns:
True if the socket is in blocking mode.
API Stability:
Stable.
int socketGetError (int sid)

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

Parameters:
sidSocket ID handle returned from socketConnect or socketAccept.
Returns:
Integer error code. See errno or GetLastError() on windows.
API Stability:
Stable.
Socket socketGetHandle (int sid)

Get the underlying socket operating system socket/file handle.

Parameters:
sidSocket ID handle returned from socketConnect or socketAccept.
Returns:
The socket handle.
API Stability:
Stable.
WebsSocket ** socketGetList (void )

Get the list of sockets.

Returns:
The socket list pointer.
API Stability:
Stable.
int socketGetPort (int sid)

Get the IP port associated with this socket.

Parameters:
sidSocket ID handle returned from socketConnect or socketAccept.
Returns:
The TCP/IP port for this socket.
API Stability:
Stable.
bool socketHasDualNetworkStack (void )

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

Returns:
True if IPv4 and IPv6 are supported on a single stack.
API Stability:
Stable.
bool socketHasIPv6 (void )

Indicate if the system has IPv6 support.

Returns:
True if IPv6 is supported on this system.
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 SOCKET_READABLE for buffered read data and SOCKET_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.
bool socketIsV6 (int sid)

Determine if a socket is bound to an IPv6 address.

Parameters:
sidSocket ID handle returned from socketConnect or socketAccept.
Returns:
True if the socket is using IPv6.
API Stability:
Stable.
int socketListen (cchar *host, int port, SocketAccept accept, int flags)

Open a listening socket.

Parameters:
hostHost IP address on which to listen. Set to NULL to listen on all interfaces.
portTCP/IP port on which to listen.
acceptSocketAccept callback function to invoke to receive incoming connections.
flagsReserved.
Returns:
Zero if successful, otherwise -1.
API Stability:
Stable.
int socketOpen (void )

Open the socket module.

Returns:
Zero if successful, otherwise -1.
API Stability:
Stable.
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 socketProcess (void )

Process pending socket I/O events.

API Stability:
Stable.
WebsSocket * socketPtr (int sid)

Return the socket object for the socket ID.

Parameters:
sidSocket ID handle returned from socketConnect or socketAccept.
Returns:
Corresponding socket object.
API Stability:
Stable.
ssize socketRead (int sid, void *buf, ssize len)

Read data from a socket.

Parameters:
sidSocket ID handle returned from socketConnect or socketAccept.
bufBuffer to hold read data.
lenSize of the buffer.
Returns:
Count of bytes actually read. Returns -1 for errors and EOF. Distinguish between errors and EOF via socketEof().
API Stability:
Stable.
void socketRegisterInterest (int sid, int mask)

Register interest in socket I/OEvents.

Parameters:
sidSocket ID handle returned from socketConnect or socketAccept.
maskMask of events of interest. Set to SOCKET_READABLE | SOCKET_WRITABLE | SOCKET_EXCEPTION.
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.
int socketSetBlock (int sid, int on)

Set the socket blocking mode.

Parameters:
sidSocket ID handle returned from socketConnect or socketAccept.
onSet to 1 to enable blocking.
Returns:
The previous blocking mode.
API Stability:
Stable.
void socketSetError (int error)

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

Parameters:
errorInteger error code. See errno or GetLastError() on windows.
API Stability:
Stable.
int socketSetNoDelay (int sid, bool on)

Set the socket delay mode.

Description:
This is used to enable or disable the TCP Nagle algorithm.
Parameters:
sidSocket ID handle returned from socketConnect or socketAccept.
onSet to 1 to disable the Nagle algorithm.
Returns:
The previous blocking mode.
API Stability:
Stable.
int socketWaitForEvent (WebsSocket *sp, int mask)

Wait for a socket I/O event.

Parameters:
spSocket object.
maskMask of events of interest. Set to SOCKET_READABLE | SOCKET_WRITABLE | SOCKET_EXCEPTION.
Returns:
Zero if successful in waiting for the desired event, otherwise return -1.
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.
void sslClose (void )

Close the ssl module.

API Stability:
Stable.
void sslFree (Webs *wp)

Free a ssl connection associated with a request.

Parameters:
wpWebs request object.
API Stability:
Stable.
int sslOpen (void )

Open the ssl module.

Returns:
Zero if successful, otherwise -1.
API Stability:
Stable.
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.
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.
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.
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:
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.
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.
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 ME_GOAHEAD_TRACING define, which defaults to 1 in this header and may be overridden by the build.
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.
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 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.
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.
void websActionOpen (void )

Open the action handler.

API Stability:
Stable.
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.
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.
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.
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.
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.
bool websAuthenticate (Webs *wp)

Authenticate a user for the current request.

Description:
Performs user authentication based on the requirements of the selected request route. The authentication process includes:
  • Checking if the route requires authentication
  • Validating credentials (Basic, Digest, or Form authentication)
  • Verifying user roles and permissions
  • Setting authentication state for the request
If authentication fails, appropriate HTTP status codes are set (401 Unauthorized). For routes that don't require authentication, this function returns true immediately
Parameters:
wpWebs request object representing the current HTTP request.
Returns:
True if authentication is not required or user is authenticated successfully, false otherwise.
API Stability:
Stable.
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.
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.
int websCgiHandler (Webs *wp)

CGI handler service callback.

Parameters:
wpWebs object.
Returns:
Returns 1 if the request was handled.
API Stability:
Stable.
int websCgiOpen (void )

Open the CGI handler.

Returns:
Zero if successful, otherwise -1.
API Stability:
Stable.
int websCgiPoll (void )

Poll for output from CGI processes and output.

Returns:
Time delay till next poll.
API Stability:
Stable.
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:
Stable.
void websClose (void )

Close the core GoAhead web server module.

Description:
Invoked when GoAhead is shutting down.
API Stability:
Stable.
void websCloseAuth (void )

Close the authentication module.

API Stability:
Stable.
void websCloseFile (int fd)

Close an open file.

Parameters:
fdOpen file handle returned by websOpenFile.
API Stability:
Stable.
void websCloseRoute (void )

Close the route module.

API Stability:
Stable.
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.
void websComputeAllUserAbilities (void )

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

API Stability:
Stable.
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.
WebsSession * websCreateSession (Webs *wp)

Test if a user possesses the required ability.

Parameters:
wpWebs request object.
Returns:
Allocated session object.
API Stability:
Stable.
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:
Stable.
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.
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.
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.
int websDefineAction (cchar *name, void *fun)

Define an action callback for use with the action handler.

Description:
The action handler provides a simple way to bind C functions to specific URIs under the "/action" prefix. This is an easy way to add dynamic functionality without creating a full custom handler. Actions are ideal for form processing, AJAX endpoints, and simple dynamic content.
Parameters:
nameURI path suffix. This suffix is added to "/action" to form the bound URI path. For example, if name is "login", the action will be accessible at "/action/login". The name should not include leading slashes.
funCallback function pointer. The function signature must be: void action(Webs *wp). The function receives the request object and should generate a response using websWrite() and complete the request with websDone().
Returns:
Zero if successful, otherwise -1 on error.
API Stability:
Stable.
int websDefineHandler (cchar *name, WebsHandlerProc match, WebsHandlerProc service, WebsHandlerClose close, int flags)

Define a custom request handler.

Description:
Registers a custom handler to process specific types of HTTP requests. Handlers are responsible for generating responses to HTTP requests. GoAhead comes with built-in handlers for static files, CGI, and actions, but you can create custom handlers for specialized processing. Handlers are matched against requests in the order they were registered.
Parameters:
nameUnique name for the handler (e.g., "myHandler", "apiHandler").
matchHandler callback match procedure. This function is called to determine if this handler should process the current request. Return true to accept the request, false to pass to next handler. Signature: bool match(Webs *wp).
serviceHandler callback service procedure. This function is called to generate the response for requests accepted by the match function. This is where you implement your custom logic. Signature: bool service(Webs *wp).
closeHandler callback close procedure. Called when GoAhead is shutting down to allow cleanup of handler-specific resources. Can be NULL if no cleanup needed. Signature: void close(void).
flagsHandler control flags. Set to WEBS_LEGACY_HANDLER to support the legacy handler API calling sequence, or 0 for standard handlers.
Returns:
Zero if successful, otherwise -1 on error.
API Stability:
Stable.
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.
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:
Stable.
void websDone (Webs *wp)

Complete a request.

Description:
A handler should call websDone() to complete the request.
Parameters:
wpWebs request object.
API Stability:
Stable.
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.
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.
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.
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.
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.
char * websEscapeUri (cchar *str)

Escape unsafe URI characters in a string using CC substitution.

Parameters:
strString to escape.
Returns:
An allocated block containing the escaped string. Caller must free.
API Stability:
Stable.
void websFileOpen (void )

Open and initialize the file handler.

API Stability:
Stable.
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.
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.
void websFreeUpload (Webs *wp)

Free file upload data structures.

Parameters:
wpWebs request object.
API Stability:
Stable.
void websFsClose (void )

Close the file system module.

API Stability:
Stable.
int websFsOpen (void )

Open the file system module.

Returns:
Zero if successful, otherwise -1.
API Stability:
Stable.
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.
char * websGetCgiCommName (void )

Get a unique temporary filename for CGI communications.

Returns:
Allocated filename string. Caller must free.
API Stability:
Stable.
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.
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.
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.
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.
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.
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.
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.
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.
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.
cchar * websGetIfaddr (Webs *wp)

Get the request interface address.

Parameters:
wpWebs request object.
Returns:
Network interface string. Caller should not free.
API Stability:
Stable.
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.
int websGetLogLevel (void )

Get the current trace log level.

Returns:
Number between 0 and 9.
API Stability:
Stable.
cchar * websGetMethod (Webs *wp)

Get the request method.

Parameters:
wpWebs request object.
Returns:
HTTP method string. Caller should not free.
API Stability:
Stable.
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.
WebsVerify websGetPasswordStoreVerify (void )

Set the password store verify callback.

Returns:
Verify WebsVerify callback function.
API Stability:
Stable.
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.
int websGetPort (Webs *wp)

Get the request TCP/IP port.

Parameters:
wpWebs request object.
Returns:
TCP/IP Port integer.
API Stability:
Stable.
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.
cchar * websGetQuery (Webs *wp)

Get the request query component.

Parameters:
wpWebs request object.
Returns:
Request query string. Caller should not free.
API Stability:
Stable.
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:
Stable.
WebsHash websGetRoles (void )

Get the roles hash.

Returns:
The roles hash object.
API Stability:
Stable.
cchar * websGetServer (void )

Get the server host name.

Returns:
Host name string. Caller should not free.
API Stability:
Stable.
cchar * websGetServerAddress (void )

Get the server IP address.

Returns:
Server IP address string. Caller should not free.
API Stability:
Stable.
cchar * websGetServerAddressUrl (void )

Get the server IP address with port number.

Returns:
Server IP:PORT address string. Caller should not free.
API Stability:
Stable.
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.
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.
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.
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.
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.
cchar * websGetUrl (Webs *wp)

Get the request URI.

Description:
This returns the request URI. This may be modified if the request is rewritten via websRewriteRequest.
Parameters:
wpWebs request object.
Returns:
URI string. Caller should not free.
API Stability:
Stable.
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.
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.
WebsHash websGetUsers (void )

Get the users hash.

Returns:
The users hash object.
API Stability:
Stable.
cchar * websGetVar (Webs *wp, cchar *name, cchar *defaultValue)

Get a request variable.

Description:
Retrieves form variables, query parameters, and HTTP headers from the current request. Request variables include:
  • Query string parameters (GET requests)
  • Form data variables (POST requests with application/x-www-form-urlencoded)
  • HTTP headers prefixed with "HTTP_" (e.g., "HTTP_USER_AGENT")
  • CGI environment variables (when using CGI handler)
  • Custom variables set by handlers
Variable names are case-sensitive. HTTP headers are converted to uppercase with hyphens replaced by underscores and prefixed with "HTTP_"
Parameters:
wpWebs request object representing the current HTTP request.
nameVariable name to retrieve. Common examples:
  • "name", "email" (form fields)
  • "q", "page" (query parameters)
  • "HTTP_USER_AGENT", "HTTP_REFERER" (HTTP headers)
  • "REQUEST_METHOD", "QUERY_STRING" (CGI variables)
defaultValueDefault value to return if the variable is not defined. Can be NULL if you want to detect missing variables.
Returns:
Variable value string, or defaultValue if not found. Caller should not free the returned string.
API Stability:
Stable.
int websJstOpen (void )

Open the Javascript module.

Returns:
Zero if successful, otherwise -1.
API Stability:
Stable.
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.
int websListen (cchar *endpoint)

Listen on a TCP/IP address endpoint.

Description:
Creates a listening socket on the specified network endpoint to accept incoming HTTP connections. The server will bind to the specified IP address and port and begin accepting connections from clients. Multiple endpoints can be created by calling this function multiple times with different addresses.
Parameters:
endpointNetwork endpoint specification in the format "IP:PORT". Supported formats:
  • "127.0.0.1:8080" - IPv4 address with port
  • ":8080" - All IPv4 interfaces on port 8080
  • "*:8080" - All interfaces on port 8080
  • "[::1]:8080" - IPv6 loopback with port
  • "[::]:8080" - All IPv6 interfaces on port 8080
  • "192.168.1.100:80" - Specific IPv4 interface
Returns:
Positive integer holding a Socket ID handle if successful, otherwise -1 on error. The socket ID can be used with other socket APIs for management.
API Stability:
Stable.
int websLoad (cchar *path)

Load routing tables from the specified filename.

Parameters:
pathRoute configuration filename.
Returns:
Zero if successful, otherwise -1.
API Stability:
Stable.
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.
bool websLogoutUser (Webs *wp)

Logout a user and remove the user login session.

Parameters:
wpWebs request object.
Returns:
True if successful.
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.
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.
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:
Stable.
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:
Stable.
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.
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.
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.
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.
int websOpen (cchar *documents, cchar *routes)

Open the web server.

Description:
This initializes the GoAhead web server subsystem and prepares it to handle HTTP requests. This function must be called before any other GoAhead APIs. It initializes internal data structures, sets up the document root directory, and optionally loads routing configuration.
Parameters:
documentsOptional web documents directory path. This becomes the document root where web files are served from. If set to NULL, the build-time default ME_GOAHEAD_DOCUMENTS value is used. The directory should contain your web content (HTML, CSS, JS, images, etc.).
routesOptional filename for a route configuration file to load. This file defines URL routing rules, authentication requirements, and handler mappings. If set to NULL, no routes are loaded. Additional route or authentication configuration files can be loaded later via websLoad().
Returns:
Zero if successful, otherwise -1 on error.
API Stability:
Stable.
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.
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.
int websOpenRoute (void )

Open the routing module.

API Stability:
Stable.
int websOptionsOpen (void )

Open the options handler.

Returns:
Zero if successful, otherwise -1.
API Stability:
Stable.
void websOsClose (void )

Close the O/S dependent code.

Description:
Called from websClose.
int websOsOpen (void )

Open the O/S dependent code.

Description:
Called from websOpen.
Returns:
Zero if successful, otherwise -1.
void websPageClose (Webs *wp)

Close the document page.

Parameters:
wpWebs request object.
API Stability:
Stable.
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.
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.
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.
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.
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.
int websParseArgs (char *args, char **argv, int maxArgc)

Parse a command line string into arguments.

Parameters:
argsCommand line string to parse.
argvArray to store parsed argument pointers.
maxArgcMaximum number of arguments that can be stored in argv.
Returns:
Number of arguments parsed.
API Stability:
Stable.
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:
Stable.
bool websProcessCgiData (Webs *wp)

Process CGI request body data.

Parameters:
wpWebs request object.
Returns:
True if processing the request can proceed.
API Stability:
Stable.
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.
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.
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.
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:
Stable.
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.
void websRedirect (Webs *wp, cchar *url)

Redirect the client to a new URL.

Description:
Sends an HTTP 302 (Temporary Redirect) response to the client with a Location header directing them to a new URL. This is commonly used for:
  • Post-login redirects
  • Temporary URL changes
  • Load balancing between servers
  • Routing after form submissions
The function automatically calls websDone() to complete the response, so no additional content should be written after calling this function
Parameters:
wpWebs request object representing the current HTTP request.
urlTarget URL to redirect the client to. Can be absolute (http://...) or relative (/path).
API Stability:
Stable.
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.
int websRemoveRole (cchar *role)

Remove a role from the system.

Parameters:
roleRole name.
Returns:
Zero if successful, otherwise -1.
API Stability:
Stable.
int websRemoveRoute (cchar *uri)

Remove a route from the routing tables.

Parameters:
uriMatching URI prefix.
Returns:
Zero if successful, otherwise -1.
API Stability:
Stable.
void websRemoveSessionVar (Webs *wp, cchar *name)

Remove a session variable.

Parameters:
wpWebs request object.
nameSession variable name.
API Stability:
Stable.
int websRemoveUser (cchar *name)

Remove a user from the system.

Parameters:
nameUser name.
Returns:
Zero if successful, otherwise -1.
API Stability:
Stable.
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.
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 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.
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.
int websRunEvents (void )

Run due events.

Returns:
Time delay till the next event.
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.
void websRuntimeClose (void )

Close the runtime code.

Description:
Called from websClose.
int websRuntimeOpen (void )

Open the runtime code.

Description:
Called from websOpen.
Returns:
Zero if successful.
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.
int websServer (cchar *endpoint, cchar *documents)

One line embedding API.

Description:
This is the simplest way to create a GoAhead web server. This call will automatically:
  • Initialize the web server
  • Load authentication configuration from auth.txt
  • Load routing configuration from route.txt
  • Start listening on the specified endpoint
  • Set the document root directory This function is ideal for simple embedded applications that need a quick web server setup.
Parameters:
endpointIP:PORT address on which to listen. Format examples:
  • "127.0.0.1:8080" (IPv4)
  • "[::1]:8080" (IPv6)
  • ":8080" (all interfaces)
  • "192.168.1.100:80" (specific interface)
documentsDirectory containing web documents to serve. This becomes the document root where index.html and other web files are located. Use NULL to use the default.
Returns:
Zero if successful, otherwise -1 on error.
API Stability:
Stable.
void websServiceEvents (int *finished)

Service I/O events until finished.

Description:
This is the main event loop for GoAhead. It will wait for socket events and service incoming HTTP requests until the finished flag is set to true. This function blocks and should be called from your main thread after starting the web server. The function will return when finished is set to a non-zero value.
Parameters:
finishedPointer to an integer flag. When set to non-zero, the event loop will exit. Note: Setting finished will not automatically wake up the service routine if it's waiting for events. The routine will check this flag during the next I/O event or timeout.
API Stability:
Stable.
void websSetBackground (int on)

Set the background processing flag.

Description:
Controls whether GoAhead runs as a background daemon process. When the background flag is set to true, GoAhead will detach from the controlling terminal and run as a daemon. This is typically used in production deployments where the web server should run independently of the user session. The flag is automatically set when GoAhead is started with the background command line option.
When running in background mode:
  • Process detaches from terminal
  • Standard I/O is redirected
  • Process continues running after user logout
  • Suitable for production server deployments onSet to 1 to enable background mode, 0 to disable background mode websGetBackground
void websSetBackgroundWriter (Webs *wp, WebsWriteProc proc)

Define a background write I/O event callback.

Description:
Sets up a callback function to handle background writing of response data. This function is useful for streaming large amounts of data or implementing server-sent events. The callback will be invoked when the socket becomes writable and the output buffer has space available.
The callback function should write data to the response using websWrite() or websWriteBlock(). When the callback has finished writing all data, it should not write anything and the framework will automatically complete the request This mechanism allows for non-blocking, event-driven data transmission that doesn't hold up the main request processing thread
Parameters:
wpWebs request object representing the current HTTP request.
procCallback function of type WebsWriteProc that will be called to write response data. The callback receives the Webs request object as its parameter.
API Stability:
Stable.
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.
API Stability:
Stable.
void websSetDebug (int on)

Set the debug processing flag.

Description:
Controls whether GoAhead operates in debug mode with enhanced diagnostic output. When debug mode is enabled, GoAhead provides additional logging, error reporting, and diagnostic information that can be helpful during development and troubleshooting.
Debug mode typically enables:
  • More verbose error messages
  • Additional runtime checks
  • Enhanced logging output
  • Development-oriented diagnostics
This flag is automatically set when GoAhead is started with the debugger command line option. Debug mode should generally be disabled in production environments for optimal performance
Parameters:
onSet to 1 to enable debug mode, 0 to disable debug mode.
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.
void websSetEnv (Webs *wp)

Create CGI environment variables for the current request.

Description:
Sets up the standard CGI environment variables that are passed to CGI scripts and programs. This function creates environment variables based on the current HTTP request that follow the CGI 1.1 specification. The variables include information about the server, request method, headers, query parameters, and client details.
Standard CGI variables created include:
  • SERVER_NAME, SERVER_PORT, SERVER_PROTOCOL
  • REQUEST_METHOD, REQUEST_URI, QUERY_STRING
  • CONTENT_TYPE, CONTENT_LENGTH
  • HTTP_* variables for all request headers
  • REMOTE_ADDR, REMOTE_HOST
  • SCRIPT_NAME, PATH_INFO
This function is automatically called by the CGI handler before executing CGI scripts
Parameters:
wpWebs request object representing the current HTTP request.
API Stability:
Stable.
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.
void websSetHost (cchar *host)

Define the host name for the server.

Description:
Sets the server's hostname which is used in various HTTP operations and responses. The hostname is used for:
  • Generating absolute URLs in redirects
  • Setting the Host header in outgoing requests
  • Virtual host processing and routing
  • Server identification in responses
  • SSL certificate validation
If not explicitly set, GoAhead will attempt to determine the hostname automatically from the system configuration. The hostname should be a fully qualified domain name (FQDN) or IP address that clients can use to reach the server
Parameters:
hostString containing the server hostname or IP address (e.g., "www.example.com" or "192.168.1.100").
API Stability:
Stable.
void websSetIndex (cchar *filename)

Set the default index document filename.

Description:
Sets the default document that will be served when a client requests a directory (URL ending with "/"). This is commonly used to serve a default page like "index.html" when users access the root directory or any subdirectory without specifying a filename.
For example, if the index is set to "index.html", then a request for "/" will actually serve "/index.html", and a request for "/docs/" will serve "/docs/index.html" The default index document is typically "index.html" but can be changed to any filename such as "default.htm", "home.html", or "main.html"
Parameters:
filenameThe filename to use as the default index document. This should be just the filename without any directory path components (e.g., "index.html", not "/path/index.html").
API Stability:
Stable.
void websSetIpAddr (cchar *ipaddr)

Define the host IP address.

Description:
Sets the server's IP address which is used for network operations and binding. This IP address represents the network interface that the server is bound to and can accept connections on. The IP address is used for:
  • Socket binding and listening
  • Response header generation
  • Access control and filtering
  • Logging and diagnostics
  • Multi-homed server configurations
The IP address should match one of the network interfaces on the server. Common values include specific interface addresses or "0.0.0.0" to bind to all available interfaces
Parameters:
ipaddrString containing the IP address in dotted decimal notation (IPv4) or colon-separated notation (IPv6). Examples: "192.168.1.100", "0.0.0.0", "::1", "::".
API Stability:
Stable.
void websSetLogLevel (int level)

Set the current trace log level.

Parameters:
levelInteger verbosity level (0-9).
API Stability:
Stable.
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:
Stable.
void websSetPasswordStoreVerify (WebsVerify verify)

Set the password store verify callback.

Parameters:
verifyWebsVerify callback function.
API Stability:
Stable.
void websSetPostLimit (ssize limit)

Override the runtime POST body size cap.

Description:
Replaces the compile-time ME_GOAHEAD_LIMIT_POST default with a runtime-chosen value. Pass 0 (or a negative value) to restore the compile-time default. Intended for test harnesses that need to accept larger bodies than the production limit allows.
Parameters:
limitMaximum permitted POST body size in bytes.
API Stability:
Prototype.
void websSetQueryVars (Webs *wp)

Create request variables for query string data.

Description:
Parses the query string from the current request URL and creates request variables that can be accessed using websGetVar(). The query string is the portion of the URL after the "?" character containing key=value pairs separated by "&" characters.
For example, for the URL "/search?name=john&age=25&active=true", this function will create request variables that can be retrieved as:
  • websGetVar(wp, "name", NULL) returns "john"
  • websGetVar(wp, "age", NULL) returns "25"
  • websGetVar(wp, "active", NULL) returns "true"
Query variables are automatically URL-decoded, so "%20" becomes a space character, etc. This function is typically called automatically during request processing
Parameters:
wpWebs request object representing the current HTTP request.
API Stability:
Stable.
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.
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:
Stable.
int websSetSessionVar (Webs *wp, cchar *name, cchar *value)

Set a session variable name value.

Description:
Stores a name-value pair in the current user session. Session variables persist across multiple HTTP requests from the same client until the session expires or is destroyed. This is useful for maintaining user state, preferences, shopping cart contents, etc. Sessions are identified by cookies sent to the client browser.
Parameters:
wpWebs request object representing the current HTTP request.
nameSession variable name. Should be a valid identifier string.
valueValue to store. The value is copied, so the original can be freed after this call. Use NULL to remove the variable from the session.
Returns:
Zero if successful, otherwise -1 on error (e.g., if sessions are not initialized).
API Stability:
Stable.
void websSetSslCertFile (cchar *path)

Override the server SSL certificate path at runtime.

Description:
Must be called before sslOpen. When set, this path takes precedence over the compile-time ME_GOAHEAD_SSL_CERTIFICATE default.
Parameters:
pathFilesystem path to a PEM-encoded certificate, or NULL to clear an override.
API Stability:
Prototype.
void websSetSslKeyFile (cchar *path)

Override the server SSL private key path at runtime.

Description:
Must be called before sslOpen. When set, this path takes precedence over the compile-time ME_GOAHEAD_SSL_KEY default.
Parameters:
pathFilesystem path to a PEM-encoded private key, or NULL to clear an override.
API Stability:
Prototype.
void websSetStatus (Webs *wp, int status)

Set the response HTTP status code.

Description:
Sets the HTTP status code that will be sent in the response to the client. The status code indicates the result of the HTTP request processing. This function should be called before sending the response headers or body content.
Common status codes include:
  • 200: OK (success)
  • 301/302: Redirect
  • 400: Bad Request
  • 401: Unauthorized
  • 403: Forbidden
  • 404: Not Found
  • 500: Internal Server Error
If not explicitly set, GoAhead will automatically set an appropriate status code based on the request processing results (typically 200 for successful requests)
Parameters:
wpWebs request object representing the current HTTP request.
statusHTTP status code (e.g., 200, 404, 500). Should be a valid HTTP status code.
API Stability:
Stable.
void websSetTxLength (Webs *wp, ssize length)

Set the response body content length.

Description:
Sets the Content-Length header for the HTTP response, indicating the size of the response body in bytes. This header tells the client how much data to expect in the response body, which enables proper handling of the response and connection management.
Setting the content length is important for:
  • Enabling HTTP/1.1 persistent connections (keep-alive)
  • Allowing clients to display download progress
  • Proper handling of binary content
  • Compliance with HTTP specifications
If the content length is not set, GoAhead may use chunked transfer encoding or close the connection after sending the response body
Parameters:
wpWebs request object representing the current HTTP request.
lengthSize of the response body in bytes. Use 0 for empty responses, or -1 to indicate that the content length is unknown (will use chunked encoding or connection close).
API Stability:
Stable.
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.
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.
WebsKey * websSetVar (Webs *wp, cchar *name, cchar *value)

Set a request variable to a string value.

Description:
Sets a request variable that can be retrieved later with websGetVar(). Request variables provide a key-value store for the current request context. Common uses include:
  • Setting HTTP headers (prefixed with "HTTP_")
  • Storing form processing results
  • Passing data between handlers
  • CGI environment variables
Variable names should follow these conventions:
  • HTTP headers: "HTTP_" prefix (e.g., "HTTP_USER_AGENT")
  • Form data: field names (e.g., "username", "email")
  • Custom data: descriptive names (e.g., "authLevel", "userRole") wpWebs request object representing the current HTTP request nameVariable name to set. Names are case-sensitive. valueString value to store. The value is copied so the original can be freed. Pointer to the allocated WebsKey structure, or NULL on error API Stability:Stable
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:
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.
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.
void websStopEvent (int id)

Stop an event.

Parameters:
idEvent id allocated by websStartEvent.
API Stability:
Stable.
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.
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.
void websTimeClose (void )

Close the date/time parsing module.

API Stability:
Stable.
int websTimeOpen (void )

Open the date/time parsing module.

Returns:
Zero if successful, otherwise -1.
API Stability:
Stable.
void websUploadOpen (void )

Open the file upload filter.

API Stability:
Stable.
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:
Stable.
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.
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.
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:
Stable.
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.
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.
ssize websWrite (Webs *wp, cchar *fmt, ...)

Write formatted data to the response.

Description:
Writes formatted data to the HTTP response buffer. The data is buffered internally and will be sent to the client when the buffer becomes full, when websFlush() is called, or when the request completes. This is the primary function for sending dynamic content to clients. Supports all standard printf formatting options.
Parameters:
wpWebs request object representing the current HTTP request/response.
fmtPrintf-style format string supporting standard format specifiers: s (string), d (integer), f (float), x (hex), etc.
...Variable arguments corresponding to the format specifiers in fmt.
Returns:
Count of bytes written to the response buffer, or -1 on error.
API Stability:
Stable.
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.
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.
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.
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.
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.
void wfree (void *blk)

Free an allocated block of memory.

Parameters:
blkReference to the memory block to free.
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.
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 wcloseAlloc 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.

© Embedthis Software. All rights reserved.