Barracuda Application Server C/C++ Reference
Native APIs, integration guides, and platform interfaces
Standard Web-Server classes

Detailed Description

A collection of common classes typically used working with server side scripting.

See also
C Server Pages and HttpResRdr
Barracuda Introduction

Classes

struct  HttpParameterIterator
 The HttpParameterIterator is used for iterating through the form elements parsed by the HttpServer object. More...
 
struct  HttpCookie
 A cookie is used for exchanging a small amount of information between a HttpPage and a web browser. More...
 
struct  HttpStdHeaders
 Standard HTTP header values. More...
 
struct  HttpRequest
 The HttpServer creates an HttpRequest object when the HttpServer parses a client request. More...
 
struct  HttpResponse
 This object is used when sending response messages back to the client. More...
 
struct  HttpCommand
 The HttpCommand class is a container class for the HttpRequest and HttpResponse command pair. More...
 
struct  HttpSessionAttribute
 The interface to an HttpSession attribute. More...
 
struct  HttpSession
 Provides a way to identify a user across more than one page request or visit to a web site, and to store information about that user. More...
 
struct  HttpSessionContainer
 The HttpSession container class. More...
 
struct  HttpPage
 An HttpPage, which is typically created by the CSP compiler, is similar to a Java servlet. More...
 
struct  HttpDir
 An instance of the HttpDir class, which is a collection of zero or more resources, serves as one directory entry in the virtual file system. More...
 
struct  HttpServerConfig
 Use an instance of this class if you want to override the default web-server parameters. More...
 
struct  HttpServer
 The Web Server. More...
 

Typedefs

typedef struct HttpParameterIterator HttpParameterIterator
 The HttpParameterIterator is used for iterating through the form elements parsed by the HttpServer object. More...
 
typedef struct HttpCookie HttpCookie
 A cookie is used for exchanging a small amount of information between a HttpPage and a web browser. More...
 
typedef struct HttpStdHeaders HttpStdHeaders
 Standard HTTP header values. More...
 
typedef struct HttpRequest HttpRequest
 The HttpServer creates an HttpRequest object when the HttpServer parses a client request. More...
 
typedef struct HttpResponse HttpResponse
 This object is used when sending response messages back to the client. More...
 
typedef struct HttpCommand HttpCommand
 The HttpCommand class is a container class for the HttpRequest and HttpResponse command pair. More...
 
typedef void(* HttpSessionAttribute_Destructor) (struct HttpSessionAttribute *o)
 HttpSessionAttribute termination callback function. More...
 
typedef struct HttpSessionAttribute HttpSessionAttribute
 The interface to an HttpSession attribute. More...
 
typedef struct HttpSession HttpSession
 Provides a way to identify a user across more than one page request or visit to a web site, and to store information about that user. More...
 
typedef struct HttpSessionContainer HttpSessionContainer
 The HttpSession container class. More...
 
typedef void(* HttpPage_Service) (struct HttpPage *page, HttpRequest *request, HttpResponse *response)
 The HttpPage service function. More...
 
typedef struct HttpPage HttpPage
 An HttpPage, which is typically created by the CSP compiler, is similar to a Java servlet. More...
 
typedef int(* HttpDir_Service) (struct HttpDir *o, const char *relPath, HttpCommand *cmd)
 The HttpDir service callback function. More...
 
typedef struct HttpDir HttpDir
 An instance of the HttpDir class, which is a collection of zero or more resources, serves as one directory entry in the virtual file system. More...
 
typedef struct HttpServerConfig HttpServerConfig
 Use an instance of this class if you want to override the default web-server parameters. More...
 
typedef struct HttpServer HttpServer
 The Web Server. More...
 

Enumerations

enum  HttpMethod
 HTTP method types. More...
 

Functions

BA_API int HttpParameterIterator_constructor (HttpParameterIterator *o, struct HttpRequest *req)
 Initialize an iterator and select its first element. More...
 
BA_API int HttpParameterIterator_constructor2 (HttpParameterIterator *o, HttpParameter *param)
 Initialize an iterator and select its first element. More...
 
BA_API const char * HttpCookie_getComment (HttpCookie *o)
 Returns the comment set for this cookie or null if the cookie comment is not set. More...
 
BA_API const char * HttpCookie_getDomain (HttpCookie *o)
 Returns the domain name set for this cookie. More...
 
BA_API BaTime HttpCookie_getMaxAge (HttpCookie *o)
 Returns the maximum age of the cookie, specified in seconds; by default, 0 indicating the cookie will persist until browser shutdown. More...
 
BA_API const char * HttpCookie_getName (HttpCookie *o)
 Returns the name of the cookie. More...
 
BA_API const char * HttpCookie_getPath (HttpCookie *o)
 Returns the path on the server to which the browser returns this cookie. More...
 
BA_API BaBool HttpCookie_getSecure (HttpCookie *o)
 Returns true if the browser is sending cookies only over a secure protocol, or false if the browser can send cookies using any protocol. More...
 
BA_API BaBool HttpCookie_getHttpOnly (HttpCookie *o)
 Return the HttpOnly attribute. More...
 
BA_API const char * HttpCookie_getValue (HttpCookie *o)
 Returns the value of the cookie. More...
 
BA_API int HttpCookie_setComment (HttpCookie *o, const char *purpose)
 Specifies a comment that describes a cookie's purpose. More...
 
BA_API int HttpCookie_setDomain (HttpCookie *o, const char *pattern)
 Specifies the domain within which this cookie should be presented. More...
 
BA_API void HttpCookie_setMaxAge (HttpCookie *o, BaTime expiry)
 Sets the maximum age of the cookie in seconds. More...
 
BA_API int HttpCookie_setPath (HttpCookie *o, const char *uri)
 Set the cookie path. More...
 
BA_API void HttpCookie_setSecure (HttpCookie *o, BaBool flag)
 Inform the browser whether the cookie should be sent only using a secure protocol such as HTTPS – i.e. More...
 
BA_API void HttpCookie_setHttpOnly (HttpCookie *o, BaBool flag)
 Marks or unmarks this Cookie as HttpOnly. More...
 
BA_API int HttpCookie_setValue (HttpCookie *o, const char *newValue)
 Assigns a new value to a cookie after the cookie is created. More...
 
BA_API void HttpCookie_activate (HttpCookie *o)
 Activates the cookie. More...
 
BA_API int HttpRequest_checkMethods (HttpRequest *o, struct HttpResponse *resp, U32 methods, BaBool addDefault)
 Checks the HTTP method type and sends a response message if condition met. More...
 
BA_API BaBool HttpRequest_checkTime (HttpRequest *o, struct HttpResponse *resp, BaTime time)
 Parses and checks if the "If-Modified-Since" time is equal or greater than "time". More...
 
BA_API const char * HttpRequest_getRequestURI (HttpRequest *o)
 Returns the pathname. More...
 
BA_API const char * HttpRequest_getRequestURL (HttpRequest *o, BaBool forceHttps)
 Reconstructs the URL the client used to make the request. More...
 
BA_API const char * HttpRequest_getVersion (HttpRequest *o)
 Returns the HTTP version as a string, normally "1.1". More...
 
BA_API const char * HttpRequest_getHeaderValue (HttpRequest *o, const char *name)
 Returns the value of the specified request header. More...
 
BA_API HttpCookieHttpRequest_getCookie (HttpRequest *o, const char *name)
 Returns the requested cookie or NULL if no cookie matches the name. More...
 
BA_API const char * HttpRequest_getParameter (HttpRequest *o, const char *paramName)
 Returns the value of a request parameter as a const char* or null if the parameter does not exist. More...
 
BA_API HttpHeader * HttpRequest_getHeaders (HttpRequest *o, int *len)
 Return an HTTP header iterator that can iterate and fetch all the HTTP headers. More...
 
BA_API int HttpRequest_wsUpgrade (HttpRequest *o)
 Validate and send an HTTP/1.1 WebSocket version-13 handshake. More...
 
BA_API struct HttpSessionHttpRequest_getSession (HttpRequest *o, BaBool create)
 Returns the current HttpSession associated with this request, or if there is no current session and create is true, returns a new session. More...
 
BA_API HttpCookieHttpResponse_createCookie (struct HttpResponse *o, const char *name)
 Create a cookie. More...
 
BA_API const char * HttpResponse_containsHeader (HttpResponse *o, const char *name)
 Searches the internal response header database for a header with the specified name. More...
 
BA_API const char * HttpResponse_encodeRedirectURL (HttpResponse *o, const char *pathName)
 Encodes the specified URL into an absolute URL, or if encoding is not needed, returns the URL unchanged. More...
 
BA_API const char * HttpResponse_encodeUrl (HttpResponse *o, const char *path)
 Encodes an absolute or relative URL, or if encoding is not needed, returns the URL unchanged. More...
 
BA_API int HttpResponse_flush (HttpResponse *o)
 Forces any content in the buffer to be written to the client. More...
 
BA_API int HttpResponse_redirect (HttpResponse *o, const char *path)
 Internally redirects the request to another resource. More...
 
BA_API int HttpResponse_setResponseBuf (HttpResponse *o, BufPrint *buf, BaBool useDefBuffer)
 This is an advanced function that makes it possible to redirect the output, which is normally sent to the client, to another buffer. More...
 
BA_API int HttpResponse_removeResponseBuf (HttpResponse *o)
 Remove buffer set by using setResponseBuf. More...
 
BA_API int HttpResponse_resetHeaders (HttpResponse *o)
 Removes all HTTP headers. More...
 
BA_API int HttpResponse_resetBuffer (HttpResponse *o)
 Clears the content of the underlying buffer in the response without clearing headers or status code. More...
 
BA_API int HttpResponse_sendBufAsError (HttpResponse *o, int eCode)
 Sends the data formatted into the HttpResponse buffer as an error message to the client. More...
 
BA_API int HttpResponse_sendBufAsTxtError (HttpResponse *o, int eCode)
 Sends the data formatted into the HttpResponse buffer as an error message to the client. More...
 
BA_API int HttpResponse_sendRedirect (HttpResponse *o, const char *url)
 Sends a temporary redirect (302) response to the client using the specified redirect location URL. More...
 
BA_API int HttpResponse_redirect2TLS (HttpResponse *o)
 Prepares an HTTPS redirect (301) for a non-secure connection. More...
 
BA_API int HttpResponse_setContentLength (HttpResponse *o, BaFileSize len)
 Sets the "Content-Length" parameter value. More...
 
BA_API int HttpResponse_setContentType (HttpResponse *o, const char *type)
 Sets the "Content-Type" parameter value. More...
 
BA_API int HttpResponse_setDateHeader (HttpResponse *o, const char *name, BaTime t)
 Set a copied date header; call before response commitment. More...
 
BA_API int HttpResponse_setHeader (HttpResponse *o, const char *name, const char *value, BaBool replace)
 Sets a HTTP response header with the given name and value. More...
 
BA_API int HttpResponse_setMaxAge (HttpResponse *response, BaTime seconds)
 Sets header "Cache-Control: max-age=seconds". More...
 
BA_API char * HttpResponse_fmtHeader (HttpResponse *o, const char *name, int valueLen, BaBool replace)
 Pre-allocate memory for a {name, value} pair in the response header database. More...
 
BA_API int HttpResponse_printf (HttpResponse *o, const char *fmt,...)
 printf is used for sending formatted data to the client. More...
 
BA_API int HttpResponse_write (HttpResponse *o, const void *data, int len, int useBuffering)
 Used for sending pre-formatted data to the client. More...
 
BA_API BufPrintHttpResponse_getWriter (HttpResponse *o)
 Returns a BufPrint object that can send any type of data to the client. More...
 
BA_API int HttpResponse_send (HttpResponse *o, const void *data, int len)
 Used when sending raw data to the client. More...
 
BA_API int HttpResponse_setDefaultHeaders (HttpResponse *o)
 Sets the most common header values in servlet and CSP files. More...
 
BA_API void HttpSessionAttribute_constructor (HttpSessionAttribute *o, const char *name, HttpSessionAttribute_Destructor d)
 Initialize a session attribute. More...
 
BA_API void HttpSessionAttribute_destructor (HttpSessionAttribute *o)
 Terminate an unattached attribute and release its copied name. More...
 
BA_API HttpSessionAttributeHttpSession_getAttribute (HttpSession *o, const char *name)
 Returns the object bound with the specified name in this session, or null if no object is bound under the name. More...
 
BA_API BaTime HttpSession_getCreationTime (HttpSession *o)
 Returns the time when this session was created, measured in seconds since midnight January 1, 1970 GMT. More...
 
BA_API BaTime HttpSession_getLastAccessedTime (HttpSession *o)
 Returns the last time the client sent a request associated with this session, as the number of seconds since midnight January 1, 1970 GMT, and marked by the time the container received the request. More...
 
BA_API BaTime HttpSession_getMaxInactiveInterval (HttpSession *o)
 Returns the maximum time interval, in seconds, that the session container will keep this session open between client accesses. More...
 
BA_API struct HttpServerHttpSession_getServer (HttpSession *o)
 Get the server object. More...
 
BA_API void HttpSession_terminate (HttpSession *o)
 Unbinds any objects bound to this session object, runs the HttpSession destructor, and frees the memory for this object. More...
 
BA_API int HttpSession_removeAttribute (HttpSession *o, const char *name)
 Removes the object bound with the specified name from this session. More...
 
BA_API int HttpSession_setAttribute (HttpSession *o, HttpSessionAttribute *value)
 Binds an object to this session, using the name specified. More...
 
BA_API void HttpSession_setMaxInactiveInterval (HttpSession *o, BaTime interval)
 Specifies the time, in seconds, between client requests before the session container will invalidate this session. More...
 
BA_API void HttpSession_decrRefCntr (HttpSession *o)
 Decrements the session reference counter. More...
 
BA_API int HttpSession_fmtSessionId (HttpSession *o, U8 *buf, size_t bufSize)
 Format the full session token as hexadecimal text. More...
 
void BA_API HttpPage_constructor (HttpPage *o, HttpPage_Service service, const char *name)
 The HttpPage constructor. More...
 
BA_API void HttpPage_destructor (HttpPage *o)
 The HttpPage destructor unlinks the page from the parent directory. More...
 
BA_API int HttpPage_unlink (HttpPage *o)
 Unlinks/removes the page from the parent directory. More...
 
BA_API void HttpDir_constructor (HttpDir *o, const char *name, S8 priority)
 Constructor for creating a sub-directory. More...
 
BA_API void HttpDir_destructor (HttpDir *o)
 Unlink this directory and notify all child pages/directories through their service callbacks with NULL request arguments. More...
 
BA_API char * HttpDir_makeAbsPath (HttpDir *o, const char *relPath, int relPathLen)
 Makes an absolute path based on where the HttpDir instance is installed in the virtual file system and the provided relative path. More...
 
BA_API int HttpDir_insertDir (HttpDir *o, HttpDir *dir)
 Insert a sub-directory. More...
 
BA_API HttpDirHttpDir_getDir (HttpDir *o, const char *name)
 Returns the first directory with the name given or NULL if not found. More...
 
BA_API HttpPageHttpDir_getPage (HttpDir *o, const char *name)
 Returns the page with the name given or NULL if not found. More...
 
BA_API int HttpDir_insertPage (HttpDir *o, HttpPage *page)
 Insert a page in the directory. More...
 
BA_API HttpPageHttpDir_findPage (HttpDir *o, HttpPage *iter, const char *name)
 Searches for a page in this directory node. More...
 
BA_API HttpDirHttpDir_findDir (HttpDir *iter, const char *name, unsigned int nameLen)
 Searches for a sub-directory in this directory node. More...
 
BA_API HttpDirHttpDir_createOrGet (HttpDir *o, const char *name)
 Returns a sub-directory with the given name. More...
 
BA_API void HttpDir_p403 (HttpDir *o, const char *p403)
 Set a 403 denied request handler. More...
 
BA_API HttpDir_Service HttpDir_setService (HttpDir *o, HttpDir_Service s)
 Replace the original service function in HttpDir with your own. More...
 
BA_API int HttpDir_unlink (HttpDir *o)
 Unlinks/removes the directory from the parent directory. More...
 
BA_API int HttpDir_authenticateAndAuthorize (HttpDir *o, HttpCommand *cmd, const char *path)
 Authenticate and authorize the user. More...
 
BA_API void HttpServerConfig_constructor (HttpServerConfig *o)
 The constructor sets up the default parameters. More...
 
BA_API int HttpServerConfig_setRequest (HttpServerConfig *o, S16 min, S16 max)
 Set the size of the HTTP request buffer. More...
 
BA_API int HttpServerConfig_setResponseHeader (HttpServerConfig *o, U16 min, U16 max)
 Set the size of the HTTP response header buffer. More...
 
BA_API int HttpServerConfig_setResponseData (HttpServerConfig *o, U16 size)
 The HttpResponse object stores formatted data in the response data buffer. More...
 
BA_API int HttpServerConfig_setCommit (HttpServerConfig *o, U16 size)
 Set the size of the HTTP response commit buffer. More...
 
BA_API int HttpServerConfig_setNoOfHttpCommands (HttpServerConfig *o, U16 size)
 The number of HttpCommand instances created by the web-server. More...
 
BA_API int HttpServerConfig_setNoOfHttpConnections (HttpServerConfig *o, U16 size)
 Number of HttpConnection instances. More...
 
BA_API int HttpServerConfig_setMaxSessions (HttpServerConfig *o, U16 size)
 Maximum allowed active HttpSession objects. More...
 
BA_API void HttpServer_constructor (HttpServer *, SoDisp *, HttpServerConfig *)
 Initialize a server in caller-provided storage (first argument), using a required borrowed dispatcher (second argument) and optional configuration (third argument). More...
 
BA_API void HttpServer_destructor (HttpServer *o)
 Stop using the server before destruction. More...
 
BA_API int HttpServer_insertRootDir (HttpServer *o, HttpDir *dir)
 Insert a root directory node. More...
 
BA_API int HttpServer_insertDir (HttpServer *o, const char *virtualDirRootPath, HttpDir *dir)
 Insert a directory node into the virtual file system. More...
 
BA_API int HttpServer_insertCSP (HttpServer *o, CspInit cspInit, const char *virtualDirRootPath, struct CspReader *reader)
 Insert and initialize a CSP Virtual Directory. More...
 
BA_API const char * HttpServer_getStatusCode (int code)
 Return a short description for common HTTP error codes. More...
 
BA_API HttpSessionHttpServer_getSession (HttpServer *o, U32 id)
 Returns the HttpSession associated with id or NULL if not found. More...
 
BA_API void HttpServer_set404Page (HttpServer *o, const char *page404)
 Set a more user friendly 404 page. More...
 
 HttpParameterIterator::HttpParameterIterator (HttpRequest *req)
 This HttpParameterIterator constructor takes a HttpRequest object as argument. More...
 
 HttpParameterIterator::HttpParameterIterator (HttpParameter *param)
 This HttpParameterIterator constructor takes a HttpParameter object as argument. More...
 
void HttpParameterIterator::nextElement ()
 Advance to the next element. More...
 
int HttpCookie::setComment (const char *purpose)
 Specifies a comment that describes a cookie's purpose. More...
 
int HttpCookie::setDomain (const char *pattern)
 Specifies the domain within which this cookie should be presented. More...
 
void HttpCookie::setMaxAge (BaTime expiry)
 Sets the maximum age of the cookie in seconds. More...
 
void HttpCookie::deleteCookie ()
 Specifies a path for the cookie to which the client should return the cookie. More...
 
int HttpCookie::setPath (const char *uri)
 Set the cookie path. More...
 
void HttpCookie::setSecure (bool flag)
 Inform the browser whether the cookie should be sent only using a secure protocol such as HTTPS – i.e. More...
 
void HttpCookie::setHttpOnly (bool flag)
 Marks or unmarks this Cookie as HttpOnly. More...
 
int HttpCookie::setValue (const char *newValue)
 Assigns a new value to a cookie after the cookie is created. More...
 
void HttpCookie::activate ()
 Activates the cookie. More...
 
const char * HttpStdHeaders::getConnection ()
 Returns the connection type for HTTP 1.1 connections, returns "Close" or "Keep-Alive. More...
 
const char * HttpStdHeaders::getHost ()
 Returns the host header. More...
 
const char * HttpStdHeaders::getDomain ()
 Returns the host header without any port number. More...
 
const char * HttpStdHeaders::getContentType ()
 Returns the content type, for example: "application/x-www-form-urlencoded". More...
 
SBaFileSize HttpStdHeaders::getContentLength ()
 Returns the content length if request contains a body. More...
 
int HttpRequest::checkMethods (HttpResponse *resp, U32 methods, bool addDefault=TRUE)
 Checks the HTTP method type and sends a response message if condition met. More...
 
BaBool HttpRequest::checkTime (struct HttpResponse *resp, BaTime time)
 Parses and checks if the "If-Modified-Since" time is equal or greater than "time". More...
 
AuthenticatedUserHttpRequest::getAuthenticatedUser ()
 Returns the authenticated user or NULL if user is not authenticated. More...
 
HttpMethod HttpRequest::getMethodType ()
 Returns the method type. More...
 
const char * HttpRequest::getMethod ()
 Returns a string representation of the value returned by HttpRequest::getMethodType. More...
 
static const char * HttpRequest::getMethod (HttpMethod method)
 Returns a string representation of the argument. More...
 
HttpServerHttpRequest::getServer ()
 Returns the web server object. More...
 
const char * HttpRequest::getRequestURI ()
 Returns the pathname. More...
 
const char * HttpRequest::getRequestURL (bool forceHttps=false)
 Reconstructs the URL the client used to make the request. More...
 
HttpStdHeadersHttpRequest::getStdHeaders ()
 Returns an object containing standard HTTP headers. More...
 
const char * HttpRequest::getVersion ()
 Returns the HTTP version as a string, normally "1.1". More...
 
const char * HttpRequest::getHeaderValue (const char *name)
 Returns the value of the specified request header. More...
 
HttpCookieHttpRequest::getCookie (const char *name)
 Returns the requested cookie or NULL if no cookie matches the name. More...
 
const char * HttpRequest::getParameter (const char *paramName)
 Returns the value of a request parameter as a const char* or null if the parameter does not exist. More...
 
int HttpRequest::wsUpgrade ()
 Validate and send an HTTP/1.1 WebSocket version-13 handshake. More...
 
HttpHeader * HttpRequest::getHeaders (int *len)
 Return an HTTP header iterator that can iterate and fetch all the HTTP headers. More...
 
HttpSessionHttpRequest::getSession (BaBool create=true)
 Returns the current HttpSession associated with this request, or if there is no current session and create is true, returns a new session. More...
 
bool HttpParameterIterator::hasMoreElements ()
 Returns true if more elements. More...
 
HttpInDataHttpRequest::getBuffer ()
 Get the internal rec buffer. More...
 
HttpCookieHttpResponse::createCookie (const char *name)
 Create a cookie. More...
 
const char * HttpResponse::containsHeader (const char *name)
 Searches the internal response header database for a header with the specified name. More...
 
U32 HttpResponse::byteCount ()
 Returns number of bytes sent thus far. More...
 
const char * HttpResponse::encodeRedirectURL (const char *pathName)
 Encodes the specified URL into an absolute URL, or if encoding is not needed, returns the URL unchanged. More...
 
const char * HttpResponse::encodeRedirectURLWithParam (const char *pathName)
 This method is similar to HttpResponse::encodeRedirectURL, but this method also includes all URL-encoded parameters in the request line and in the body if the client sent a POST message. More...
 
const char * HttpResponse::encodeUrl (const char *path)
 Encodes an absolute or relative URL, or if encoding is not needed, returns the URL unchanged. More...
 
int HttpResponse::flush ()
 Forces any content in the buffer to be written to the client. More...
 
int HttpResponse::forward (const char *path)
 Forwards a request from a servlet to another resource (servlet, CSP file, or HTML file). More...
 
int HttpResponse::redirect (const char *path)
 Internally redirects the request to another resource. More...
 
int HttpResponse::include (const char *path)
 Includes the content of a resource (servlet, CSP page, HTML file) in the response. More...
 
bool HttpResponse::committed () const
 Returns a boolean indicating if the response has been committed. More...
 
bool HttpResponse::isForward () const
 Returns true if this is a forward request from another servlet or CSP file. More...
 
bool HttpResponse::isInclude () const
 Returns true if this is an include from another servlet or CSP file. More...
 
bool HttpResponse::initial () const
 Returns true if this is the initial page. More...
 
int HttpResponse::setResponseBuf (BufPrint *buf, bool useDefBuffer=true)
 This is an advanced function that makes it possible to redirect the output, which is normally sent to the client, to another buffer. More...
 
int HttpResponse::removeResponseBuf ()
 Remove buffer set by using setResponseBuf. More...
 
int HttpResponse::resetHeaders ()
 Removes all HTTP headers. More...
 
int HttpResponse::resetBuffer ()
 Clears the content of the underlying buffer in the response without clearing headers or status code. More...
 
int HttpResponse::sendError (int eCode)
 Sends an error response as a simple HTML page to the client using the specified status code. More...
 
int HttpResponse::sendError (int eCode, const char *msg)
 Sends an error response as a simple HTML page to the client using the specified status code. More...
 
int HttpResponse::sendBufAsError (int eCode)
 Sends the data formatted into the HttpResponse buffer as an error message to the client. More...
 
int HttpResponse::sendBufAsTxtError (int eCode)
 Sends the data formatted into the HttpResponse buffer as an error message to the client. More...
 
int HttpResponse::fmtError (int eCode, const char *fmt,...)
 This method implements a printf like implementation for formatting and sending an error message. More...
 
int HttpResponse::sendRedirect (const char *url)
 Sends a temporary redirect (302) response to the client using the specified redirect location URL. More...
 
int HttpResponse::redirect2TLS ()
 Prepares an HTTPS redirect (301) for a non-secure connection. More...
 
int HttpResponse::setContentLength (BaFileSize len)
 Sets the "Content-Length" parameter value. More...
 
int HttpResponse::setContentType (const char *type)
 Sets the "Content-Type" parameter value. More...
 
int HttpResponse::setDateHeader (const char *name, BaTime time)
 Sets a response header with the given name and date-value. More...
 
int HttpResponse::setHeader (const char *name, const char *value, bool replace=true)
 Sets a HTTP response header with the given name and value. More...
 
int HttpResponse::setMaxAge (BaTime seconds)
 Sets header "Cache-Control: max-age=seconds". More...
 
char * HttpResponse::fmtHeader (const char *name, int valueLen, bool replace=true)
 Pre-allocate memory for a {name, value} pair in the response header database. More...
 
void HttpResponse::setStatus (int statusCode)
 Sets the status code for this response. More...
 
int HttpResponse::printf (const char *fmt,...)
 printf is used for sending formatted data to the client. More...
 
int HttpResponse::write (const char *data, int useBuffering=TRUE)
 Used for sending a zero terminated string to the client. More...
 
BufPrintHttpResponse::getWriter ()
 Returns a BufPrint object that can send any type of data to the client. More...
 
int HttpResponse::write (const void *data, int len, int useBuffering=TRUE)
 Used for sending pre-formatted data to the client. More...
 
int HttpResponse::send (const void *data, int len)
 Used when sending raw data to the client. More...
 
int HttpResponse::setDefaultHeaders ()
 Sets the most common header values in servlet and CSP files. More...
 
HttpRequestHttpCommand::getRequest ()
 Get the request object. More...
 
HttpResponseHttpCommand::getResponse ()
 Get the response object. More...
 
struct HttpConnectionHttpCommand::getConnection ()
 Get the current connection object that the HttpCommand instance is bound with. More...
 
struct HttpServerHttpCommand::getServer ()
 Get the web-server object. More...
 
 HttpSessionAttribute::HttpSessionAttribute (const char *name, HttpSessionAttribute_Destructor terminate)
 Create a session attribute. More...
 
HttpSessionHttpSessionAttribute::getSession ()
 Get the session object. More...
 
HttpSessionAttributeHttpSession::getAttribute (const char *name)
 Returns the object bound with the specified name in this session, or null if no object is bound under the name. More...
 
BaTime HttpSession::getCreationTime ()
 Returns the time when this session was created, measured in seconds since midnight January 1, 1970 GMT. More...
 
BaTime HttpSession::getLastAccessedTime ()
 Returns the last time the client sent a request associated with this session, as the number of seconds since midnight January 1, 1970 GMT, and marked by the time the container received the request. More...
 
BaTime HttpSession::getMaxInactiveInterval ()
 Returns the maximum time interval, in seconds, that the session container will keep this session open between client accesses. More...
 
HttpServerHttpSession::getServer ()
 Get the server object. More...
 
void HttpSession::terminate ()
 Unbinds any objects bound to this session object, runs the HttpSession destructor, and frees the memory for this object. More...
 
int HttpSession::removeAttribute (const char *name)
 Removes the object bound with the specified name from this session. More...
 
int HttpSession::setAttribute (HttpSessionAttribute *value)
 Binds an object to this session, using the name specified. More...
 
void HttpSession::setMaxInactiveInterval (BaTime interval)
 Specifies the time, in seconds, between client requests before the session container will invalidate this session. More...
 
void HttpSession::incrRefCntr ()
 Increments the session reference counter. More...
 
void HttpSession::decrRefCntr ()
 Decrements the session reference counter. More...
 
U32 HttpSession::getId ()
 Returns a unique identifier assigned to this session. More...
 
U32 HttpSession::getUseCounter ()
 Get the session usage counter. More...
 
AuthenticatedUserHttpSession::getAuthenticatedUser ()
 Returns the AuthenticatedUser if user is authenticated. More...
 
void HttpSessionContainer::setMaxSessions (int max)
 Set the maximum number of session objects. More...
 
 HttpPage::HttpPage (HttpPage_Service service, const char *name)
 The HttpPage constructor. More...
 
 HttpPage::~HttpPage ()
 The HttpPage destructor unlinks the page from the parent directory. More...
 
bool HttpPage::isLinked ()
 Returns true if this page node is installed into a parent directory. More...
 
int HttpPage::unlink ()
 Unlinks/removes the page from the parent directory. More...
 
void HttpPage::service (HttpRequest *request, HttpResponse *response)
 The virtual service function (C callback function) is normally run by the parent directory when delegating the request to the page service method. More...
 
 HttpDir::HttpDir ()
 Constructor for creating a root dir, a root dir has no name. More...
 
 HttpDir::HttpDir (const char *name, S8 priority=0)
 Constructor for creating a sub-directory. More...
 
 HttpDir::~HttpDir ()
 Unlink this directory and notify all child pages/directories through their service callbacks with NULL request arguments. More...
 
char * HttpDir::makeAbsPath (const char *relPath, int relPathLen)
 Makes an absolute path based on where the HttpDir instance is installed in the virtual file system and the provided relative path. More...
 
char * HttpDir::getRootPath ()
 Calculates the root of where the HttpDir instance is installed in the virtual file system. More...
 
int HttpDir::insertDir (HttpDir *dir)
 Insert a sub-directory. More...
 
int HttpDir::insertPage (HttpPage *page)
 Insert a page in the directory. More...
 
HttpPageHttpDir::getFirstPage ()
 Returns the first page. More...
 
HttpDirHttpDir::getFirstDir ()
 Returns the first sub-directory. More...
 
HttpDirHttpDir::getDir (const char *name)
 Returns the first directory with the name given or NULL if not found. More...
 
HttpPageHttpDir::getPage (const char *name)
 Returns the page with the name given or NULL if not found. More...
 
HttpDirHttpDir::getNext ()
 Returns the next dir in the parent list. More...
 
HttpPageHttpDir::findPage (HttpPage *iter, const char *name)
 Searches for a page in this directory node. More...
 
static HttpDirHttpDir::findDir (HttpDir *iter, const char *name, unsigned int nameLen)
 Searches for a sub-directory in this directory node. More...
 
HttpDirHttpDir::createOrGet (const char *name)
 Returns a sub-directory with the given name. More...
 
HttpDir_Service HttpDir::setService (HttpDir_Service s)
 Replace the original service function in HttpDir with your own. More...
 
void HttpDir::p403 (const char *p403)
 Set a 403 denied request handler. More...
 
int HttpDir::unlink ()
 Unlinks/removes the directory from the parent directory. More...
 
bool HttpDir::isLinked ()
 Returns true if this directory node is installed into a parent directory. More...
 
void HttpDir::setAuthenticator (struct AuthenticatorIntf *authenticator, struct AuthorizerIntf *authorizer=0)
 Set the optional authenticator and optional AuthorizerIntf. More...
 
bool HttpDir::authenticateAndAuthorize (HttpCommand *cmd, const char *path)
 Authenticate and authorize the user. More...
 
 HttpServerConfig::HttpServerConfig ()
 The constructor sets up the default parameters. More...
 
int HttpServerConfig::setRequest (S16 min, S16 max)
 Set the size of the HTTP request buffer. More...
 
int HttpServerConfig::setResponseHeader (U16 min, U16 max)
 Set the size of the HTTP response header buffer. More...
 
int HttpServerConfig::setResponseData (U16 size)
 The HttpResponse object stores formatted data in the response data buffer. More...
 
int HttpServerConfig::setCommit (U16 size)
 Set the size of the HTTP response commit buffer. More...
 
int HttpServerConfig::setNoOfHttpCommands (U16 size)
 The number of HttpCommand instances created by the web-server. More...
 
int HttpServerConfig::setNoOfHttpConnections (U16 size)
 Number of HttpConnection instances. More...
 
int HttpServerConfig::setMaxSessions (U16 size)
 Maximum allowed active HttpSession objects. More...
 
 HttpServer::HttpServer (SoDisp *dispatcher, HttpServerConfig *cfg=0)
 Create a Web Server object. More...
 
 HttpServer::~HttpServer ()
 Stop using the server before destruction. More...
 
int HttpServer::insertRootDir (HttpDir *dir)
 Insert a root directory node. More...
 
ThreadMutexHttpServer::getMutex ()
 Get the dispatcher mutex. More...
 
int HttpServer::insertDir (const char *virtualDirRootPath, HttpDir *dir)
 Insert a directory node into the virtual file system. More...
 
int HttpServer::insertCSP (CspInit cspInit, const char *virtualDirRootPath, struct CspReader *reader)
 Insert and initialize a CSP Virtual Directory. More...
 
SoDispHttpServer::getDispatcher ()
 Returns the dispatcher object. More...
 
HttpDirHttpServer::getFirstRootDir ()
 Returns the first root directory. More...
 
HttpSessionContainerHttpServer::getSessionContainer ()
 Get the HttpSessionContainer. More...
 
HttpSessionHttpServer::getSession (U32 id)
 Returns the HttpSession associated with id or NULL if not found. More...
 
static void HttpServer::initStatic (void)
 The only purpose with this function is to clean all static variables that are in the BSS section; i.e., you do not need to call this function if you properly clear your static uninitialized variables. More...
 
static void HttpServer::setErrHnd (UserDefinedErrHandler e)
 You can set your own user defined error handler for the web-server. More...
 
void HttpServer::set404Page (const char *page404)
 Set a more user friendly 404 page. More...
 
const char * HttpServer::get404Page ()
 Returns a pointer to the current 404 page, if any. More...
 
static const char * HttpServer::getStatusCode (int code)
 Return a short description for common HTTP error codes. More...
 
HttpResponseHttpRequest::getResponse ()
 Returns the HttpResponse object. More...
 
HttpConnectionHttpRequest::getConnection ()
 Returns the connection object associated with this request. More...
 
HttpRequestHttpResponse::getRequest ()
 Get the HttpRequest object. More...
 
HttpCommandHttpResponse::getCommand ()
 Get the HttpCommand object. More...
 
HttpCommandHttpRequest::getCommand ()
 Get the HttpCommand object. More...
 
struct HttpServerHttpConnection::getServer ()
 

Typedef Documentation

◆ HttpCommand

typedef struct HttpCommand HttpCommand

The HttpCommand class is a container class for the HttpRequest and HttpResponse command pair.

An instance of the HttpServer class contains N HttpCommand instances, where N is set with method HttpServerConfig::setNoOfHttpCommands.

◆ HttpCookie

typedef struct HttpCookie HttpCookie

A cookie is used for exchanging a small amount of information between a HttpPage and a web browser.

A cookie's value can uniquely identify a client, so cookies are commonly used for session management.

A cookie has a name, a single value, and optional attributes such as: a comment, path and domain qualifiers, a maximum age, and a version number.

The cookie implementation is almost identical to the cookie implementation in the JavaTM Enterprise Edition

Typical usage:

HttpCookie* cookie = request->getCookie("myCookie");
if( ! cookie ) //If no cookie set for this page
{ //Create a session cookie
cookie = reply->createCookie("myCookie");
//Active cookie i.e. send cookie to client
cookie->activate();
}
//This will never fail
baAssert(cookie == request->getCookie("myCookie"));
void activate()
Activates the cookie.
Definition: HttpServer.h:818
A cookie is used for exchanging a small amount of information between a HttpPage and a web browser.
Definition: HttpServer.h:589

Cookie objects and getter strings are owned by the request/response and expire with it. Do not destroy or free a cookie obtained from the server. String setters copy input; a successful replacement invalidates the old getter pointer. Activate before committing to emit a Set-Cookie header.

◆ HttpDir

typedef struct HttpDir HttpDir

An instance of the HttpDir class, which is a collection of zero or more resources, serves as one directory entry in the virtual file system.

An instance of HttpDir class installed in the virtual file system searches for the next directory and delegates the request to the directory if found. The HttpDir class also delegates requests to HttpPage instances installed in the directory.

The HttpDir class can be sub-classed and the functionality can be extended. The HttpDir instance is an ideal building block when designing Representational State Transfer (RESTful) based applications. See the tutorial Designing Embedded RESTful Services in C and C++ for details.

See also
HttpPage

◆ HttpDir_Service

typedef int(* HttpDir_Service) (struct HttpDir *o, const char *relPath, HttpCommand *cmd)

The HttpDir service callback function.

Parameters
othe HttpDir instance
relPaththe relative path: absolute path - base path
cmdBorrowed request/response command, or NULL for destruction. relPath is borrowed during a request and NULL for destruction. Handle NULL cmd before inspecting request data. Cleanup must release derived resources.
Returns
0 if handled, nonzero to continue searching another directory. Do not emit a response when returning "not handled". Cleanup returns zero.

◆ HttpPage

typedef struct HttpPage HttpPage

An HttpPage, which is typically created by the CSP compiler, is similar to a Java servlet.

Please see our introduction whitepaper for an introduction to server side scripting using the CSP compiler. See the device control whitepaper for an example of how to manually sub-class the HttpPage class.

The page service function cannot be a virtual C++ function since the code must be compatible with C. You must create a "static C++" callback method, which means that the method has no "this" pointer. The "this" pointer is passed into the static method as the first parameter in the callback function. The "static" callback function in the above code simply typecasts the HttpPage object to a MyPage object and calls the private service method, which has a "this" pointer.

Typical C usage:

struct MyPage
{
HttpPage page;
int myData;
};
void MyPage_service(HttpPage* page,
HttpRequest* request,
HttpResponse* response)
{
struct MyPage* o = (struct MyPage*)page;
if(!request) return; // This example uses caller-owned page storage.
o->myData++;
"<html><body>"
"Number of visits: %d"
"</body></html>",
o->myData);
}
void MyPage_constructor(struct MyPage* o, const char* name)
{
HttpPage_constructor(&o->page, MyPage_service, name);
o->myData = 0;
}
void BA_API HttpPage_constructor(HttpPage *o, HttpPage_Service service, const char *name)
The HttpPage constructor.
BA_API int HttpResponse_printf(HttpResponse *o, const char *fmt,...)
printf is used for sending formatted data to the client.
An HttpPage, which is typically created by the CSP compiler, is similar to a Java servlet.
Definition: HttpServer.h:2656
The HttpServer creates an HttpRequest object when the HttpServer parses a client request.
Definition: HttpServer.h:950
This object is used when sending response messages back to the client.
Definition: HttpServer.h:1379
See also
HttpDir

◆ HttpPage_Service

typedef void(* HttpPage_Service) (struct HttpPage *page, HttpRequest *request, HttpResponse *response)

The HttpPage service function.

All service functions must be of this type.

Parameters
pagea pointer to the page object. This object can be typecasted to the overloaded type.
requestA pointer to the request object created by HttpServer.
responseBorrowed response during service; NULL for destruction. request is also NULL for destruction. Test this before using either pointer. The callback returns no value. On destruction, release derived resources according to their ownership; ordinary requests borrow all three objects.

◆ HttpParameterIterator

The HttpParameterIterator is used for iterating through the form elements parsed by the HttpServer object.

C++ Example:

for( ; i.hasMoreElements() ; i.nextElement())
{
if( ! strcmp(i.getName(), "visa number") )
visaNumber = i.getValue();
}
The HttpParameterIterator is used for iterating through the form elements parsed by the HttpServer ob...
Definition: HttpServer.h:485

C Example: See HttpParameter.

See also
HttpRequest::getParameter HttpParameter

◆ HttpRequest

typedef struct HttpRequest HttpRequest

The HttpServer creates an HttpRequest object when the HttpServer parses a client request.

The object is passed in as the first argument to the HttpPage service function. Request-owned pointers (headers, parameters, cookies, URI, and associated command objects) must not be freed or retained beyond request completion. Access requires the server mutex. Copy data needed by asynchronous work.

◆ HttpResponse

typedef struct HttpResponse HttpResponse

This object is used when sending response messages back to the client.

The HttpServer creates an HttpResponse object and passes it as the second argument to the HttpPage Service Function.

The HttpResponse struct contains a number of methods that can be used when sending messages back to the client from the HttpPage Service Function. Most of the response functions return an int. The methods return 0 on success or -1 on failure. A function might, for example, send -1 if the socket connection closes.

◆ HttpServer

typedef struct HttpServer HttpServer

The Web Server.

◆ HttpServerConfig

Use an instance of this class if you want to override the default web-server parameters.

An instance of this class can be created on the stack in a function. The object is of no use after the call to the HttpServer constructor. You should not create an instance of this class unless you want to change the default parameters in an HttpServer instance.

◆ HttpSession

typedef struct HttpSession HttpSession

Provides a way to identify a user across more than one page request or visit to a web site, and to store information about that user.

The HttpSession container uses this class to create a session between an HTTP client and an HTTP server. The session persists for a specified time period across more than one connection or page request from the user. A session usually corresponds to one user who may visit a site many times. The server can maintain a session in many ways, for example, by using cookies or rewriting URLs.

This interface enables you to:

  • View and manipulate information about a session, such as the session identifier, creation time, and last accessed time.
  • Bind objects to sessions, allowing user information to persist across multiple user connections

The session is automatically terminated after being inactive for the specified number of seconds. The default value is 1200 seconds, or 20 minutes.

The session object and all the session attributes associated with the session are automatically terminated by the server when "MaxInactiveInterval" is reached.

A malicious user can create a tool that could potentially overflow the session container. The authentication classes make sure that a session object is not created before the user is authenticated. It is therefore recommended to create a session object by using the authentication classes. See HttpSessionContainer::setMaxSessions for more information on the size of the session container.

This class is similar to the java Interface HttpSession.

Garbage Collection

Unlike the Java programming language, C and C++ does not handle garbage collection of released objects. We must explicitly delete the object when using C and C++. This is a problem when using the session object as the session may expire or be terminated by another concurrent request. The web-server is therefore designed to keep track of the sessions by using reference counting. The reference counting is automatic when fetching the session object by using HttpRequest::getSession. The web-server keeps track of the number of concurrent requests using the same object and makes sure that the object is not deleted as long as any request is being serviced.

CSP example

<%
/* Get session and implisitly increment the reference counter */
HttpSession* s = request->getSession();
/* Method getSession may return NULL if not enough memory, if the
 * response is committed, or if HttpSession::terminate was previously
 * called during this request.
 */
if(s)
{
   U32 sessionId = s->getId();
   assert(server->getSession(sessionId) != NULL);

   s->terminate(); /* invalidated, but not terminated */
   /* Method getSession returns null since the object is invalidated.
    */
   assert(request->getSession() == NULL);

   HttpServer* server = request->getServer();

   /* HttpServer::getSession can be used by any code, not just a request
   * callback method. The result is NULL for any code using this
   * sessionId even though the actual session object is still not
   * deleted.
   */
   assert(server->getSession(sessionId) == NULL);

   /* The following is not recommended, but the code will not crash as
    * the object is not yet deleted.
    */
   s->getAttribute("MyAttr");
}
%>

We called method HttpSession::terminate in the above example. The termination of the session object is automatically delayed by the web-server until all concurrent requests using this session object have completed.

The HttpRequest::getSession method automatically handles the reference counting and makes sure that the session object cannot be deleted before at the end of the request. This means that you do not normally have to deal with this problem.

The following methods do not handle the reference counting:

  • HttpServer::getSession

Faulty CSP example:

U32 sessionId = myObj->getMySavedSessionId();
HttpSession* s = request->getServer()->getSession(sessionId);
if(sessionId)
{
   //HttpResponse::printf may yield and another thread may start to execute.
   response->printf("I found the session for ID %u", sessionId);
   s->getAttribute("MyAttr"); // Dangerous, the session may be deleted.
}

Any method that writes data to the socket may yield the current thread. Another request may terminate the session or the session may expire. The above code is therefore unsafe.

We can fix the above problem by explicitly incrementing and decrementing the reference counter.

Correct CSP example:

U32 sessionId = myObj->getMySavedSessionId();
HttpSession* s = request->getServer()->getSession(sessionId);
if(sessionId)
{
   s->incrRefCntr();
   response->printf("I found the session for ID %u", sessionId);
   s->getAttribute("MyAttr");
   /* The above code is safe since the object is locked, but
    * request->getServer()->getSession(sessionId) may return null.
    */
   s->decrRefCntr();
}

It is very important that you keep track of how many times you call incrRefCntr and decrRefCntr. Your system will eventually become unstable if you call one of the methods more than the other.

◆ HttpSessionAttribute

The interface to an HttpSession attribute.

Each attribute added to an HttpSession must inherit from this class. The HttpSession object calls the HttpSessionAttribute destructor when the HttpSession object is terminated.

The HttpSessionAttribute is an abstract class with a virtual destructor. We cannot use a "real" virtual destructor since the Web-Server must be ANSI C compatible. The function pointer passed in to the constructor is the function being called when the attribute is scheduled to terminate. The function pointer can be NULL if no cleanup is necessary.

Typical C++ usage:

class MyAttribute : public HttpSessionAttribute
{
public:
MyAttribute() : HttpSessionAttribute("MyAttribute", destructor) {}
private:
static void destructor(HttpSessionAttribute* o);
};
void MyAttribute::destructor(HttpSessionAttribute* o)
{
delete ((MyAttribute*)o); // Run destructor and free memory.
}
The interface to an HttpSession attribute.
Definition: HttpServer.h:2247

◆ HttpSessionAttribute_Destructor

typedef void(* HttpSessionAttribute_Destructor) (struct HttpSessionAttribute *o)

HttpSessionAttribute termination callback function.

This function is called when the session object times out. The callback function should release the memory to the session attribute.

Parameters
oThe attribute object, typically cast to its containing application type. Also called when explicitly removing an attribute. Release application-owned payload/allocation here; do not call HttpSessionAttribute_destructor again.

◆ HttpSessionContainer

The HttpSession container class.

You get a reference to this class from HttpServer::getSessionContainer.

◆ HttpStdHeaders

Standard HTTP header values.

See also
HttpRequest::getHeaderValue

Enumeration Type Documentation

◆ HttpMethod

enum HttpMethod

HTTP method types.

The most common headers are: HttpMethod_Get, HttpMethod_Head, HttpMethod_Options, HttpMethod_Post, HttpMethod_Put and HttpMethod_Trace.

Function Documentation

◆ activate()

void HttpCookie::activate ( )

Activates the cookie.

The cookie will not be sent to the client unless this function is called. You cannot activate a cookie if the data is committed. See HttpResponse::committed for more information.

◆ authenticateAndAuthorize()

bool HttpDir::authenticateAndAuthorize ( HttpCommand cmd,
const char *  path 
)

Authenticate and authorize the user.

This method provides a simple mechanism for authenticating and authorizing a user. The method takes care of the response message if the user is not authenticated and authorized – i.e., you should not send a response message if this method returns false. See the DiskDir implementation for an example of how to use this method.

Parameters
cmdThe parameter passed into the HttpDir service callback method.
pathThe relative path (from the URL) at the current position in the virtual file system.
Returns
true if:
  • Both authenticator and authorizer are NULL.
  • This is an include or forward request, or NO_HTTP_SESSION is configured.
  • The user is authenticated and the realm argument is NULL.
  • The user is authenticated and authorized.

◆ byteCount()

U32 HttpResponse::byteCount ( )

Returns number of bytes sent thus far.

◆ checkMethods()

int HttpRequest::checkMethods ( HttpResponse resp,
U32  methods,
bool  addDefault = TRUE 
)

Checks the HTTP method type and sends a response message if condition met.

RFC 2616 specifies that each resource in a web-server can have its own set of allowed HTTP methods.

The checkMethod method checks if the requested HTTP method is one of the allowed HTTP methods as specified in the argument list to checkMethod. The function returns 0 if the condition is met; otherwise, status code is set to 405 and a nonzero value is returned.

The method checkMethod also checks if the requested HTTP method is OPTIONS. If the requested HTTP method is OPTIONS, a nonzero value is returned.

A response message is automatically sent to the client when method checkMethod returns a nonzero number; thus, the service function should not send a response message.

This method is typically used by HttpDir and HttpPage objects prior to sending a response message. For example, a service function that only accepts GET requests would do the following:

HttpMethod_Options and HttpMethod_Head should not be added to the argument list since the two HTTP methods are added automatically if 'addDefault' is TRUE. It is assumed that a resource always can accept HEAD and OPTIONS. The OPTIONS request is handled automatically by checkMethod, and HEAD is automatically handled by the HttpResponse write methods; thus, the two methods are transparent to users.

A CSP page should not use the checkMethod method as the auto generated CSP code automatically sets the HttpMethod_Get, HttpMethod_Post, HttpMethod_Head and HttpMethod_Options.

Se RFC2616 section 9.2 for more information.

Parameters
respThe response object.
methodsThe methods added. Separate multiple methods by using character |.
addDefaultset to true if you would like to add OPTIONS and HEAD.
See also
HttpRequest::getMethodType

◆ checkTime()

BaBool HttpRequest::checkTime ( struct HttpResponse resp,
BaTime  time 
)

Parses and checks if the "If-Modified-Since" time is equal or greater than "time".

Prepares a "304 Not modified" response and returns true if the condition is true; otherwise, false is returned.

! You cannot write to the output stream if this function returns true.

Parameters
respthe response object is used if sending a 304 response.
timeis the GMT time.
Returns
TRUE if the cached time condition matches and response setup was attempted; FALSE otherwise. This is not a network delivery result. time is Unix time in seconds; call before committing the response.

◆ committed()

bool HttpResponse::committed ( ) const

Returns a boolean indicating if the response has been committed.

A committed response has already had its status code and headers written.

◆ containsHeader()

const char * HttpResponse::containsHeader ( const char *  name)

Searches the internal response header database for a header with the specified name.

Returns the value of the {name, value} pair if the header is found or NULL if not found. The response header values are set with method HttpResponse::setHeader. This method is typically used by servlets either included by another servlet or when a servlet forwards the request to another servlet. See methods HttpResponse::forward and HttpResponse::include for more information.

◆ createCookie()

HttpCookie * HttpResponse::createCookie ( const char *  name)

Create a cookie.

Parameters
namethe name of the cookie. Returns an existing cookie with the same name, or a new cookie. Returns NULL if the cookie or its name cannot be allocated.

◆ createOrGet()

HttpDir * HttpDir::createOrGet ( const char *  name)

Returns a sub-directory with the given name.

The directory will be created if not found.

HttpDir* mySubDir3 = myDir->createOrGet("sub1/sub2/sub3");
HttpDir * createOrGet(const char *name)
Returns a sub-directory with the given name.
Definition: HttpServer.h:3125
An instance of the HttpDir class, which is a collection of zero or more resources,...
Definition: HttpServer.h:2777
Parameters
nameNUL-terminated slash-separated path. NULL/empty returns this directory; a leading slash is skipped, not resolved from the root.
Returns
Borrowed existing/new directory, or NULL on allocation failure. Newly created nodes copy their path components and are owned by the directory tree. Partial intermediate nodes can remain on failure.

◆ decrRefCntr()

void HttpSession::decrRefCntr ( )

Decrements the session reference counter.

This method is used together with method incrRefCntr. See HttpSession for more information. A matching outstanding reference is required. This can immediately destroy a termination-pending session; do not access it afterward.

◆ deleteCookie()

void HttpCookie::deleteCookie ( )

Specifies a path for the cookie to which the client should return the cookie.

This method sets the maximum age to zero. Calling this method has the same effect as calling setMaxAge(0). You must make sure the cookie path is set and is identical to the path you used when creating the cookie.

◆ encodeRedirectURL()

const char * HttpResponse::encodeRedirectURL ( const char *  pathName)

Encodes the specified URL into an absolute URL, or if encoding is not needed, returns the URL unchanged.

Parameters
pathNamethe absolute or relative URL to be encoded
Returns
the encoded absolute URL. The buffer returned by encodeRedirectURL is valid until end of client request or until encodeRedirectURL is called again.
See also
HttpResponse::sendRedirect

◆ encodeRedirectURLWithParam()

const char * HttpResponse::encodeRedirectURLWithParam ( const char *  pathName)

This method is similar to HttpResponse::encodeRedirectURL, but this method also includes all URL-encoded parameters in the request line and in the body if the client sent a POST message.

Parameters
pathNamethe absolute or relative URL to be encoded
Returns
the encoded absolute URL. The buffer returned by encodeRedirectURL is valid until end of client request or until encodeRedirectURL is called again.
See also
HttpResponse::sendRedirect

◆ encodeUrl()

const char * HttpResponse::encodeUrl ( const char *  path)

Encodes an absolute or relative URL, or if encoding is not needed, returns the URL unchanged.

This method escapes all symbols that cannot be in a URL. The method differs from encodeRedirectURL in that it only escapes non-URL compatible symbols.

◆ findDir()

HttpDir * HttpDir::findDir ( HttpDir iter,
const char *  name,
unsigned int  nameLen 
)
static

Searches for a sub-directory in this directory node.

Parameters
itera pointer to a reference in the directory list.
namethe name of the directory to search for.
nameLenthe length of name.
Returns
the directory or NULL if not found.

Typical usage:

HttpDir* dir = dir->findDir(dir->getFirstDir(), "dirName",
strlen("dirName"));
static HttpDir * findDir(HttpDir *iter, const char *name, unsigned int nameLen)
Searches for a sub-directory in this directory node.
Definition: HttpServer.h:3122
HttpDir * getFirstDir()
Returns the first sub-directory.
Definition: HttpServer.h:3114

◆ findPage()

HttpPage * HttpDir::findPage ( HttpPage iter,
const char *  name 
)

Searches for a page in this directory node.

Parameters
itera pointer to a reference in the page list.
namethe name of the page to search for.
Returns
the page or NULL if not found.

Typical usage:

HttpPage* page = dir->getPage("pageName"); // Also handles an empty directory.

iter must be a valid page-list node, not NULL. Prefer getPage(name) when searching from the start, since getFirstPage() returns NULL for an empty list. name is a required case-sensitive NUL-terminated string.

◆ flush()

int HttpResponse::flush ( )

Forces any content in the buffer to be written to the client.

A call to this method automatically commits the response, meaning the status code and headers will be written.

Returns
0 on success or the writer/transport error. Buffered output may already have been partly sent on failure; no byte count is returned.

◆ fmtError()

int HttpResponse::fmtError ( int  eCode,
const char *  fmt,
  ... 
)

This method implements a printf like implementation for formatting and sending an error message.

The error message is sent as plain text to the client.

Parameters
eCodeThe HTTP error code.
fmtSee BufPrint::printf.

◆ fmtHeader()

char * HttpResponse::fmtHeader ( const char *  name,
int  valueLen,
bool  replace = true 
)

Pre-allocate memory for a {name, value} pair in the response header database.

Sometimes setting a header value with setHeader involves unnecessary copying or allocation of memory. The fmtHeader method makes it possible to pre-allocate a memory area in the internal {name, value} pair database in the response object. The function, if successful, returns a pointer to a memory area for the value in a {name, value} pair. You can then use, for example, sprintf to format this memory area.

You must use extreme caution when using this function. Writing more data to the pointer returned than requested, will corrupt the internal data structures in the database.

Example:
Setting the extended foobar header as per RFC 3092

const char foo[] = {"foo"};
const char bar[] = {"bar"};
int len = strlen(bar);
char* ptr = resp->fmtHeader(foo, len+1);
if(ptr)
strcpy(ptr, bar);
Parameters
namethe name of the header to set.
valueLenthe length of the memory area returned by fmtHeader.
replacethe parameter if already set.
Returns
Borrowed writable value storage, or NULL for invalid name/length, include context, committed response, or allocation failure. Write a NUL-terminated value before any response operation that uses headers. Returned storage may be invalidated by later header changes/reset.

◆ forward()

int HttpResponse::forward ( const char *  path)

Forwards a request from a servlet to another resource (servlet, CSP file, or HTML file).

This method allows one servlet/CSP file to do preliminary processing of a request and another resource to generate the response. See the introduction to Request Delegation for more information.

Forward should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method returns a non-zero value.

Parameters
pathis the path to the resource to execute. The path is assumed to be an absolute path value on the server if the string starts with "/". The path is otherwise assumed to be a relative path.

This method is similar to method redirect, except that forward bypasses any required authentication or authorization.

Returns
Zero on success. Returns a non-zero value if the response is committed.
See also
redirect

◆ get404Page()

const char * HttpServer::get404Page ( )

Returns a pointer to the current 404 page, if any.

◆ getAttribute()

HttpSessionAttribute * HttpSession::getAttribute ( const char *  name)

Returns the object bound with the specified name in this session, or null if no object is bound under the name.

Parameters
nameRequired case-sensitive NUL-terminated name.
Returns
Borrowed attribute or NULL. Its termination callback controls lifetime; do not free it while attached.

◆ getAuthenticatedUser() [1/2]

AuthenticatedUser * HttpRequest::getAuthenticatedUser ( )

Returns the authenticated user or NULL if user is not authenticated.

◆ getAuthenticatedUser() [2/2]

AuthenticatedUser * HttpSession::getAuthenticatedUser ( )

Returns the AuthenticatedUser if user is authenticated.

◆ getBuffer()

HttpInData * HttpRequest::getBuffer ( )

Get the internal rec buffer.

◆ getCommand() [1/2]

HttpCommand * HttpRequest::getCommand ( )

Get the HttpCommand object.

◆ getCommand() [2/2]

HttpCommand * HttpResponse::getCommand ( )

Get the HttpCommand object.

◆ getConnection() [1/3]

const char * HttpStdHeaders::getConnection ( )

Returns the connection type for HTTP 1.1 connections, returns "Close" or "Keep-Alive.

◆ getConnection() [2/3]

HttpConnection * HttpRequest::getConnection ( )

Returns the connection object associated with this request.

◆ getConnection() [3/3]

struct HttpConnection * HttpCommand::getConnection ( )

Get the current connection object that the HttpCommand instance is bound with.

◆ getContentLength()

SBaFileSize HttpStdHeaders::getContentLength ( )

Returns the content length if request contains a body.

◆ getContentType()

const char * HttpStdHeaders::getContentType ( )

Returns the content type, for example: "application/x-www-form-urlencoded".

◆ getCookie()

HttpCookie * HttpRequest::getCookie ( const char *  name)

Returns the requested cookie or NULL if no cookie matches the name.

Parameters
namethe name of the cookie.

◆ getCreationTime()

BaTime HttpSession::getCreationTime ( )

Returns the time when this session was created, measured in seconds since midnight January 1, 1970 GMT.

◆ getDir()

HttpDir * HttpDir::getDir ( const char *  name)

Returns the first directory with the name given or NULL if not found.

Parameters
nameRequired NUL-terminated exact, case-sensitive child name. Result is borrowed.

◆ getDispatcher()

SoDisp * HttpServer::getDispatcher ( )

Returns the dispatcher object.

◆ getDomain()

const char * HttpStdHeaders::getDomain ( )

Returns the host header without any port number.

Typically used with name-based virtual hosting. The returned value is always lower-case.

See also
getHost.

◆ getFirstDir()

HttpDir * HttpDir::getFirstDir ( )

Returns the first sub-directory.

◆ getFirstPage()

HttpPage * HttpDir::getFirstPage ( )

Returns the first page.

◆ getFirstRootDir()

HttpDir * HttpServer::getFirstRootDir ( )

Returns the first root directory.

Returns the first root directory or NULL if no root directory is installed.

◆ getHeaders()

HttpHeader * HttpRequest::getHeaders ( int *  len)

Return an HTTP header iterator that can iterate and fetch all the HTTP headers.

CSP page Example:

int len;
HttpHeader* hIter = request->getHeaders(&len);
for(int i = 0 ; i < len ; i++, hIter++)
{
response->printf("%s = %s\n",
hIter->name(request),
hIter->value(request));
}
Parameters
lenRequired output pointer receiving the number of entries.
Returns
Borrowed array of len entries; use each with this same request. The array and its name/value strings expire with the request.

◆ getHeaderValue()

const char * HttpRequest::getHeaderValue ( const char *  name)

Returns the value of the specified request header.

If the request did not include a header of the specified name, this method returns null. The header name is case insensitive. You can use this method with any request header.

Parameters
namea string specifying the header name.
See also
HttpRequest::getStdHeaders HttpStdHeaders

◆ getHost()

const char * HttpStdHeaders::getHost ( )

Returns the host header.

The host header includes the port number if the request is of the form http://myserver.com:8080

See also
getDomain

◆ getId()

U32 HttpSession::getId ( )

Returns a unique identifier assigned to this session.

See HttpServer::getSession for more information.

◆ getLastAccessedTime()

BaTime HttpSession::getLastAccessedTime ( )

Returns the last time the client sent a request associated with this session, as the number of seconds since midnight January 1, 1970 GMT, and marked by the time the container received the request.

◆ getMaxInactiveInterval()

BaTime HttpSession::getMaxInactiveInterval ( )

Returns the maximum time interval, in seconds, that the session container will keep this session open between client accesses.

◆ getMethod() [1/2]

const char * HttpRequest::getMethod ( )

Returns a string representation of the value returned by HttpRequest::getMethodType.

See also
HttpRequest::getMethodType

◆ getMethod() [2/2]

const char * HttpRequest::getMethod ( HttpMethod  method)
static

Returns a string representation of the argument.

See also
HttpRequest::getMethodType

◆ getMethodType()

HttpMethod HttpRequest::getMethodType ( )

Returns the method type.

Common method types are HttpMethod_Get, HttpMethod_Post and HttpMethod_Head.

See also
HttpRequest::getMethod HttpRequest::checkMethods

◆ getMutex()

ThreadMutex * HttpServer::getMutex ( )

Get the dispatcher mutex.

◆ getNext()

HttpDir * HttpDir::getNext ( )

Returns the next dir in the parent list.

(next sibling)

◆ getPage()

HttpPage * HttpDir::getPage ( const char *  name)

Returns the page with the name given or NULL if not found.

Parameters
nameRequired NUL-terminated exact, case-sensitive page name. Result is borrowed.

◆ getParameter()

const char * HttpRequest::getParameter ( const char *  paramName)

Returns the value of a request parameter as a const char* or null if the parameter does not exist.

Request parameters is extra information sent with the request that is contained in the query string or posted form data.

If you use this method with a multivalued parameter, the value returned is equal to the first value in a HttpParameterIterator.

Parameters
paramNameRequired NUL-terminated, case-sensitive name. Returned values are borrowed for the request lifetime.
See also
HttpParameterIterator HttpParameter

◆ getRequest() [1/2]

HttpRequest * HttpResponse::getRequest ( )

Get the HttpRequest object.

◆ getRequest() [2/2]

HttpRequest * HttpCommand::getRequest ( )

Get the request object.

◆ getRequestURI()

const char * HttpRequest::getRequestURI ( )

Returns the pathname.

The pathname will be "/myDir/index.html" if the URL is "http://myServer.net/myDir/index.html"

◆ getRequestURL()

const char * HttpRequest::getRequestURL ( bool  forceHttps = false)

Reconstructs the URL the client used to make the request.

The returned URL contains a protocol, server name, port number, and server path, but it does not include query string parameters.

Parameters
forceHttpsmakes the function return a URL that starts with HTTPS if forceHttps is set to true. The default is to return a URL that starts with HTTP for a non-secure connection and HTTPS for a secure connection.
See also
HttpResponse::forceHttps
Returns
Borrowed URL or NULL on allocation failure. Valid until another request/redirect URL encoding call or request completion. Host normally comes from the request Host header; without it the implementation uses the peer address. Do not treat this as the server's configured URL.

◆ getResponse() [1/2]

HttpResponse * HttpRequest::getResponse ( )

Returns the HttpResponse object.

◆ getResponse() [2/2]

HttpResponse * HttpCommand::getResponse ( )

Get the response object.

◆ getRootPath()

char * HttpDir::getRootPath ( )

Calculates the root of where the HttpDir instance is installed in the virtual file system.

This method is not fast and you should, therefore, cache the result. The path may, however, change if the HttpDir instance is dynamically moved to another location in the virtual file system.

Memory is allocated by using baMalloc. The caller must release the memory by using baFree.

See also
makeAbsPath
Returns
Caller-owned NUL-terminated root path, or NULL on allocation failure.

◆ getServer() [1/4]

struct HttpServer * HttpConnection::getServer ( )
Returns
Borrowed associated server, possibly NULL for a non-HTTP use.

◆ getServer() [2/4]

HttpServer * HttpRequest::getServer ( )

Returns the web server object.

◆ getServer() [3/4]

struct HttpServer * HttpCommand::getServer ( )

Get the web-server object.

◆ getServer() [4/4]

HttpServer * HttpSession::getServer ( )

Get the server object.

◆ getSession() [1/3]

HttpSession * HttpSessionAttribute::getSession ( )

Get the session object.

◆ getSession() [2/3]

HttpSession * HttpRequest::getSession ( BaBool  create = true)

Returns the current HttpSession associated with this request, or if there is no current session and create is true, returns a new session.

If create is false and the request has no valid HttpSession, this method returns NULL.

To make sure the session is properly maintained, you must call this method before the response is committed.

Parameters
createTRUE to create a new session for this request if necessary; FALSE to return NULL if there is no current session.
Returns
the HttpSession associated with this request or null if there is no session and create is false, creation fails, the response is already committed, or the current session has termination pending. The pointer is borrowed; hold a session reference if retaining it beyond this request. See HttpSession::incrRefCntr.

Typical C++ usage:

MyPage::service(HttpRequest* request, HttpResponse* response)
{
HttpSession* session = request->getSession(true);
if(!session) return; // Allocation, limit, or committed response.
ShoppingCart* sc = (ShoppingCart*)session->getAttribute("Cart");
if ( ! sc )
{// User has no shopping cart, create one.
sc = new ShoppingCart();
session->setAttribute("Cart", sc);
}
}
int setAttribute(HttpSessionAttribute *value)
Binds an object to this session, using the name specified.
Definition: HttpServer.h:2510
HttpSessionAttribute * getAttribute(const char *name)
Returns the object bound with the specified name in this session, or null if no object is bound under...
Definition: HttpServer.h:2496
HttpSession * getSession(BaBool create=true)
Returns the current HttpSession associated with this request, or if there is no current session and c...
Definition: HttpServer.h:1341
Provides a way to identify a user across more than one page request or visit to a web site,...
Definition: HttpServer.h:2305

◆ getSession() [3/3]

HttpSession * HttpServer::getSession ( U32  id)

Returns the HttpSession associated with id or NULL if not found.

See HttpSession::getId for more information.

It can be potentially dangerous to use this method in a multithread enabled web-server. See the explanation in the HttpSession for more information.

See also
HttpSession::incrRefCntr

◆ getSessionContainer()

HttpSessionContainer * HttpServer::getSessionContainer ( )

◆ getStatusCode()

const char * HttpServer::getStatusCode ( int  code)
static

Return a short description for common HTTP error codes.

Parameters
codeHTTP status integer recognized by the implementation.
Returns
Static string including the numeric code and reason phrase; an unrecognized code returns "??? Server Error". Do not free.

◆ getStdHeaders()

HttpStdHeaders * HttpRequest::getStdHeaders ( )

Returns an object containing standard HTTP headers.

See also
HttpStdHeaders HttpRequest::getHeaderValue

◆ getUseCounter()

U32 HttpSession::getUseCounter ( )

Get the session usage counter.

◆ getVersion()

const char * HttpRequest::getVersion ( )

Returns the HTTP version as a string, normally "1.1".

◆ getWriter()

BufPrint * HttpResponse::getWriter ( )

Returns a BufPrint object that can send any type of data to the client.

The BufPrint object is also used implicitly when using method HttpResponse::printf or HttpResponse::write.

Returns
Borrowed active writer, valid during the request. This initializes output framing but does not expose a framing-initialization error.

◆ hasMoreElements()

bool HttpParameterIterator::hasMoreElements ( )

Returns true if more elements.

◆ HttpCookie_activate()

BA_API void HttpCookie_activate ( HttpCookie o)

Activates the cookie.

The cookie will not be sent to the client unless this function is called. You cannot activate a cookie if the data is committed. See HttpResponse::committed for more information.

Parameters
oRequired live cookie.

◆ HttpCookie_getComment()

BA_API const char * HttpCookie_getComment ( HttpCookie o)

Returns the comment set for this cookie or null if the cookie comment is not set.

Parameters
oRequired live cookie.

◆ HttpCookie_getDomain()

BA_API const char * HttpCookie_getDomain ( HttpCookie o)

Returns the domain name set for this cookie.

Parameters
oRequired live cookie.

◆ HttpCookie_getHttpOnly()

BA_API BaBool HttpCookie_getHttpOnly ( HttpCookie o)

Return the HttpOnly attribute.

See also
setHttpOnly.
Parameters
oRequired live cookie.

◆ HttpCookie_getMaxAge()

BA_API BaTime HttpCookie_getMaxAge ( HttpCookie o)

Returns the maximum age of the cookie, specified in seconds; by default, 0 indicating the cookie will persist until browser shutdown.

Parameters
oRequired live cookie.

◆ HttpCookie_getName()

BA_API const char * HttpCookie_getName ( HttpCookie o)

Returns the name of the cookie.

Parameters
oRequired live cookie.

◆ HttpCookie_getPath()

BA_API const char * HttpCookie_getPath ( HttpCookie o)

Returns the path on the server to which the browser returns this cookie.

Parameters
oRequired live cookie.

◆ HttpCookie_getSecure()

BA_API BaBool HttpCookie_getSecure ( HttpCookie o)

Returns true if the browser is sending cookies only over a secure protocol, or false if the browser can send cookies using any protocol.

Parameters
oRequired live cookie.

◆ HttpCookie_getValue()

BA_API const char * HttpCookie_getValue ( HttpCookie o)

Returns the value of the cookie.

Parameters
oRequired live cookie.

◆ HttpCookie_setComment()

BA_API int HttpCookie_setComment ( HttpCookie o,
const char *  purpose 
)

Specifies a comment that describes a cookie's purpose.

Returns 0 on success or E_MALLOC on allocation failure, preserving the old comment on failure. NULL clears the comment.

Parameters
purposePurpose text as a NUL-terminated string, or NULL to clear.
oRequired live cookie.

◆ HttpCookie_setDomain()

BA_API int HttpCookie_setDomain ( HttpCookie o,
const char *  pattern 
)

Specifies the domain within which this cookie should be presented.

Returns 0 on success or E_MALLOC on allocation failure, preserving the old domain on failure. NULL clears the domain.

Parameters
patternDomain attribute as a NUL-terminated string, or NULL to clear.
oRequired live cookie.

◆ HttpCookie_setHttpOnly()

BA_API void HttpCookie_setHttpOnly ( HttpCookie o,
BaBool  flag 
)

Marks or unmarks this Cookie as HttpOnly.

If isHttpOnly is set to true, this cookie is marked as HttpOnly, by adding the HttpOnly attribute to it.

HttpOnly cookies are not supposed to be exposed to client-side scripting code, and may therefore help mitigate certain kinds of cross-site scripting attacks.

Parameters
flagtrue adds HttpOnly; false removes it. Default false.
oRequired live cookie.

◆ HttpCookie_setMaxAge()

BA_API void HttpCookie_setMaxAge ( HttpCookie o,
BaTime  expiry 
)

Sets the maximum age of the cookie in seconds.

The cookie is by default not stored persistently and will be deleted when the web browser exits. This function turns the cookie into a persistent cookie, which the browser keeps in its cookie container. A persistent cookie can later be deleted with function HttpCookie::deleteCookie.

Parameters
expiryLifetime in seconds; a positive value makes the cookie persistent. Zero explicitly requests deletion. A freshly created cookie's default zero instead means no lifetime attribute was set.
oRequired live cookie.

◆ HttpCookie_setPath()

BA_API int HttpCookie_setPath ( HttpCookie o,
const char *  uri 
)

Set the cookie path.

Returns 0 on success or E_MALLOC on allocation failure, preserving the old path on failure. NULL clears the path.

Parameters
uriPath attribute as a NUL-terminated string, or NULL to clear.
oRequired live cookie.

◆ HttpCookie_setSecure()

BA_API void HttpCookie_setSecure ( HttpCookie o,
BaBool  flag 
)

Inform the browser whether the cookie should be sent only using a secure protocol such as HTTPS – i.e.

using SSL.

Parameters
flagtrue adds Secure; false removes it. Default false.
oRequired live cookie.

◆ HttpCookie_setValue()

BA_API int HttpCookie_setValue ( HttpCookie o,
const char *  newValue 
)

Assigns a new value to a cookie after the cookie is created.

Returns 0 on success or E_MALLOC on allocation failure, preserving the old value on failure. NULL clears the value.

Parameters
newValueCookie value as a NUL-terminated string, or NULL to clear.
oRequired live cookie.

◆ HttpDir() [1/2]

HttpDir::HttpDir ( )

Constructor for creating a root dir, a root dir has no name.

◆ HttpDir() [2/2]

HttpDir::HttpDir ( const char *  name,
S8  priority = 0 
)

Constructor for creating a sub-directory.

Parameters
namethe name of the directory. The pointer "name" must always be a valid pointer since the constructor does not duplicate the string, but only stores the pointer value. Note the name cannot be volatile.
priorityThe priority is used when you have duplicate directory names. Zero is the default priority and a higher value gives higher priority. Two directory branches with the same name, but with different pages will never conflict. You only have a conflict if you have two pages with the same name, one page in each directory branch. Range: min <= priority <=max, where min=-14 and max=14. NULL or an empty name creates an anonymous directory. Initialization allocates no name storage. The ordinary constructor installs the default service callback; replacing it must preserve cleanup handling.

◆ HttpDir_authenticateAndAuthorize()

BA_API int HttpDir_authenticateAndAuthorize ( HttpDir o,
HttpCommand cmd,
const char *  path 
)

Authenticate and authorize the user.

This method provides a simple mechanism for authenticating and authorizing a user. The method takes care of the response message if the user is not authenticated and authorized – i.e., you should not send a response message if this method returns false. See the DiskDir implementation for an example of how to use this method.

Parameters
cmdThe parameter passed into the HttpDir service callback method.
pathThe relative path (from the URL) at the current position in the virtual file system.
Returns
true if:
  • Both authenticator and authorizer are NULL.
  • This is an include or forward request, or NO_HTTP_SESSION is configured.
  • The user is authenticated and the realm argument is NULL.
  • The user is authenticated and authorized.
Parameters
oRequired initialized HttpDir instance.

◆ HttpDir_constructor()

BA_API void HttpDir_constructor ( HttpDir o,
const char *  name,
S8  priority 
)

Constructor for creating a sub-directory.

Parameters
namethe name of the directory. The pointer "name" must always be a valid pointer since the constructor does not duplicate the string, but only stores the pointer value. Note the name cannot be volatile.
priorityThe priority is used when you have duplicate directory names. Zero is the default priority and a higher value gives higher priority. Two directory branches with the same name, but with different pages will never conflict. You only have a conflict if you have two pages with the same name, one page in each directory branch. Range: min <= priority <=max, where min=-14 and max=14. NULL or an empty name creates an anonymous directory. Initialization allocates no name storage. The ordinary constructor installs the default service callback; replacing it must preserve cleanup handling.
oRequired storage to initialize.

◆ HttpDir_createOrGet()

BA_API HttpDir * HttpDir_createOrGet ( HttpDir o,
const char *  name 
)

Returns a sub-directory with the given name.

The directory will be created if not found.

HttpDir* mySubDir3 = myDir->createOrGet("sub1/sub2/sub3");
Parameters
nameNUL-terminated slash-separated path. NULL/empty returns this directory; a leading slash is skipped, not resolved from the root.
Returns
Borrowed existing/new directory, or NULL on allocation failure. Newly created nodes copy their path components and are owned by the directory tree. Partial intermediate nodes can remain on failure.
Parameters
oRequired initialized HttpDir instance.

◆ HttpDir_destructor()

BA_API void HttpDir_destructor ( HttpDir o)

Unlink this directory and notify all child pages/directories through their service callbacks with NULL request arguments.

Release owned directory metadata, but not this object's allocation or borrowed name. Derived callbacks must implement their own allocation cleanup.

Parameters
oRequired initialized object; its allocation remains caller-owned.

◆ HttpDir_findDir()

BA_API HttpDir * HttpDir_findDir ( HttpDir iter,
const char *  name,
unsigned int  nameLen 
)

Searches for a sub-directory in this directory node.

Parameters
itera pointer to a reference in the directory list.
namethe name of the directory to search for.
nameLenthe length of name.
Returns
the directory or NULL if not found.

Typical usage:

HttpDir* dir = dir->findDir(dir->getFirstDir(), "dirName",
strlen("dirName"));

◆ HttpDir_findPage()

BA_API HttpPage * HttpDir_findPage ( HttpDir o,
HttpPage iter,
const char *  name 
)

Searches for a page in this directory node.

Parameters
itera pointer to a reference in the page list.
namethe name of the page to search for.
Returns
the page or NULL if not found.

Typical usage:

HttpPage* page = dir->getPage("pageName"); // Also handles an empty directory.

iter must be a valid page-list node, not NULL. Prefer getPage(name) when searching from the start, since getFirstPage() returns NULL for an empty list. name is a required case-sensitive NUL-terminated string.

Parameters
oRequired initialized HttpDir instance.

◆ HttpDir_getDir()

BA_API HttpDir * HttpDir_getDir ( HttpDir o,
const char *  name 
)

Returns the first directory with the name given or NULL if not found.

Parameters
nameRequired NUL-terminated exact, case-sensitive child name. Result is borrowed.
oRequired initialized HttpDir instance.

◆ HttpDir_getPage()

BA_API HttpPage * HttpDir_getPage ( HttpDir o,
const char *  name 
)

Returns the page with the name given or NULL if not found.

Parameters
nameRequired NUL-terminated exact, case-sensitive page name. Result is borrowed.
oRequired initialized HttpDir instance.

◆ HttpDir_insertDir()

BA_API int HttpDir_insertDir ( HttpDir o,
HttpDir dir 
)

Insert a sub-directory.

Parameters
dirthe directory to insert. dir must be initialized, with no parent and no sibling linkage.
Returns
0 on success, E_ALREADY_INSERTED if next is non-NULL. Parent ownership is also a precondition; it is only asserted, not a return check. The directory is linked by descending priority; its name is borrowed.
Parameters
oRequired initialized HttpDir instance.

◆ HttpDir_insertPage()

BA_API int HttpDir_insertPage ( HttpDir o,
HttpPage page 
)

Insert a page in the directory.

Parameters
pagethe page to insert. page is required, initialized, and unlinked; its name remains borrowed.
Returns
0 on success, -1 when already linked. Cleanup later calls the page service callback with NULL request/response, not C++ delete.
Parameters
oRequired initialized HttpDir instance.

◆ HttpDir_makeAbsPath()

BA_API char * HttpDir_makeAbsPath ( HttpDir o,
const char *  relPath,
int  relPathLen 
)

Makes an absolute path based on where the HttpDir instance is installed in the virtual file system and the provided relative path.

This method is not fast. You should consider using method getRootPath and cache the root path. You can calculate the abs path from adding root path + relative path.

absPath = installPath + relPath.

Parameters
relPathThe relative path argument added to installPath. This path may include '..' i.e. makeAbsPath("..",2) returns the absolute path to the parent directory.

Memory is allocated by using baMalloc. The caller must release the memory by using baFree.

Parameters
relPathLenlength of relPath.
See also
getRootPath relPathLen must be a nonnegative byte count matching readable input.
Returns
Caller-owned NUL-terminated path, or NULL on allocation failure.
Parameters
oRequired initialized HttpDir instance.

◆ HttpDir_p403()

BA_API void HttpDir_p403 ( HttpDir o,
const char *  p403 
)

Set a 403 denied request handler.

The directory forwards the request to the page if an authorizer is installed and the user is denied access by the authorizer. The default for a directory is to send a basic 403 message if a 403 denied request handler is not installed.

Parameters
p403is the path to a page that can be accessed by response:forward. HttpDir makes a copy of the path provided and releases the path if/when the destructor is called. p403 must be a NUL-terminated path. Allocation failure is not returned; the old path is discarded before the new copy is attempted.
oRequired initialized HttpDir instance.

◆ HttpDir_setService()

BA_API HttpDir_Service HttpDir_setService ( HttpDir o,
HttpDir_Service  s 
)

Replace the original service function in HttpDir with your own.

Returns
the original service function.
Parameters
sRequired callback for an active directory, including handling cmd == NULL cleanup notifications. It must remain callable for its lifetime.
oRequired initialized HttpDir instance.

◆ HttpDir_unlink()

BA_API int HttpDir_unlink ( HttpDir o)

Unlinks/removes the directory from the parent directory.

Returns 0 when unlinked, -1 if it had no parent. Does not destroy/free it.

Parameters
oRequired initialized HttpDir instance.

◆ HttpPage()

HttpPage::HttpPage ( HttpPage_Service  service,
const char *  name 
)

The HttpPage constructor.

Parameters
servicea pointer to a HttpPage_Service function.
nameThe page name, for example "index.html". The pointer "name" must always be a valid pointer since the constructor does not duplicate the string, but only stores the pointer value. Note the name cannot be volatile.

◆ HttpPage_constructor()

void BA_API HttpPage_constructor ( HttpPage o,
HttpPage_Service  service,
const char *  name 
)

The HttpPage constructor.

Parameters
servicea pointer to a HttpPage_Service function.
nameThe page name, for example "index.html". The pointer "name" must always be a valid pointer since the constructor does not duplicate the string, but only stores the pointer value. Note the name cannot be volatile.
oRequired storage to initialize.

◆ HttpPage_destructor()

BA_API void HttpPage_destructor ( HttpPage o)

The HttpPage destructor unlinks the page from the parent directory.

Parameters
oRequired initialized object; its allocation remains caller-owned.

◆ HttpPage_unlink()

BA_API int HttpPage_unlink ( HttpPage o)

Unlinks/removes the page from the parent directory.

Parameters
oRequired initialized HttpPage instance.

◆ HttpParameterIterator() [1/2]

HttpParameterIterator::HttpParameterIterator ( HttpParameter param)

This HttpParameterIterator constructor takes a HttpParameter object as argument.

c name: HttpParameterIterator_constructor2

◆ HttpParameterIterator() [2/2]

HttpParameterIterator::HttpParameterIterator ( HttpRequest req)

This HttpParameterIterator constructor takes a HttpRequest object as argument.

◆ HttpParameterIterator_constructor()

BA_API int HttpParameterIterator_constructor ( HttpParameterIterator o,
struct HttpRequest req 
)

Initialize an iterator and select its first element.

Parameters
oRequired iterator storage.
reqRequired live request; borrowed through iteration.
Returns
Number of parameters, zero for an empty collection. The C++ constructor does not return this count. Names/values remain owned by the source; no iterator destructor is needed.

◆ HttpParameterIterator_constructor2()

BA_API int HttpParameterIterator_constructor2 ( HttpParameterIterator o,
HttpParameter param 
)

Initialize an iterator and select its first element.

Parameters
oRequired iterator storage.
paramRequired cloned parameter container; borrowed through iteration.
Returns
Number of parameters, zero for an empty collection. The C++ constructor does not return this count. Names/values remain owned by the source; no iterator destructor is needed.

◆ HttpRequest_checkMethods()

BA_API int HttpRequest_checkMethods ( HttpRequest o,
struct HttpResponse resp,
U32  methods,
BaBool  addDefault 
)

Checks the HTTP method type and sends a response message if condition met.

RFC 2616 specifies that each resource in a web-server can have its own set of allowed HTTP methods.

The checkMethod method checks if the requested HTTP method is one of the allowed HTTP methods as specified in the argument list to checkMethod. The function returns 0 if the condition is met; otherwise, status code is set to 405 and a nonzero value is returned.

The method checkMethod also checks if the requested HTTP method is OPTIONS. If the requested HTTP method is OPTIONS, a nonzero value is returned.

A response message is automatically sent to the client when method checkMethod returns a nonzero number; thus, the service function should not send a response message.

This method is typically used by HttpDir and HttpPage objects prior to sending a response message. For example, a service function that only accepts GET requests would do the following:

HttpMethod_Options and HttpMethod_Head should not be added to the argument list since the two HTTP methods are added automatically if 'addDefault' is TRUE. It is assumed that a resource always can accept HEAD and OPTIONS. The OPTIONS request is handled automatically by checkMethod, and HEAD is automatically handled by the HttpResponse write methods; thus, the two methods are transparent to users.

A CSP page should not use the checkMethod method as the auto generated CSP code automatically sets the HttpMethod_Get, HttpMethod_Post, HttpMethod_Head and HttpMethod_Options.

Se RFC2616 section 9.2 for more information.

Parameters
respThe response object.
methodsThe methods added. Separate multiple methods by using character |.
addDefaultset to true if you would like to add OPTIONS and HEAD.
See also
HttpRequest::getMethodType
Parameters
oRequired live request.

◆ HttpRequest_checkTime()

BA_API BaBool HttpRequest_checkTime ( HttpRequest o,
struct HttpResponse resp,
BaTime  time 
)

Parses and checks if the "If-Modified-Since" time is equal or greater than "time".

Prepares a "304 Not modified" response and returns true if the condition is true; otherwise, false is returned.

! You cannot write to the output stream if this function returns true.

Parameters
respthe response object is used if sending a 304 response.
timeis the GMT time.
Returns
TRUE if the cached time condition matches and response setup was attempted; FALSE otherwise. This is not a network delivery result. time is Unix time in seconds; call before committing the response.
Parameters
oRequired live request.

◆ HttpRequest_getCookie()

BA_API HttpCookie * HttpRequest_getCookie ( HttpRequest o,
const char *  name 
)

Returns the requested cookie or NULL if no cookie matches the name.

Parameters
namethe name of the cookie.
oRequired live request.

◆ HttpRequest_getHeaders()

BA_API HttpHeader * HttpRequest_getHeaders ( HttpRequest o,
int *  len 
)

Return an HTTP header iterator that can iterate and fetch all the HTTP headers.

CSP page Example:

int len;
HttpHeader* hIter = request->getHeaders(&len);
for(int i = 0 ; i < len ; i++, hIter++)
{
response->printf("%s = %s\n",
hIter->name(request),
hIter->value(request));
}
Parameters
lenRequired output pointer receiving the number of entries.
Returns
Borrowed array of len entries; use each with this same request. The array and its name/value strings expire with the request.
Parameters
oRequired live request.

◆ HttpRequest_getHeaderValue()

BA_API const char * HttpRequest_getHeaderValue ( HttpRequest o,
const char *  name 
)

Returns the value of the specified request header.

If the request did not include a header of the specified name, this method returns null. The header name is case insensitive. You can use this method with any request header.

Parameters
namea string specifying the header name.
See also
HttpRequest::getStdHeaders HttpStdHeaders
Parameters
oRequired live request.

◆ HttpRequest_getParameter()

BA_API const char * HttpRequest_getParameter ( HttpRequest o,
const char *  paramName 
)

Returns the value of a request parameter as a const char* or null if the parameter does not exist.

Request parameters is extra information sent with the request that is contained in the query string or posted form data.

If you use this method with a multivalued parameter, the value returned is equal to the first value in a HttpParameterIterator.

Parameters
paramNameRequired NUL-terminated, case-sensitive name. Returned values are borrowed for the request lifetime.
See also
HttpParameterIterator HttpParameter
Parameters
oRequired live request.

◆ HttpRequest_getRequestURI()

BA_API const char * HttpRequest_getRequestURI ( HttpRequest o)

Returns the pathname.

The pathname will be "/myDir/index.html" if the URL is "http://myServer.net/myDir/index.html"

Parameters
oRequired live request.

◆ HttpRequest_getRequestURL()

BA_API const char * HttpRequest_getRequestURL ( HttpRequest o,
BaBool  forceHttps 
)

Reconstructs the URL the client used to make the request.

The returned URL contains a protocol, server name, port number, and server path, but it does not include query string parameters.

Parameters
forceHttpsmakes the function return a URL that starts with HTTPS if forceHttps is set to true. The default is to return a URL that starts with HTTP for a non-secure connection and HTTPS for a secure connection.
See also
HttpResponse::forceHttps
Returns
Borrowed URL or NULL on allocation failure. Valid until another request/redirect URL encoding call or request completion. Host normally comes from the request Host header; without it the implementation uses the peer address. Do not treat this as the server's configured URL.
Parameters
oRequired live request.

◆ HttpRequest_getSession()

BA_API struct HttpSession * HttpRequest_getSession ( HttpRequest o,
BaBool  create 
)

Returns the current HttpSession associated with this request, or if there is no current session and create is true, returns a new session.

If create is false and the request has no valid HttpSession, this method returns NULL.

To make sure the session is properly maintained, you must call this method before the response is committed.

Parameters
createTRUE to create a new session for this request if necessary; FALSE to return NULL if there is no current session.
Returns
the HttpSession associated with this request or null if there is no session and create is false, creation fails, the response is already committed, or the current session has termination pending. The pointer is borrowed; hold a session reference if retaining it beyond this request. See HttpSession::incrRefCntr.

Typical C++ usage:

MyPage::service(HttpRequest* request, HttpResponse* response)
{
HttpSession* session = request->getSession(true);
if(!session) return; // Allocation, limit, or committed response.
ShoppingCart* sc = (ShoppingCart*)session->getAttribute("Cart");
if ( ! sc )
{// User has no shopping cart, create one.
sc = new ShoppingCart();
session->setAttribute("Cart", sc);
}
}
Parameters
oRequired live request.

◆ HttpRequest_getVersion()

BA_API const char * HttpRequest_getVersion ( HttpRequest o)

Returns the HTTP version as a string, normally "1.1".

Parameters
oRequired live request.

◆ HttpRequest_wsUpgrade()

BA_API int HttpRequest_wsUpgrade ( HttpRequest o)

Validate and send an HTTP/1.1 WebSocket version-13 handshake.

Requires GET, Host, Upgrade/Connection tokens, one version field, and one base64 key encoding a 16-byte nonce. Application routing, authentication and Origin policy remain the caller's responsibility.

Returns
0 after sending 101; -1 if no WebSocket indication is present (no response sent); -2 if the response cannot be reset; -3 on output failure; -4 after attempting a 400 rejection, or 426 with the supported version for an otherwise valid unsupported-version request. Errors do not transfer connection ownership. Callers must not send a second response for -4. Ordinary HTTP can still be taken over as a raw connection when -1 is returned.
Parameters
oRequired live request.

◆ HttpResponse_containsHeader()

BA_API const char * HttpResponse_containsHeader ( HttpResponse o,
const char *  name 
)

Searches the internal response header database for a header with the specified name.

Returns the value of the {name, value} pair if the header is found or NULL if not found. The response header values are set with method HttpResponse::setHeader. This method is typically used by servlets either included by another servlet or when a servlet forwards the request to another servlet. See methods HttpResponse::forward and HttpResponse::include for more information.

Parameters
oRequired live response.
nameRequired NUL-terminated header name; comparison is case-insensitive.

◆ HttpResponse_createCookie()

BA_API HttpCookie * HttpResponse_createCookie ( struct HttpResponse o,
const char *  name 
)

Create a cookie.

Parameters
namethe name of the cookie. Returns an existing cookie with the same name, or a new cookie. Returns NULL if the cookie or its name cannot be allocated.
oRequired live response.

◆ HttpResponse_encodeRedirectURL()

BA_API const char * HttpResponse_encodeRedirectURL ( HttpResponse o,
const char *  pathName 
)

Encodes the specified URL into an absolute URL, or if encoding is not needed, returns the URL unchanged.

Parameters
pathNamethe absolute or relative URL to be encoded
Returns
the encoded absolute URL. The buffer returned by encodeRedirectURL is valid until end of client request or until encodeRedirectURL is called again.
See also
HttpResponse::sendRedirect
Parameters
oRequired live response.

◆ HttpResponse_encodeUrl()

BA_API const char * HttpResponse_encodeUrl ( HttpResponse o,
const char *  path 
)

Encodes an absolute or relative URL, or if encoding is not needed, returns the URL unchanged.

This method escapes all symbols that cannot be in a URL. The method differs from encodeRedirectURL in that it only escapes non-URL compatible symbols.

Parameters
oRequired live response.
pathRequired NUL-terminated URL path.
Returns
Borrowed encoded string or NULL on allocation/encoding failure; valid until the next encodeUrl call or request completion.

◆ HttpResponse_flush()

BA_API int HttpResponse_flush ( HttpResponse o)

Forces any content in the buffer to be written to the client.

A call to this method automatically commits the response, meaning the status code and headers will be written.

Returns
0 on success or the writer/transport error. Buffered output may already have been partly sent on failure; no byte count is returned.
Parameters
oRequired live response.

◆ HttpResponse_fmtHeader()

BA_API char * HttpResponse_fmtHeader ( HttpResponse o,
const char *  name,
int  valueLen,
BaBool  replace 
)

Pre-allocate memory for a {name, value} pair in the response header database.

Sometimes setting a header value with setHeader involves unnecessary copying or allocation of memory. The fmtHeader method makes it possible to pre-allocate a memory area in the internal {name, value} pair database in the response object. The function, if successful, returns a pointer to a memory area for the value in a {name, value} pair. You can then use, for example, sprintf to format this memory area.

You must use extreme caution when using this function. Writing more data to the pointer returned than requested, will corrupt the internal data structures in the database.

Example:
Setting the extended foobar header as per RFC 3092

const char foo[] = {"foo"};
const char bar[] = {"bar"};
int len = strlen(bar);
char* ptr = resp->fmtHeader(foo, len+1);
if(ptr)
strcpy(ptr, bar);
Parameters
namethe name of the header to set.
valueLenthe length of the memory area returned by fmtHeader.
replacethe parameter if already set.
Returns
Borrowed writable value storage, or NULL for invalid name/length, include context, committed response, or allocation failure. Write a NUL-terminated value before any response operation that uses headers. Returned storage may be invalidated by later header changes/reset.
Parameters
oRequired live response.

◆ HttpResponse_getWriter()

BA_API BufPrint * HttpResponse_getWriter ( HttpResponse o)

Returns a BufPrint object that can send any type of data to the client.

The BufPrint object is also used implicitly when using method HttpResponse::printf or HttpResponse::write.

Returns
Borrowed active writer, valid during the request. This initializes output framing but does not expose a framing-initialization error.
Parameters
oRequired live response.

◆ HttpResponse_printf()

BA_API int HttpResponse_printf ( HttpResponse o,
const char *  fmt,
  ... 
)

printf is used for sending formatted data to the client.

Parameters
fmtSee BufPrint::printf
Returns
BufPrint status, normally 0 on success and negative on output failure, not the number of characters. Output can be partial.
Parameters
oRequired live response.

◆ HttpResponse_redirect()

BA_API int HttpResponse_redirect ( HttpResponse o,
const char *  path 
)

Internally redirects the request to another resource.

Redirect should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method returns a non-zero value.

Parameters
pathis the path to the resource to execute. The path is assumed to be an absolute path value on the server if the string starts with "/". The path is otherwise assumed to be a relative path.

This method is similar to method forward. Unlike forward, redirect does not bypass required authentication or authorization.

Returns
Zero on success. Returns a non-zero value if the response is committed.
See also
forward
Parameters
oRequired live response.

◆ HttpResponse_redirect2TLS()

BA_API int HttpResponse_redirect2TLS ( HttpResponse o)

Prepares an HTTPS redirect (301) for a non-secure connection.

A Host with an explicit port selects a 403 error response instead. Bracketed IPv6 hosts without an explicit port are accepted. Call before committing the response. An already-secure connection returns 0 without changing the response.

Returns
0 if the connection is secure and nothing is prepared. Returns 1 when preparing the 301 or 403 response succeeds. Returns < 0 if the command fails. Success does not establish that the client received the response.
See also
HttpRequest::getRequestURL
HttpResponse::sendRedirect
Parameters
oRequired live response.

◆ HttpResponse_removeResponseBuf()

BA_API int HttpResponse_removeResponseBuf ( HttpResponse o)

Remove buffer set by using setResponseBuf.

See also
setResponseBuf
Returns
0 after restoring the default writer and resetting headers, or -1 when already committed or no custom writer is active. Custom buffered data is not flushed by this operation.
Parameters
oRequired live response.

◆ HttpResponse_resetBuffer()

BA_API int HttpResponse_resetBuffer ( HttpResponse o)

Clears the content of the underlying buffer in the response without clearing headers or status code.

If the response has been committed, this method returns a non-zero value.

Parameters
oRequired live response.

◆ HttpResponse_resetHeaders()

BA_API int HttpResponse_resetHeaders ( HttpResponse o)

Removes all HTTP headers.

This method returns a non-zero value if the response has been committed.

Parameters
oRequired live response.

◆ HttpResponse_send()

BA_API int HttpResponse_send ( HttpResponse o,
const void *  data,
int  len 
)

Used when sending raw data to the client.

This function is typically used when sending binary data to the client.

Parameters
dataRequired readable bytes, borrowed for the call.
lenNonnegative byte count. Set response framing first; this raw path does not add chunk framing or pass through a custom writer. Do not mix with buffered body output.
Returns
0 on success, E_MIXING_WRITE_SEND when buffered data remains, or a header/connection error. HEAD counts bytes without sending a body.
Parameters
oRequired live response.

◆ HttpResponse_sendBufAsError()

BA_API int HttpResponse_sendBufAsError ( HttpResponse o,
int  eCode 
)

Sends the data formatted into the HttpResponse buffer as an error message to the client.

The mime type is set to 'text/html'.

Parameters
eCodeThe HTTP error code.
oRequired live response.

◆ HttpResponse_sendBufAsTxtError()

BA_API int HttpResponse_sendBufAsTxtError ( HttpResponse o,
int  eCode 
)

Sends the data formatted into the HttpResponse buffer as an error message to the client.

The mime type is set to 'text/plain'.

Parameters
eCodeThe HTTP error code.
oRequired live response.

◆ HttpResponse_sendRedirect()

BA_API int HttpResponse_sendRedirect ( HttpResponse o,
const char *  url 
)

Sends a temporary redirect (302) response to the client using the specified redirect location URL.

The method is internally using HttpResponse::encodeRedirectURL if the URL does not start with http[s]:.

Parameters
urlabsolute or relative URL.
Returns
zero on success or a negative value if the method fails. Typical C++ usage:
response->sendRedirect("start.html");
response->sendRedirect("https://127.0.0.1:9357/intro/start.html");
See also
HttpResponse::encodeRedirectURL
HttpResponse::encodeRedirectURLWithParam
HttpRequest::getRequestURI
Parameters
oRequired live response.

◆ HttpResponse_setContentLength()

BA_API int HttpResponse_setContentLength ( HttpResponse o,
BaFileSize  len 
)

Sets the "Content-Length" parameter value.

If the header has already been set, the new value overwrites the previous one. The HttpResponse::containsHeader method can be used to test for the presence of a header before setting its value.

Parameters
lenNonnegative body byte count. The caller must send exactly this amount; this call sets framing, not a body-size enforcement limit.
Returns
0 on success, E_IS_COMMITTED or allocation error on failure.
Parameters
oRequired live response.

◆ HttpResponse_setContentType()

BA_API int HttpResponse_setContentType ( HttpResponse o,
const char *  type 
)

Sets the "Content-Type" parameter value.

If the header has already been set, the new value overwrites the previous one. The HttpResponse::containsHeader method can be used to test for the presence of a header before setting its value.

Parameters
typeNUL-terminated media type, copied; NULL or empty clears it.
Returns
0 on success, E_IS_COMMITTED or allocation error on failure.
Parameters
oRequired live response.

◆ HttpResponse_setDateHeader()

BA_API int HttpResponse_setDateHeader ( HttpResponse o,
const char *  name,
BaTime  t 
)

Set a copied date header; call before response commitment.

Parameters
oRequired live response.
nameRequired NUL-terminated header name.
tUnix time in seconds, formatted as an HTTP date.
Returns
0 on success, or E_MALLOC on allocation failure. This C path does not reject a committed response, but changing stored headers is then too late.

◆ HttpResponse_setDefaultHeaders()

BA_API int HttpResponse_setDefaultHeaders ( HttpResponse o)

Sets the most common header values in servlet and CSP files.

Sets content type to "text/html" and sets the header "Cache-Control", "No-Cache".

This method is automatically inserted by the CSP/JSSP compiler.

Parameters
oRequired live response.

◆ HttpResponse_setHeader()

BA_API int HttpResponse_setHeader ( HttpResponse o,
const char *  name,
const char *  value,
BaBool  replace 
)

Sets a HTTP response header with the given name and value.

If the header has already been set, the new value overwrites the previous one. The HttpResponse::containsHeader method can be used to test for the presence of a header before setting its value.

setStatus should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method returns a non-zero value.

Parameters
namethe name of the header to set.
valuethe header value. Set to NULL if you want to erase any previous value, if any. An empty string also erases the header. Removing Content-Length preserves buffered body data, removes Transfer-Encoding, and immediately restores automatic framing. The default writer enables chunking for keep-alive responses other than HEAD. Custom writers retain responsibility for their output. Restoring chunking can return an allocation error; do not continue sending the response after this failure.
replaceset to false if you do not want to overwrite any previous value, if any.
oRequired live response.

◆ HttpResponse_setMaxAge()

BA_API int HttpResponse_setMaxAge ( HttpResponse response,
BaTime  seconds 
)

Sets header "Cache-Control: max-age=seconds".

Can, for example, be used by CSP code to overide the default headers inserted by the CSP compiler. See HttpResponse::setDefaultHeaders for more information.

Parameters
secondsNonnegative cache lifetime in seconds, representable as U32.
Returns
0 on success (also for an include no-op), E_IS_COMMITTED or E_MALLOC on failure.
Parameters
responseRequired live response.

◆ HttpResponse_setResponseBuf()

BA_API int HttpResponse_setResponseBuf ( HttpResponse o,
BufPrint buf,
BaBool  useDefBuffer 
)

This is an advanced function that makes it possible to redirect the output, which is normally sent to the client, to another buffer.

The function must be called before any data is emitted.

Method setDefaultHeaders is used internally by the Lua bindings for method response:setresponse

See also
removeResponseBuf
Parameters
bufthe server emits response data to this buffer. The parameter buf and bufSize in struct BufPrint must be initialized if useDefBuffer is set to false.
useDefBufferThe parameter buf and bufSize in struct BufPrint is set to the internal web-server buffer if this variable is set to true. buf is borrowed until restored or request completion. Its flush callback must be initialized. No ownership of the BufPrint or its storage transfers.
Returns
0 on success, E_IS_COMMITTED when output/buffer state prevents installation. Passing the already active custom buffer restores the default writer in the implementation's restore path.
Parameters
oRequired live response.

◆ HttpResponse_write()

BA_API int HttpResponse_write ( HttpResponse o,
const void *  data,
int  len,
int  useBuffering 
)

Used for sending pre-formatted data to the client.

Parameters
datapointer to data.
lensize of data.
useBufferingset this to true if the internal HttpResponse object should buffer the data before sending it to the client. The buffer will be automatically flushed when full.
See also
BufPrint::write len is a byte count; negative uses strlen and therefore requires text. Data is borrowed only during the call. A custom writer is always used regardless of useBuffering.
Returns
0 on success, nonzero on initialization/output failure. Partial output is possible, but no partial byte count is provided.
Parameters
oRequired live response.

◆ HttpServer()

HttpServer::HttpServer ( SoDisp dispatcher,
HttpServerConfig cfg = 0 
)

Create a Web Server object.

Parameters
dispatcherThe socket dispatcher object. The SoDisp object is platform specific.
cfgis an optional parameter, which you use to override the default web-server configurations. dispatcher is required and borrowed for the server lifetime. cfg is read during construction and its noOfHttpCommands field is decremented to zero; reinitialize it before reuse. NULL selects defaults. Allocation or platform-type failures invoke the fatal handler; no status is returned.

◆ HttpServer_constructor()

BA_API void HttpServer_constructor ( HttpServer ,
SoDisp ,
HttpServerConfig  
)

Initialize a server in caller-provided storage (first argument), using a required borrowed dispatcher (second argument) and optional configuration (third argument).

See HttpServer::HttpServer for configuration mutation and fatal-error behavior. No return value.

◆ HttpServer_destructor()

BA_API void HttpServer_destructor ( HttpServer o)

Stop using the server before destruction.

Terminates owned commands, connections, sessions, and installed directory trees. Directory/page cleanup callbacks run. The borrowed dispatcher remains caller-owned; stop worker pools and retain callback dependencies through cleanup.

Parameters
oRequired initialized object; its allocation remains caller-owned.

◆ HttpServer_getSession()

BA_API HttpSession * HttpServer_getSession ( HttpServer o,
U32  id 
)

Returns the HttpSession associated with id or NULL if not found.

See HttpSession::getId for more information.

It can be potentially dangerous to use this method in a multithread enabled web-server. See the explanation in the HttpSession for more information.

See also
HttpSession::incrRefCntr
Parameters
oRequired initialized HttpServer instance.
idSession identifier returned by HttpSession_getId; lookup does not acquire an extra session reference.

◆ HttpServer_getStatusCode()

BA_API const char * HttpServer_getStatusCode ( int  code)

Return a short description for common HTTP error codes.

Parameters
codeHTTP status integer recognized by the implementation.
Returns
Static string including the numeric code and reason phrase; an unrecognized code returns "??? Server Error". Do not free.

◆ HttpServer_insertCSP()

BA_API int HttpServer_insertCSP ( HttpServer o,
CspInit  cspInit,
const char *  virtualDirRootPath,
struct CspReader reader 
)

Insert and initialize a CSP Virtual Directory.

A CSP Virtual Directory structure is generated by CspCompile and CspLink .

Parameters
cspInitis the function generated by CspLink. The default name is httpInitGeneratedCode, but this can be changed with the CspLink –init flag.
readeris a reader such as FileCspReader or a reader generated by the bin2c , if you embed the data file into the executable.
virtualDirRootPathis the root path of the CSP pages.

Example:

extern "C" void //See HttpLink for more info.
httpInitGeneratedCode(HttpDir* parent, CspReader* reader);
void insertCspIntoRootDir(HttpServer* server, CspReader* reader)
{
server->insertCSP(httpInitGeneratedCode, "/", reader);
}
int insertCSP(CspInit cspInit, const char *virtualDirRootPath, struct CspReader *reader)
Insert and initialize a CSP Virtual Directory.
Definition: HttpServer.h:3704
Abstract interface class for reading the "dat" file generated by HttpLink.
Definition: CspRunTm.h:126
The Web Server.
Definition: HttpServer.h:3393

It is sometimes more convenient to populate a CSP Virtual File System directly on a HttpResRdr node.

Example:

DiskIo io;
HttpResRdr myRootDir(&io, NULL);
FileCspReader reader("/home/webserver/CspPages.dat");
httpInitGeneratedCode(&myRootDir, &reader);
The DiskIo class makes it possible for the web server to work with resources on a hard drive.
Definition: BaDiskIo.h:91
Example code that shows you how to write a CspReader driver object.
Definition: FileCspReader.h:26
The HTTP resource reader searches and presents IoIntf resources to HTTP clients requesting such infor...
Definition: HttpResRdr.h:170

cspInit is required. reader and its backing data must outlive installed pages. The initializer is called synchronously with the created parent.

Returns
0 after calling cspInit, or E_MALLOC creating the parent path. This return does not report errors internal to the void initializer.
Parameters
oRequired initialized HttpServer instance.

◆ HttpServer_insertDir()

BA_API int HttpServer_insertDir ( HttpServer o,
const char *  virtualDirRootPath,
HttpDir dir 
)

Insert a directory node into the virtual file system.

Here are some examples if you insert a directory node with a page, say "start.html":

virtualDirRootPath HttpDir name URL
"D1/D2""D3"http://{IP address}/D1/D2/D3/start.html
"D1""D3"http://{IP address}/D1/D3/start.html
NULL or "/""D3"http://{IP address}/D3/start.html
NULL or "/"NULLhttp://{IP address}/start.html (*)
"D1"NULLInvalid
      (*) Identical to HttpServer::insertRootDir

      \param virtualDirRootPath start path in the virtual file system.
      \param dir the directory node to insert.
  dir must be initialized and unlinked. Missing intermediate directories
      are allocated; they can remain if a later allocation fails.
      @return 0 on success, E_ALREADY_INSERTED for linked input detected by
      HttpDir_insertDir, or E_MALLOC when the parent path cannot be created.
Parameters
oRequired initialized HttpServer instance.
virtualDirRootPathNUL-terminated parent path; NULL/empty/slash selects root.
dirRequired initialized, unlinked directory.

◆ HttpServer_insertRootDir()

BA_API int HttpServer_insertRootDir ( HttpServer o,
HttpDir dir 
)

Insert a root directory node.

A root directory node is a special directory in which the name of the directory is ignored. The directory name can be NULL. For example, if you insert a directory node with a page, say "start.html", the URL to this page will be: http://{IP address}/start.html.

Parameters
dirthe directory node to install. A root directory node does not need a name. See HttpDir::HttpDir for more information.
Returns
0 on success or E_ALREADY_INSERTED for detected next linkage. The caller must supply an unlinked directory (including no parent). Its service callback will receive a cleanup notification when the installed tree is destroyed.
Parameters
oRequired initialized HttpServer instance.

◆ HttpServer_set404Page()

BA_API void HttpServer_set404Page ( HttpServer o,
const char *  page404 
)

Set a more user friendly 404 page.

Have you ever noticed that some sites give you a nice looking page when you mistype a URL, as opposed to the default 404 File Not Found error? This function lets you set your own user friendly 404 page.

Parameters
page404is a URL to your user friendly 404 page. Example "/myUserFriendly404Page.html" The path is borrowed, not copied. Keep the NUL-terminated string alive until replaced or server destruction; NULL selects the default handler.
oRequired initialized HttpServer instance.

◆ HttpServerConfig()

HttpServerConfig::HttpServerConfig ( )

The constructor sets up the default parameters.

Use one or several of the methods in this class after you have created this object to change one or more of the configuration parameters.

◆ HttpServerConfig_constructor()

BA_API void HttpServerConfig_constructor ( HttpServerConfig o)

The constructor sets up the default parameters.

Use one or several of the methods in this class after you have created this object to change one or more of the configuration parameters.

Parameters
oRequired configuration storage to initialize.

◆ HttpServerConfig_setCommit()

BA_API int HttpServerConfig_setCommit ( HttpServerConfig o,
U16  size 
)

Set the size of the HTTP response commit buffer.

This buffer is used by the web-server when formatting the HTTP response header data. This buffer should be bigger than the HTTP response header buffer for best performance. A smaller buffer makes the web-server call socket send every time the buffer is full. This might deteriorate the performance of the web-server. See your TCP/IP stack for internal TCP buffer and the Nagle algorithm.

See HttpResponse::committed for more information.

Default value is 512. The minimum value cannot be smaller than 128.

Parameters
sizeCommit-buffer bytes, 128..65535.
Returns
0 on success; -1 for a rejected value, leaving this setting unchanged.
Parameters
oRequired initialized HttpServerConfig instance.

◆ HttpServerConfig_setMaxSessions()

BA_API int HttpServerConfig_setMaxSessions ( HttpServerConfig o,
U16  size 
)

Maximum allowed active HttpSession objects.

The size can also be changed during runtime with method HttpSessionContainer::setMaxSessions. Default value is set equal to NoOfHttpConnections.

Parameters
sizeActive-session limit, 1..65535. Independent of connection count after this setter; the connection setter may raise it again.
Returns
0 on success; -1 for a rejected value, leaving this setting unchanged.
Parameters
oRequired initialized HttpServerConfig instance.

◆ HttpServerConfig_setNoOfHttpCommands()

BA_API int HttpServerConfig_setNoOfHttpCommands ( HttpServerConfig o,
U16  size 
)

The number of HttpCommand instances created by the web-server.

This is by default set to one. You should not change this value unless you use the HttpCmdThreadPool class.

Creating more than one instance of this class is expensive. The total memory consumption is N*M, where N is the number of HttpCommand instances and M is the sum of all buffers in an HttpCommand. M = Request buffer + ResponseHeader buffer + ResponseData buffer + Commit buffer

  • the size of HttpCommand.
    Parameters
    sizePositive command count. Keep size+3 representable as U16. Increasing it also raises the connection count to at least size+3.
    Returns
    0 on success; -1 for a rejected value, leaving this setting unchanged.
    Parameters
    oRequired initialized HttpServerConfig instance.

◆ HttpServerConfig_setNoOfHttpConnections()

BA_API int HttpServerConfig_setNoOfHttpConnections ( HttpServerConfig o,
U16  size 
)

Number of HttpConnection instances.

An HttpConnection object is the web-server's socket connection. The web-server supports HTTP1.1 persistent connections; thus, the web-server may maintain many idle client connections simultaneously. It is recommended to set the size to 3 times the number of HttpCommand objects. An HttpConnection object can also queue incoming requests if the HttpCmdThreadPool class is used.

The size of an HttpConnection object depends on build configuration, but be aware that this object can potentially hold large amounts of data if the connection is secure. A secure SSL connection may have to buffer its data stream before coding/decoding the data. See your SSL stack for more information.

Default value is 16. Minimum value is NoOfHttpCommands + 3.

See the HTTP Engine and Sockets for more information on using this function.

Parameters
sizeConnection count, at least noOfHttpCommands+3, at most 65535. Increasing it also raises maxSessions if smaller.
Returns
0 on success; -1 for a rejected value, leaving this setting unchanged.
Parameters
oRequired initialized HttpServerConfig instance.

◆ HttpServerConfig_setRequest()

BA_API int HttpServerConfig_setRequest ( HttpServerConfig o,
S16  min,
S16  max 
)

Set the size of the HTTP request buffer.

This buffer is used by the web-server when parsing an incoming HTTP request. The buffer must be big enough to contain all HTTP headers, the request path, and all HTTP parameters.

See HttpRequest::getHeaderValue for more information on HTTP headers.
See HttpRequest::getParameter and HttpParameterIterator for more information on HTTP parameters.

The buffer is used for storing HTTP headers and for storing URL encoded data from HTTP requests. The buffer is also used for storing POST data if the client sends x-www-form-urlencoded data.

Default values: min= 1024, max= 2048. Set min = max if you do not want the buffer to dynamically grow if needed. The minimum value cannot be smaller than 1024.

It is recommended to set the max size to at least 4096 bytes if the HttpCmdThreadPool is enabled. The reason for this is that the web-server is sending response data and reading pipelined data at the same time when using the thread pool. The web-server has no option but to terminate the connection if the buffer overflows. See HttpTrace::setReqBufOverflow and the Http Command Thread Pool documentation for more information.

Parameters
minInitial bytes, 1024..32767.
maxMaximum bytes, min..32767.
Returns
0 on success; -1 for a rejected value, leaving this setting unchanged.
Parameters
oRequired initialized HttpServerConfig instance.

◆ HttpServerConfig_setResponseData()

BA_API int HttpServerConfig_setResponseData ( HttpServerConfig o,
U16  size 
)

The HttpResponse object stores formatted data in the response data buffer.

You add data to this buffer when using HttpResponse::printf and HttpResponse::write. The web-server flushes the buffer automatically when full. It is sometimes convenient to have a large buffer if you implement rollback handling; i.e., you print response data, but later decide to erase the data in the buffer. See HttpResponse::resetBuffer and HttpResponse::committed for more information.

Default value is 1400. The minimum value cannot be smaller than 512.

Parameters
sizeBody-buffer bytes, 512..65535. Demo builds default to 8192.
Returns
0 on success; -1 for a rejected value, leaving this setting unchanged.
Parameters
oRequired initialized HttpServerConfig instance.

◆ HttpServerConfig_setResponseHeader()

BA_API int HttpServerConfig_setResponseHeader ( HttpServerConfig o,
U16  min,
U16  max 
)

Set the size of the HTTP response header buffer.

This buffer is used by the web-server for storing the HTTP response headers.

See HttpResponse::setHeader and HttpResponse::committed for more information.

Default values: min= 512, max= 1024. Set min = max if you do not want the buffer to dynamically grow if needed. The minimum value cannot be smaller than 512.

Parameters
minInitial bytes, 512..32767.
maxMaximum bytes, min..32767.
Returns
0 on success; -1 for a rejected value, leaving this setting unchanged.
Parameters
oRequired initialized HttpServerConfig instance.

◆ HttpSession_decrRefCntr()

BA_API void HttpSession_decrRefCntr ( HttpSession o)

Decrements the session reference counter.

This method is used together with method incrRefCntr. See HttpSession for more information. A matching outstanding reference is required. This can immediately destroy a termination-pending session; do not access it afterward.

Parameters
oRequired live session.

◆ HttpSession_fmtSessionId()

BA_API int HttpSession_fmtSessionId ( HttpSession o,
U8 buf,
size_t  bufSize 
)

Format the full session token as hexadecimal text.

Parameters
oRequired live session.
bufRequired writable output.
bufSizeCapacity in bytes, at least 25.
Returns
24 (text length) on success, -1 without writing when too small.

◆ HttpSession_getAttribute()

BA_API HttpSessionAttribute * HttpSession_getAttribute ( HttpSession o,
const char *  name 
)

Returns the object bound with the specified name in this session, or null if no object is bound under the name.

Parameters
nameRequired case-sensitive NUL-terminated name.
Returns
Borrowed attribute or NULL. Its termination callback controls lifetime; do not free it while attached.
Parameters
oRequired live session.

◆ HttpSession_getCreationTime()

BA_API BaTime HttpSession_getCreationTime ( HttpSession o)

Returns the time when this session was created, measured in seconds since midnight January 1, 1970 GMT.

Parameters
oRequired live session.

◆ HttpSession_getLastAccessedTime()

BA_API BaTime HttpSession_getLastAccessedTime ( HttpSession o)

Returns the last time the client sent a request associated with this session, as the number of seconds since midnight January 1, 1970 GMT, and marked by the time the container received the request.

Parameters
oRequired live session.

◆ HttpSession_getMaxInactiveInterval()

BA_API BaTime HttpSession_getMaxInactiveInterval ( HttpSession o)

Returns the maximum time interval, in seconds, that the session container will keep this session open between client accesses.

Parameters
oRequired live session.

◆ HttpSession_getServer()

BA_API struct HttpServer * HttpSession_getServer ( HttpSession o)

Get the server object.

Parameters
oRequired live session.

◆ HttpSession_removeAttribute()

BA_API int HttpSession_removeAttribute ( HttpSession o,
const char *  name 
)

Removes the object bound with the specified name from this session.

Parameters
nameRequired case-sensitive NUL-terminated name.
Returns
0 when found and its termination callback ran, -1 when absent. This is a destroying removal, not a transfer to the caller.
Parameters
oRequired live session.

◆ HttpSession_setAttribute()

BA_API int HttpSession_setAttribute ( HttpSession o,
HttpSessionAttribute value 
)

Binds an object to this session, using the name specified.

Parameters
valueRequired initialized, unattached attribute with a non-NULL name. On success the session arranges its termination callback.
Returns
0 on success; -1 for a duplicate name, -2 for non-NULL next linkage, -3 for a NULL name. This does not replace an existing attribute.
Parameters
oRequired live session.

◆ HttpSession_setMaxInactiveInterval()

BA_API void HttpSession_setMaxInactiveInterval ( HttpSession o,
BaTime  interval 
)

Specifies the time, in seconds, between client requests before the session container will invalidate this session.

Parameters
intervalInactivity threshold in seconds. Zero is an immediate threshold, not an unlimited lifetime; expiry is checked periodically.
oRequired live session.

◆ HttpSession_terminate()

BA_API void HttpSession_terminate ( HttpSession o)

Unbinds any objects bound to this session object, runs the HttpSession destructor, and frees the memory for this object.

The web-server controls this object, and the object may linger for some time before the object is terminated and released. See HttpSession for more information.

When the web-server destroys the object, all attached HttpSessionAttributes are terminated by calling method HttpSessionAttribute_Destructor for each attached HttpSessionAttribute.

See also
AuthenticatedUser::logout
Parameters
oRequired live session.

◆ HttpSessionAttribute()

HttpSessionAttribute::HttpSessionAttribute ( const char *  name,
HttpSessionAttribute_Destructor  terminate 
)

Create a session attribute.

Parameters
namea unique attribute name.
terminatea pointer to a function called when the session object times out.

◆ HttpSessionAttribute_constructor()

BA_API void HttpSessionAttribute_constructor ( HttpSessionAttribute o,
const char *  name,
HttpSessionAttribute_Destructor  d 
)

Initialize a session attribute.

Parameters
oRequired caller-owned storage.
nameRequired NUL-terminated name, copied. If allocation fails, name is NULL and later setAttribute returns -3; construction has no return status.
dCleanup callback, or NULL. The framework frees the copied name after invoking d; d is responsible for payload/allocation cleanup.

◆ HttpSessionAttribute_destructor()

BA_API void HttpSessionAttribute_destructor ( HttpSessionAttribute o)

Terminate an unattached attribute and release its copied name.

Parameters
oRequired initialized attribute. Its callback may free this storage. Normally invoked by session cleanup; use removeAttribute for attached data.

◆ include()

int HttpResponse::include ( const char *  path)

Includes the content of a resource (servlet, CSP page, HTML file) in the response.

In essence, this method enables programmatic server-side includes. See the introduction to Request Delegation for more information.

The HttpResponse object's path elements and parameters remain unchanged from the caller's values. The included servlet cannot change the response status code. Ordinary setHeader calls can change headers before commitment; fmtHeader rejects include contexts. Do not assume included code cannot modify headers.

Parameters
pathis the path to the resource to include. The path is assumed to be an absolute path value on the server if the string starts with "/". The path is otherwise assumed to be a relative path.

◆ incrRefCntr()

void HttpSession::incrRefCntr ( )

Increments the session reference counter.

This method is used together with method decrRefCntr. See HttpSession for more information.

◆ initial()

bool HttpResponse::initial ( ) const

Returns true if this is the initial page.

Returns
(!isForward() && !isInclude())

◆ initStatic()

void HttpServer::initStatic ( void  )
static

The only purpose with this function is to clean all static variables that are in the BSS section; i.e., you do not need to call this function if you properly clear your static uninitialized variables.

◆ insertCSP()

int HttpServer::insertCSP ( CspInit  cspInit,
const char *  virtualDirRootPath,
struct CspReader reader 
)

Insert and initialize a CSP Virtual Directory.

A CSP Virtual Directory structure is generated by CspCompile and CspLink .

Parameters
cspInitis the function generated by CspLink. The default name is httpInitGeneratedCode, but this can be changed with the CspLink –init flag.
readeris a reader such as FileCspReader or a reader generated by the bin2c , if you embed the data file into the executable.
virtualDirRootPathis the root path of the CSP pages.

Example:

extern "C" void //See HttpLink for more info.
httpInitGeneratedCode(HttpDir* parent, CspReader* reader);
void insertCspIntoRootDir(HttpServer* server, CspReader* reader)
{
server->insertCSP(httpInitGeneratedCode, "/", reader);
}

It is sometimes more convenient to populate a CSP Virtual File System directly on a HttpResRdr node.

Example:

DiskIo io;
HttpResRdr myRootDir(&io, NULL);
FileCspReader reader("/home/webserver/CspPages.dat");
httpInitGeneratedCode(&myRootDir, &reader);

cspInit is required. reader and its backing data must outlive installed pages. The initializer is called synchronously with the created parent.

Returns
0 after calling cspInit, or E_MALLOC creating the parent path. This return does not report errors internal to the void initializer.

◆ insertDir() [1/2]

int HttpServer::insertDir ( const char *  virtualDirRootPath,
HttpDir dir 
)

Insert a directory node into the virtual file system.

Here are some examples if you insert a directory node with a page, say "start.html":

virtualDirRootPath HttpDir name URL
"D1/D2""D3"http://{IP address}/D1/D2/D3/start.html
"D1""D3"http://{IP address}/D1/D3/start.html
NULL or "/""D3"http://{IP address}/D3/start.html
NULL or "/"NULLhttp://{IP address}/start.html (*)
"D1"NULLInvalid
      (*) Identical to HttpServer::insertRootDir

      \param virtualDirRootPath start path in the virtual file system.
      \param dir the directory node to insert.
  dir must be initialized and unlinked. Missing intermediate directories
      are allocated; they can remain if a later allocation fails.
      @return 0 on success, E_ALREADY_INSERTED for linked input detected by
      HttpDir_insertDir, or E_MALLOC when the parent path cannot be created.

◆ insertDir() [2/2]

int HttpDir::insertDir ( HttpDir dir)

Insert a sub-directory.

Parameters
dirthe directory to insert. dir must be initialized, with no parent and no sibling linkage.
Returns
0 on success, E_ALREADY_INSERTED if next is non-NULL. Parent ownership is also a precondition; it is only asserted, not a return check. The directory is linked by descending priority; its name is borrowed.

◆ insertPage()

int HttpDir::insertPage ( HttpPage page)

Insert a page in the directory.

Parameters
pagethe page to insert. page is required, initialized, and unlinked; its name remains borrowed.
Returns
0 on success, -1 when already linked. Cleanup later calls the page service callback with NULL request/response, not C++ delete.

◆ insertRootDir()

int HttpServer::insertRootDir ( HttpDir dir)

Insert a root directory node.

A root directory node is a special directory in which the name of the directory is ignored. The directory name can be NULL. For example, if you insert a directory node with a page, say "start.html", the URL to this page will be: http://{IP address}/start.html.

Parameters
dirthe directory node to install. A root directory node does not need a name. See HttpDir::HttpDir for more information.
Returns
0 on success or E_ALREADY_INSERTED for detected next linkage. The caller must supply an unlinked directory (including no parent). Its service callback will receive a cleanup notification when the installed tree is destroyed.

◆ isForward()

bool HttpResponse::isForward ( ) const

Returns true if this is a forward request from another servlet or CSP file.

◆ isInclude()

bool HttpResponse::isInclude ( ) const

Returns true if this is an include from another servlet or CSP file.

◆ isLinked() [1/2]

bool HttpPage::isLinked ( )

Returns true if this page node is installed into a parent directory.

◆ isLinked() [2/2]

bool HttpDir::isLinked ( )

Returns true if this directory node is installed into a parent directory.

◆ makeAbsPath()

char * HttpDir::makeAbsPath ( const char *  relPath,
int  relPathLen 
)

Makes an absolute path based on where the HttpDir instance is installed in the virtual file system and the provided relative path.

This method is not fast. You should consider using method getRootPath and cache the root path. You can calculate the abs path from adding root path + relative path.

absPath = installPath + relPath.

Parameters
relPathThe relative path argument added to installPath. This path may include '..' i.e. makeAbsPath("..",2) returns the absolute path to the parent directory.

Memory is allocated by using baMalloc. The caller must release the memory by using baFree.

Parameters
relPathLenlength of relPath.
See also
getRootPath relPathLen must be a nonnegative byte count matching readable input.
Returns
Caller-owned NUL-terminated path, or NULL on allocation failure.

◆ nextElement()

void HttpParameterIterator::nextElement ( )

Advance to the next element.

At the end, name and value become NULL. Call hasMoreElements() before accessing the current entry.

◆ p403()

void HttpDir::p403 ( const char *  p403)

Set a 403 denied request handler.

The directory forwards the request to the page if an authorizer is installed and the user is denied access by the authorizer. The default for a directory is to send a basic 403 message if a 403 denied request handler is not installed.

Parameters
p403is the path to a page that can be accessed by response:forward. HttpDir makes a copy of the path provided and releases the path if/when the destructor is called. p403 must be a NUL-terminated path. Allocation failure is not returned; the old path is discarded before the new copy is attempted.

◆ printf()

int HttpResponse::printf ( const char *  fmt,
  ... 
)

printf is used for sending formatted data to the client.

Parameters
fmtSee BufPrint::printf
Returns
BufPrint status, normally 0 on success and negative on output failure, not the number of characters. Output can be partial.

◆ redirect()

int HttpResponse::redirect ( const char *  path)

Internally redirects the request to another resource.

Redirect should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method returns a non-zero value.

Parameters
pathis the path to the resource to execute. The path is assumed to be an absolute path value on the server if the string starts with "/". The path is otherwise assumed to be a relative path.

This method is similar to method forward. Unlike forward, redirect does not bypass required authentication or authorization.

Returns
Zero on success. Returns a non-zero value if the response is committed.
See also
forward

◆ redirect2TLS()

int HttpResponse::redirect2TLS ( )

Prepares an HTTPS redirect (301) for a non-secure connection.

A Host with an explicit port selects a 403 error response instead. Bracketed IPv6 hosts without an explicit port are accepted. Call before committing the response. An already-secure connection returns 0 without changing the response.

Returns
0 if the connection is secure and nothing is prepared. Returns 1 when preparing the 301 or 403 response succeeds. Returns < 0 if the command fails. Success does not establish that the client received the response.
See also
HttpRequest::getRequestURL
HttpResponse::sendRedirect

◆ removeAttribute()

int HttpSession::removeAttribute ( const char *  name)

Removes the object bound with the specified name from this session.

Parameters
nameRequired case-sensitive NUL-terminated name.
Returns
0 when found and its termination callback ran, -1 when absent. This is a destroying removal, not a transfer to the caller.

◆ removeResponseBuf()

int HttpResponse::removeResponseBuf ( )

Remove buffer set by using setResponseBuf.

See also
setResponseBuf
Returns
0 after restoring the default writer and resetting headers, or -1 when already committed or no custom writer is active. Custom buffered data is not flushed by this operation.

◆ resetBuffer()

int HttpResponse::resetBuffer ( )

Clears the content of the underlying buffer in the response without clearing headers or status code.

If the response has been committed, this method returns a non-zero value.

◆ resetHeaders()

int HttpResponse::resetHeaders ( )

Removes all HTTP headers.

This method returns a non-zero value if the response has been committed.

◆ send()

int HttpResponse::send ( const void *  data,
int  len 
)

Used when sending raw data to the client.

This function is typically used when sending binary data to the client.

Parameters
dataRequired readable bytes, borrowed for the call.
lenNonnegative byte count. Set response framing first; this raw path does not add chunk framing or pass through a custom writer. Do not mix with buffered body output.
Returns
0 on success, E_MIXING_WRITE_SEND when buffered data remains, or a header/connection error. HEAD counts bytes without sending a body.

◆ sendBufAsError()

int HttpResponse::sendBufAsError ( int  eCode)

Sends the data formatted into the HttpResponse buffer as an error message to the client.

The mime type is set to 'text/html'.

Parameters
eCodeThe HTTP error code.

◆ sendBufAsTxtError()

int HttpResponse::sendBufAsTxtError ( int  eCode)

Sends the data formatted into the HttpResponse buffer as an error message to the client.

The mime type is set to 'text/plain'.

Parameters
eCodeThe HTTP error code.

◆ sendError() [1/2]

int HttpResponse::sendError ( int  eCode)

Sends an error response as a simple HTML page to the client using the specified status code.

If the response has been committed, this method returns a non-zero value.

C function name:
HttpResponse_sendError1
Parameters
eCodethe error code.

◆ sendError() [2/2]

int HttpResponse::sendError ( int  eCode,
const char *  msg 
)

Sends an error response as a simple HTML page to the client using the specified status code.

If the response has been committed, this method returns a non-zero value.

C function name:
HttpResponse_sendError2
Parameters
eCodeThe HTTP error code.
msgThe error message.

◆ sendRedirect()

int HttpResponse::sendRedirect ( const char *  url)

Sends a temporary redirect (302) response to the client using the specified redirect location URL.

The method is internally using HttpResponse::encodeRedirectURL if the URL does not start with http[s]:.

Parameters
urlabsolute or relative URL.
Returns
zero on success or a negative value if the method fails. Typical C++ usage:
response->sendRedirect("start.html");
response->sendRedirect("https://127.0.0.1:9357/intro/start.html");
See also
HttpResponse::encodeRedirectURL
HttpResponse::encodeRedirectURLWithParam
HttpRequest::getRequestURI

◆ service()

void HttpPage::service ( HttpRequest request,
HttpResponse response 
)

The virtual service function (C callback function) is normally run by the parent directory when delegating the request to the page service method.

◆ set404Page()

void HttpServer::set404Page ( const char *  page404)

Set a more user friendly 404 page.

Have you ever noticed that some sites give you a nice looking page when you mistype a URL, as opposed to the default 404 File Not Found error? This function lets you set your own user friendly 404 page.

Parameters
page404is a URL to your user friendly 404 page. Example "/myUserFriendly404Page.html" The path is borrowed, not copied. Keep the NUL-terminated string alive until replaced or server destruction; NULL selects the default handler.

◆ setAttribute()

int HttpSession::setAttribute ( HttpSessionAttribute value)

Binds an object to this session, using the name specified.

Parameters
valueRequired initialized, unattached attribute with a non-NULL name. On success the session arranges its termination callback.
Returns
0 on success; -1 for a duplicate name, -2 for non-NULL next linkage, -3 for a NULL name. This does not replace an existing attribute.

◆ setAuthenticator()

void HttpDir::setAuthenticator ( struct AuthenticatorIntf authenticator,
struct AuthorizerIntf authorizer = 0 
)

Set the optional authenticator and optional AuthorizerIntf.

Parameters
authenticatoris one of the authenticator implementations.
authorizerthe authorizer. Both pointers are borrowed, may be NULL, and must remain alive while installed. An authorizer alone still requires an authenticated user; NULL authenticator does not bypass an installed authorizer.

◆ setComment()

int HttpCookie::setComment ( const char *  purpose)

Specifies a comment that describes a cookie's purpose.

Returns 0 on success or E_MALLOC on allocation failure, preserving the old comment on failure. NULL clears the comment.

Parameters
purposePurpose text as a NUL-terminated string, or NULL to clear.

◆ setCommit()

int HttpServerConfig::setCommit ( U16  size)

Set the size of the HTTP response commit buffer.

This buffer is used by the web-server when formatting the HTTP response header data. This buffer should be bigger than the HTTP response header buffer for best performance. A smaller buffer makes the web-server call socket send every time the buffer is full. This might deteriorate the performance of the web-server. See your TCP/IP stack for internal TCP buffer and the Nagle algorithm.

See HttpResponse::committed for more information.

Default value is 512. The minimum value cannot be smaller than 128.

Parameters
sizeCommit-buffer bytes, 128..65535.
Returns
0 on success; -1 for a rejected value, leaving this setting unchanged.

◆ setContentLength()

int HttpResponse::setContentLength ( BaFileSize  len)

Sets the "Content-Length" parameter value.

If the header has already been set, the new value overwrites the previous one. The HttpResponse::containsHeader method can be used to test for the presence of a header before setting its value.

Parameters
lenNonnegative body byte count. The caller must send exactly this amount; this call sets framing, not a body-size enforcement limit.
Returns
0 on success, E_IS_COMMITTED or allocation error on failure.

◆ setContentType()

int HttpResponse::setContentType ( const char *  type)

Sets the "Content-Type" parameter value.

If the header has already been set, the new value overwrites the previous one. The HttpResponse::containsHeader method can be used to test for the presence of a header before setting its value.

Parameters
typeNUL-terminated media type, copied; NULL or empty clears it.
Returns
0 on success, E_IS_COMMITTED or allocation error on failure.

◆ setDateHeader()

int HttpResponse::setDateHeader ( const char *  name,
BaTime  time 
)

Sets a response header with the given name and date-value.

The date is specified in terms of seconds. If the header has already been set, the new value overwrites the previous one. The HttpResponse::containsHeader method can be used to test for the presence of a header before setting its value.

Parameters
namethe name of the header to set.
timethe assigned time value in number of seconds elapsed since midnight (00:00:00), January 1, 1970.

◆ setDefaultHeaders()

int HttpResponse::setDefaultHeaders ( )

Sets the most common header values in servlet and CSP files.

Sets content type to "text/html" and sets the header "Cache-Control", "No-Cache".

This method is automatically inserted by the CSP/JSSP compiler.

◆ setDomain()

int HttpCookie::setDomain ( const char *  pattern)

Specifies the domain within which this cookie should be presented.

Returns 0 on success or E_MALLOC on allocation failure, preserving the old domain on failure. NULL clears the domain.

Parameters
patternDomain attribute as a NUL-terminated string, or NULL to clear.

◆ setErrHnd()

void HttpServer::setErrHnd ( UserDefinedErrHandler  e)
static

You can set your own user defined error handler for the web-server.

The web-server calls this function if any non-recoverable error is detected. The error codes are defined in BaErrorCodes.h. See the example directory for an example on how to write your own error handler.

Parameters
eis the name of your error handler function. The prototype for this function should be: void myError(BaFatalErrorCodes ecode1, unsigned int ecode2, const char* file, int line);

◆ setHeader()

int HttpResponse::setHeader ( const char *  name,
const char *  value,
bool  replace = true 
)

Sets a HTTP response header with the given name and value.

If the header has already been set, the new value overwrites the previous one. The HttpResponse::containsHeader method can be used to test for the presence of a header before setting its value.

setStatus should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method returns a non-zero value.

Parameters
namethe name of the header to set.
valuethe header value. Set to NULL if you want to erase any previous value, if any. An empty string also erases the header. Removing Content-Length preserves buffered body data, removes Transfer-Encoding, and immediately restores automatic framing. The default writer enables chunking for keep-alive responses other than HEAD. Custom writers retain responsibility for their output. Restoring chunking can return an allocation error; do not continue sending the response after this failure.
replaceset to false if you do not want to overwrite any previous value, if any.

◆ setHttpOnly()

void HttpCookie::setHttpOnly ( bool  flag)

Marks or unmarks this Cookie as HttpOnly.

If isHttpOnly is set to true, this cookie is marked as HttpOnly, by adding the HttpOnly attribute to it.

HttpOnly cookies are not supposed to be exposed to client-side scripting code, and may therefore help mitigate certain kinds of cross-site scripting attacks.

Parameters
flagtrue adds HttpOnly; false removes it. Default false.

◆ setMaxAge() [1/2]

void HttpCookie::setMaxAge ( BaTime  expiry)

Sets the maximum age of the cookie in seconds.

The cookie is by default not stored persistently and will be deleted when the web browser exits. This function turns the cookie into a persistent cookie, which the browser keeps in its cookie container. A persistent cookie can later be deleted with function HttpCookie::deleteCookie.

Parameters
expiryLifetime in seconds; a positive value makes the cookie persistent. Zero explicitly requests deletion. A freshly created cookie's default zero instead means no lifetime attribute was set.

◆ setMaxAge() [2/2]

int HttpResponse::setMaxAge ( BaTime  seconds)

Sets header "Cache-Control: max-age=seconds".

Can, for example, be used by CSP code to overide the default headers inserted by the CSP compiler. See HttpResponse::setDefaultHeaders for more information.

Parameters
secondsNonnegative cache lifetime in seconds, representable as U32.
Returns
0 on success (also for an include no-op), E_IS_COMMITTED or E_MALLOC on failure.

◆ setMaxInactiveInterval()

void HttpSession::setMaxInactiveInterval ( BaTime  interval)

Specifies the time, in seconds, between client requests before the session container will invalidate this session.

Parameters
intervalInactivity threshold in seconds. Zero is an immediate threshold, not an unlimited lifetime; expiry is checked periodically.

◆ setMaxSessions() [1/2]

void HttpSessionContainer::setMaxSessions ( int  max)

Set the maximum number of session objects.

See HttpServerConfig::setMaxSessions for default value. See The authentication classes for security considerations.

◆ setMaxSessions() [2/2]

int HttpServerConfig::setMaxSessions ( U16  size)

Maximum allowed active HttpSession objects.

The size can also be changed during runtime with method HttpSessionContainer::setMaxSessions. Default value is set equal to NoOfHttpConnections.

Parameters
sizeActive-session limit, 1..65535. Independent of connection count after this setter; the connection setter may raise it again.
Returns
0 on success; -1 for a rejected value, leaving this setting unchanged.

◆ setNoOfHttpCommands()

int HttpServerConfig::setNoOfHttpCommands ( U16  size)

The number of HttpCommand instances created by the web-server.

This is by default set to one. You should not change this value unless you use the HttpCmdThreadPool class.

Creating more than one instance of this class is expensive. The total memory consumption is N*M, where N is the number of HttpCommand instances and M is the sum of all buffers in an HttpCommand. M = Request buffer + ResponseHeader buffer + ResponseData buffer + Commit buffer

  • the size of HttpCommand.
    Parameters
    sizePositive command count. Keep size+3 representable as U16. Increasing it also raises the connection count to at least size+3.
    Returns
    0 on success; -1 for a rejected value, leaving this setting unchanged.

◆ setNoOfHttpConnections()

int HttpServerConfig::setNoOfHttpConnections ( U16  size)

Number of HttpConnection instances.

An HttpConnection object is the web-server's socket connection. The web-server supports HTTP1.1 persistent connections; thus, the web-server may maintain many idle client connections simultaneously. It is recommended to set the size to 3 times the number of HttpCommand objects. An HttpConnection object can also queue incoming requests if the HttpCmdThreadPool class is used.

The size of an HttpConnection object depends on build configuration, but be aware that this object can potentially hold large amounts of data if the connection is secure. A secure SSL connection may have to buffer its data stream before coding/decoding the data. See your SSL stack for more information.

Default value is 16. Minimum value is NoOfHttpCommands + 3.

See the HTTP Engine and Sockets for more information on using this function.

Parameters
sizeConnection count, at least noOfHttpCommands+3, at most 65535. Increasing it also raises maxSessions if smaller.
Returns
0 on success; -1 for a rejected value, leaving this setting unchanged.

◆ setPath()

int HttpCookie::setPath ( const char *  uri)

Set the cookie path.

Returns 0 on success or E_MALLOC on allocation failure, preserving the old path on failure. NULL clears the path.

Parameters
uriPath attribute as a NUL-terminated string, or NULL to clear.

◆ setRequest()

int HttpServerConfig::setRequest ( S16  min,
S16  max 
)

Set the size of the HTTP request buffer.

This buffer is used by the web-server when parsing an incoming HTTP request. The buffer must be big enough to contain all HTTP headers, the request path, and all HTTP parameters.

See HttpRequest::getHeaderValue for more information on HTTP headers.
See HttpRequest::getParameter and HttpParameterIterator for more information on HTTP parameters.

The buffer is used for storing HTTP headers and for storing URL encoded data from HTTP requests. The buffer is also used for storing POST data if the client sends x-www-form-urlencoded data.

Default values: min= 1024, max= 2048. Set min = max if you do not want the buffer to dynamically grow if needed. The minimum value cannot be smaller than 1024.

It is recommended to set the max size to at least 4096 bytes if the HttpCmdThreadPool is enabled. The reason for this is that the web-server is sending response data and reading pipelined data at the same time when using the thread pool. The web-server has no option but to terminate the connection if the buffer overflows. See HttpTrace::setReqBufOverflow and the Http Command Thread Pool documentation for more information.

Parameters
minInitial bytes, 1024..32767.
maxMaximum bytes, min..32767.
Returns
0 on success; -1 for a rejected value, leaving this setting unchanged.

◆ setResponseBuf()

int HttpResponse::setResponseBuf ( BufPrint buf,
bool  useDefBuffer = true 
)

This is an advanced function that makes it possible to redirect the output, which is normally sent to the client, to another buffer.

The function must be called before any data is emitted.

Method setDefaultHeaders is used internally by the Lua bindings for method response:setresponse

See also
removeResponseBuf
Parameters
bufthe server emits response data to this buffer. The parameter buf and bufSize in struct BufPrint must be initialized if useDefBuffer is set to false.
useDefBufferThe parameter buf and bufSize in struct BufPrint is set to the internal web-server buffer if this variable is set to true. buf is borrowed until restored or request completion. Its flush callback must be initialized. No ownership of the BufPrint or its storage transfers.
Returns
0 on success, E_IS_COMMITTED when output/buffer state prevents installation. Passing the already active custom buffer restores the default writer in the implementation's restore path.

◆ setResponseData()

int HttpServerConfig::setResponseData ( U16  size)

The HttpResponse object stores formatted data in the response data buffer.

You add data to this buffer when using HttpResponse::printf and HttpResponse::write. The web-server flushes the buffer automatically when full. It is sometimes convenient to have a large buffer if you implement rollback handling; i.e., you print response data, but later decide to erase the data in the buffer. See HttpResponse::resetBuffer and HttpResponse::committed for more information.

Default value is 1400. The minimum value cannot be smaller than 512.

Parameters
sizeBody-buffer bytes, 512..65535. Demo builds default to 8192.
Returns
0 on success; -1 for a rejected value, leaving this setting unchanged.

◆ setResponseHeader()

int HttpServerConfig::setResponseHeader ( U16  min,
U16  max 
)

Set the size of the HTTP response header buffer.

This buffer is used by the web-server for storing the HTTP response headers.

See HttpResponse::setHeader and HttpResponse::committed for more information.

Default values: min= 512, max= 1024. Set min = max if you do not want the buffer to dynamically grow if needed. The minimum value cannot be smaller than 512.

Parameters
minInitial bytes, 512..32767.
maxMaximum bytes, min..32767.
Returns
0 on success; -1 for a rejected value, leaving this setting unchanged.

◆ setSecure()

void HttpCookie::setSecure ( bool  flag)

Inform the browser whether the cookie should be sent only using a secure protocol such as HTTPS – i.e.

using SSL.

Parameters
flagtrue adds Secure; false removes it. Default false.

◆ setService()

HttpDir_Service HttpDir::setService ( HttpDir_Service  s)

Replace the original service function in HttpDir with your own.

Returns
the original service function.
Parameters
sRequired callback for an active directory, including handling cmd == NULL cleanup notifications. It must remain callable for its lifetime.

◆ setStatus()

void HttpResponse::setStatus ( int  statusCode)

Sets the status code for this response.

This method is used to set the return status code when there is no error (for example, for the status code 304 Not Modified). If there is an error, the sendError method should be used instead.

setStatus should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, the C function returns E_IS_COMMITTED; this void C++ wrapper discards it.

Included resources cannot change the status.

Parameters
statusCodeThe HTTP status code

◆ setValue()

int HttpCookie::setValue ( const char *  newValue)

Assigns a new value to a cookie after the cookie is created.

Returns 0 on success or E_MALLOC on allocation failure, preserving the old value on failure. NULL clears the value.

Parameters
newValueCookie value as a NUL-terminated string, or NULL to clear.

◆ terminate()

void HttpSession::terminate ( )

Unbinds any objects bound to this session object, runs the HttpSession destructor, and frees the memory for this object.

The web-server controls this object, and the object may linger for some time before the object is terminated and released. See HttpSession for more information.

When the web-server destroys the object, all attached HttpSessionAttributes are terminated by calling method HttpSessionAttribute_Destructor for each attached HttpSessionAttribute.

See also
AuthenticatedUser::logout

◆ unlink() [1/2]

int HttpPage::unlink ( )

Unlinks/removes the page from the parent directory.

◆ unlink() [2/2]

int HttpDir::unlink ( )

Unlinks/removes the directory from the parent directory.

Returns 0 when unlinked, -1 if it had no parent. Does not destroy/free it.

◆ write() [1/2]

int HttpResponse::write ( const char *  data,
int  useBuffering = TRUE 
)

Used for sending a zero terminated string to the client.

This method is only available if you use C++.

Parameters
dataa reference to the string.
useBufferingset this to true if the internal HttpResponse object should buffer the data before sending it to the client. The buffer will be automatically flushed when full.

◆ write() [2/2]

int HttpResponse::write ( const void *  data,
int  len,
int  useBuffering = TRUE 
)

Used for sending pre-formatted data to the client.

Parameters
datapointer to data.
lensize of data.
useBufferingset this to true if the internal HttpResponse object should buffer the data before sending it to the client. The buffer will be automatically flushed when full.
See also
BufPrint::write len is a byte count; negative uses strlen and therefore requires text. Data is borrowed only during the call. A custom writer is always used regardless of useBuffering.
Returns
0 on success, nonzero on initialization/output failure. Partial output is possible, but no partial byte count is provided.

◆ wsUpgrade()

int HttpRequest::wsUpgrade ( )

Validate and send an HTTP/1.1 WebSocket version-13 handshake.

Requires GET, Host, Upgrade/Connection tokens, one version field, and one base64 key encoding a 16-byte nonce. Application routing, authentication and Origin policy remain the caller's responsibility.

Returns
0 after sending 101; -1 if no WebSocket indication is present (no response sent); -2 if the response cannot be reset; -3 on output failure; -4 after attempting a 400 rejection, or 426 with the supported version for an otherwise valid unsupported-version request. Errors do not transfer connection ownership. Callers must not send a second response for -4. Ordinary HTTP can still be taken over as a raw connection when -1 is returned.

◆ ~HttpDir()

HttpDir::~HttpDir ( )

Unlink this directory and notify all child pages/directories through their service callbacks with NULL request arguments.

Release owned directory metadata, but not this object's allocation or borrowed name. Derived callbacks must implement their own allocation cleanup.

◆ ~HttpPage()

HttpPage::~HttpPage ( )

The HttpPage destructor unlinks the page from the parent directory.

◆ ~HttpServer()

HttpServer::~HttpServer ( )

Stop using the server before destruction.

Terminates owned commands, connections, sessions, and installed directory trees. Directory/page cleanup callbacks run. The borrowed dispatcher remains caller-owned; stop worker pools and retain callback dependencies through cleanup.