Barracuda Application Server C/C++ Reference
NO
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.
 

Enumerations

enum  HttpMethod
 HTTP method types. More...
 

Functions

 HttpParameterIterator::HttpParameterIterator (HttpRequest *req)
 This HttpParameterIterator constructor takes a HttpRequest object as argument.
 
 HttpParameterIterator::HttpParameterIterator (HttpParameter *param)
 This HttpParameterIterator constructor takes a HttpParameter object as argument. More...
 
void HttpParameterIterator::nextElement ()
 Advance to the next element.
 
void HttpCookie::setComment (const char *purpose)
 Specifies a comment that describes a cookie's purpose.
 
void HttpCookie::setDomain (const char *pattern)
 Specifies the domain within which this cookie should be presented.
 
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...
 
void HttpCookie::setPath (const char *uri)
 Set the cookie path.
 
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...
 
void HttpCookie::setValue (const char *newValue)
 Assigns a new value to a cookie after the cookie is created.
 
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.
 
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".
 
SBaFileSize HttpStdHeaders::getContentLength ()
 Returns the content length if request contains a body.
 
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.
 
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.
 
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".
 
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 ()
 Activate a WebSocket handshake. More...
 
HttpHeader * HttpRequest::getHeaders (int *len)
 Return a 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.
 
HttpInDataHttpRequest::getBuffer ()
 Get the internal rec buffer.
 
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.
 
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.
 
bool HttpResponse::isInclude () const
 Returns true if this is an include from another servlet or CSP file.
 
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 ()
 Converts the URL to HTTPS and sends a redirect (301) response to the client if this is 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.
 
HttpResponseHttpCommand::getResponse ()
 Get the response object.
 
struct HttpConnectionHttpCommand::getConnection ()
 Get the current connection object that the HttpCommand instance is bound with.
 
struct HttpServerHttpCommand::getServer ()
 Get the web-server object.
 
 HttpSessionAttribute::HttpSessionAttribute (const char *name, HttpSessionAttribute_Destructor terminate)
 Create a session attribute. More...
 
HttpSessionHttpSessionAttribute::getSession ()
 Get the session object.
 
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.
 
BaTime HttpSession::getCreationTime ()
 Returns the time when this session was created, measured in seconds since midnight January 1, 1970 GMT.
 
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.
 
BaTime HttpSession::getMaxInactiveInterval ()
 Returns the maximum time interval, in seconds, that the session container will keep this session open between client accesses.
 
HttpServerHttpSession::getServer ()
 Get the server object.
 
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.
 
int HttpSession::setAttribute (HttpSessionAttribute *value)
 Binds an object to this session, using the name specified.
 
void HttpSession::setMaxInactiveInterval (BaTime interval)
 Specifies the time, in seconds, between client requests before the session container will invalidate this session.
 
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.
 
AuthenticatedUserHttpSession::getAuthenticatedUser ()
 Returns the AuthenticatedUser if user is authenticated.
 
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.
 
bool HttpPage::isLinked ()
 Returns true if this page node is installed into a parent directory.
 
int HttpPage::unlink ()
 Unlinks/removes the page from the parent directory.
 
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.
 
 HttpDir::HttpDir ()
 Constructor for creating a root dir, a root dir has no name.
 
 HttpDir::HttpDir (const char *name, S8 priority=0)
 Constructor for creating a sub-directory. 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.
 
HttpDirHttpDir::getFirstDir ()
 Returns the first sub-directory.
 
HttpDirHttpDir::getDir (const char *name)
 Returns the first directory with the name given or NULL if not found.
 
HttpPageHttpDir::getPage (const char *name)
 Returns the page with the name given or NULL if not found.
 
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::overloadService (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.
 
bool HttpDir::isLinked ()
 Returns true if this directory node is installed into a parent directory.
 
void HttpDir::setAuthenticator (struct AuthenticatorIntf *authenticator, struct AuthorizerIntf *authorizer=0)
 Set the optional authenticator and/or the 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...
 
int HttpServer::insertRootDir (HttpDir *dir)
 Insert a root directory node. More...
 
ThreadMutexHttpServer::getMutex ()
 Get the dispatcher mutex.
 
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.
 
HttpDirHttpServer::getFirstRootDir ()
 Returns the first root directory. More...
 
HttpSessionContainerHttpServer::getSessionContainer ()
 Get the HttpSessionContainer.
 
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.
 
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.
 
static const char * HttpServer::getStatusCode (int code)
 Return a short description for common HTTP error codes.
 
HttpResponseHttpRequest::getResponse ()
 Returns the HttpResponse object.
 
HttpConnectionHttpRequest::getConnection ()
 Returns the connection object associated with this request.
 
HttpRequestHttpResponse::getRequest ()
 Get the HttpRequest object.
 
HttpCommandHttpResponse::getCommand ()
 Get the HttpCommand object.
 
HttpCommandHttpRequest::getCommand ()
 Get the HttpCommand object.
 
struct HttpServerHttpConnection::getServer ()
 Fetch the HttpServer object.
 

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:680
A cookie is used for exchanging a small amount of information between a HttpPage and a web browser.
Definition: HttpServer.h:516

◆ 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.

In a true RESTful application, every resource is uniquely addressable through the resource's URL. The URL can point to physical objects such as files handled by the HttpResMgr or to virtual resources created on demand from the URL itself.

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
cmdthe request/response object

◆ 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)
{
MyPage* o = (MyPage*)page;
o->myData++;
HttpResponse_printf(response,
"<html><body>"
"Number of visits: %d"
"</body></html>",
myData);
}
MyPage_constructor(MyPage* o, const char* name)
{
HttpPage_constructor(&o->page, MyPage_service, name);
o->myData = 0;
}
An HttpPage, which is typically created by the CSP compiler, is similar to a Java servlet.
Definition: HttpServer.h:2256
The HttpServer creates an HttpRequest object when the HttpServer parses a client request.
Definition: HttpServer.h:808
This object is used when sending response messages back to the client.
Definition: HttpServer.h:1178
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.
responseA pointer to the response object created by HttpServer.

◆ 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:432

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.

◆ 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.

◆ 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);
};
MyAttribute::destructor(HttpSessionAttribute* o)
{
delete ((MyAttribute*)o); // Run destructor and free memory.
}
The interface to an HttpSession attribute.
Definition: HttpServer.h:1912

◆ 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 session object. Typically upcasted to the derived class.

◆ 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:
  • The authenticator argument is NULL.
  • The user is authenticated and the realm argument is NULL.
  • The user is authenticated and authorized.

◆ checkMethods()

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

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

RFC26216 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 OPTION and HEADER.
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".

Sends 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.

◆ 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.

◆ 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:2638
An instance of the HttpDir class, which is a collection of zero or more resources,...
Definition: HttpServer.h:2368

◆ decrRefCntr()

void HttpSession::decrRefCntr ( )

Decrements the session reference counter.

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

◆ 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 an 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:2635
HttpDir * getFirstDir()
Returns the first sub-directory.
Definition: HttpServer.h:2627

◆ 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->findPage(dir->getFirstPage(), "pageName");

◆ 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.

◆ 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 when setting a header value with setHeader involves unnecessary copying and/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 lenght of the memory area returned by fmtHeader.
replacethe parameter if already set.

◆ 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, with the exception that forward bypasses any form of required authentication and/or authentication.

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

◆ 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.

◆ 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.

◆ 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 a 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));
}

◆ 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.

◆ 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

◆ getNext()

HttpDir * HttpDir::getNext ( )

Returns the next dir in the parent list.

(next sibling)

◆ 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.

See also
HttpParameterIterator HttpParameter

◆ 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 an 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

◆ 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

◆ getSession() [1/2]

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 create is false and the request has no valid session.

Typical C++ usage:

MyPage::service(HttpRequest* request, HttpResponse* response)
{
HttpSession* session = request->getSession(true);
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:2114
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:2100
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:1140
Provides a way to identify a user across more than one page request or visit to a web site,...
Definition: HttpServer.h:1959

◆ getSession() [2/2]

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

◆ getStdHeaders()

HttpStdHeaders * HttpRequest::getStdHeaders ( )

Returns an object containing standard HTTP headers.

See also
HttpStdHeaders HttpRequest::getHeaderValue

◆ 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.

◆ HttpDir()

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.

◆ 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.

◆ HttpParameterIterator()

HttpParameterIterator::HttpParameterIterator ( HttpParameter param)

This HttpParameterIterator constructor takes a HttpParameter object as argument.

c name: HttpParameterIterator_constructor2

◆ 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.

◆ 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.

◆ 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.

◆ 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 or set headers; any attempt to make a change is ignored.

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())

◆ 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);
}
int insertCSP(CspInit cspInit, const char *virtualDirRootPath, struct CspReader *reader)
Insert and initialize a CSP Virtual Directory.
Definition: HttpServer.h:3123
Abstract interface class for reading the "dat" file generated byHttpLink.
Definition: CspRunTm.h:119
The Web Server.
Definition: HttpServer.h:2864

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:97
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:144

◆ 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.

◆ insertDir() [2/2]

int HttpDir::insertDir ( HttpDir dir)

Insert a sub-directory.

Parameters
dirthe directory to insert.

◆ insertPage()

int HttpDir::insertPage ( HttpPage page)

Insert a page in the directory.

Parameters
pagethe page to insert.

◆ 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 -1 if the directory is already installed in the virtual file system.

◆ 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

◆ overloadService()

HttpDir_Service HttpDir::overloadService ( HttpDir_Service  s)

Replace the original service function in HttpDir with your own.

Returns
the original service function.

◆ 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.

◆ printf()

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

printf is used for sending formatted data to the client.

Parameters
fmtSee BufPrint::printf

◆ 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, with the exception that forward bypasses any form of required authentication and/or authentication.

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

◆ redirect2TLS()

int HttpResponse::redirect2TLS ( )

Converts the URL to HTTPS and sends a redirect (301) response to the client if this is a non secure connection.

This function fails if the response is committed.

Returns
0 if the connection is secure and nothing is sent. Returns 1 if a 301 HTTP response is sent. Returns < 0 if the command fails.
See also
HttpRequest::getRequestURL
HttpResponse::sendRedirect

◆ removeResponseBuf()

int HttpResponse::removeResponseBuf ( )

Remove buffer set by using setResponseBuf.

See also
setResponseBuf

◆ 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.

◆ 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

◆ 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 an URL, as opposed to the default nasty 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"

◆ setAuthenticator()

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

Set the optional authenticator and/or the optional AuthorizerIntf.

Parameters
authenticatoris one of the authenticator implementations.
authorizerthe authorizer.

◆ 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 "naggle" algorithm.

See HttpResponse::committed for more information.

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

◆ 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.

◆ 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.

◆ 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.

◆ 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(BaErrorCodes 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.
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.

◆ 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.

◆ 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.

◆ 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.

◆ 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

◆ 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 one HttpConnection object is roughly 40 bytes, 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.

◆ 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.

◆ 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.

◆ 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::reset, HttpResponse::resetBuffer and HttpResponse::committed for more information.

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

◆ 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.

◆ 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.

◆ 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, this method returns a non-zero value.

Parameters
statusCodeThe HTTP status code

◆ 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

◆ 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

◆ wsUpgrade()

int HttpRequest::wsUpgrade ( )

Activate a WebSocket handshake.

The function returns 0 on successful handshake and a negative value if the client is not a WebSocket client.