MLIB
Loading...
Searching...
No Matches
mlib::http::server Class Reference

Small multi-threaded HTTP server. More...

#include <httpd.h>

Inheritance diagram for mlib::http::server:
mlib::tcpserver mlib::thread mlib::syncbase

Public Member Functions

 server (unsigned short port=0, unsigned int maxconn=0)
 Constructor.
 
 ~server ()
 Destructor.
 
void add_ohdr (const std::string &hdr, const std::string &value)
 Add or modify a server response header.
 
void remove_ohdr (const std::string &hdr)
 Remove a server response header.
 
void add_handler (const std::string &uri, uri_handler func, void *info=0)
 Add or modify an URI handler function.
 
void add_post_handler (const std::string &uri, uri_handler func, void *info=0)
 Add or modify an POST handler function.
 
bool add_user (const char *realm, const char *username, const char *pwd)
 Add a new user to a relm or modifies password for an existing user.
 
bool remove_user (const char *realm, const char *username)
 
void add_realm (const char *realm, const char *uri)
 Add a new access realm.
 
template<typename T>
void add_var (const std::string &name, const T *addr, const char *fmt=nullptr)
 
template<typename T>
std::enable_if_t< std::is_floating_point_v< T > > add_var (const std::string &name, const T *addr, const char *fmt=nullptr, double multiplier=1.)
 
const std::string get_var (const std::string &name)
 Return the current string representation of a variable.
 
void aquire_varlock ()
 Acquire lock on server's variables.
 
void release_varlock ()
 Release lock on server's variables.
 
bool try_varlock ()
 Try to acquire lock on server's variables.
 
void name (const char *nam)
 Change server name.
 
void docroot (const std::string &path)
 Set server root path.
 
const std::filesystem::path & docroot () const
 Return current file origin.
 
void add_alias (const std::string &uri, const std::string &path)
 Maps a local file path to an URI resource path.
 
void default_uri (const std::string &name)
 
const std::string & default_uri ()
 
bool is_protected (const std::string &uri, std::string &realm)
 Find the realm with longest matching path that covers an URI.
 
bool authenticate (const std::string &realm, const std::string &user, const std::string &pwd)
 Verify user credentials for a realm.
 
- Public Member Functions inherited from mlib::tcpserver
 tcpserver (unsigned short port, const std::string &name=std::string(), unsigned int max_conn=0)
 Opens the socket and initializes the connections table.
 
 ~tcpserver ()
 Terminate any connection that still exists.
 
socksocket ()
 Provides access to server listening socket.
 
void foreach (conn_iter_func f, void *param)
 Invoke an iteration function for each active connection.
 
threadget_connection_thread (const sock &conn_sock)
 Return the thread servicing a connection.
 
void close_connection (const sock &conn_sock)
 Closes a connection.
 
void terminate ()
 Terminate the tcp server.
 
size_t numconn () const
 Return number of active connections.
 
unsigned int timeout () const
 Return max interval to wait for an incoming connection (in milliseconds)
 
void timeout (DWORD msec)
 Set maximum timeout interval (in milliseconds)
 
void maxconn (unsigned int new_max)
 Set maximum number of connections accepted.
 
unsigned int maxconn () const
 Return maximum number of connections accepted.
 
void set_connfunc (std::function< int(const sock &)> f)
 Set function object that becomes the body of the thread serving a new connection.
 
- Public Member Functions inherited from mlib::thread
 thread (std::function< unsigned int()> func)
 Make a thread with the given function body.
 
virtual ~thread ()
 Destructor.
 
virtual void start ()
 Begin execution of a newly created thread.
 
void fork ()
 Another name for start () function.
 
void join ()
 Another name for wait () function.
 
DWORD wait (DWORD time_limit=INFINITE)
 Wait for thread to finish execution.
 
DWORD wait_alertable (DWORD time_limit=INFINITE)
 Wait for thread to finish or an APC, or IO completion routine to occur.
 
DWORD wait_msg (DWORD time_limit=INFINITE, DWORD mask=QS_ALLINPUT)
 Wait for thread to finish or a message to be queued.
 
void rethrow_exception () const
 Rethrow an exception usually in the context of another thread.
 
DWORD id () const
 Return thread's ID.
 
UINT result () const
 Return thread's exit code.
 
bool is_running () const
 Return true if thread is running.
 
state get_state () const
 Return thread's execution status.
 
int priority () const
 Return thread's priority.
 
void priority (int pri)
 Set thread's priority.
 
virtual void name (const std::string &nam)
 Set thread's name.
 
virtual const std::string & name () const
 Return object's name.
 
- Public Member Functions inherited from mlib::syncbase
 syncbase ()
 Default constructor.
 
 syncbase (const syncbase &e)
 Copy constructor.
 
 syncbase (syncbase &&e) noexcept
 Move constructor.
 
virtual ~syncbase ()
 Destructor.
 
syncbaseoperator= (const syncbase &rhs)
 Assignment operator.
 
syncbaseoperator= (syncbase &&rhs) noexcept
 Move assignment operator.
 
int operator== (const syncbase &rhs) const
 Equality operator.
 
virtual void wait ()
 Wait for object to become signaled.
 
virtual DWORD wait (std::chrono::milliseconds limit)
 Wait a number of milliseconds for the object to become signaled.
 
 operator bool ()
 Check if object is signaled.
 
virtual bool is_signaled ()
 Try to wait on the object.
 
HANDLE handle () const
 Return OS handle of this object.
 

Static Public Member Functions

static void add_mime_type (const std::string &ext, const std::string &type, bool shtml=false)
 Add/change content of table matching MIME types to file extensions.
 
static void delete_mime_type (const std::string &ext)
 Remove a file type from the MIME type table.
 

Protected Types

enum  vtype {
  VT_UNKNOWN , VT_BOOL , VT_CHAR , VT_STRING ,
  VT_SHORT , VT_USHORT , VT_INT , VT_UINT ,
  VT_LONG , VT_ULONG , VT_FLOAT , VT_DOUBLE
}
 SSI variables type. More...
 

Protected Member Functions

int invoke_handler (connection &client)
 Invoke a user defined URI handler.
 
int invoke_post_handler (connection &client)
 Invoke a user defined handler in response to a POST or PUT request.
 
bool find_alias (const std::string &res, std::filesystem::path &path)
 Retrieve the local file path mapped to a resource.
 
const std::string & guess_mimetype (const std::filesystem::path &fn, bool &shtml)
 Guess MIME type of a file and if SSI replacement should be enabled based on file extension.
 
connectionmake_thread (sock &connection)
 Create an new mlib::http::connection object in response to a new client connection request.
 
void add_var (const std::string &name, vtype t, const void *addr, const char *fmt=nullptr, double multiplier=1.)
 Add or modify a user variable.
 
- Protected Member Functions inherited from mlib::tcpserver
bool init () override
 Binds the server socket to listening address and places it in listen mode.
 
void run () override
 Run loop.
 
virtual bool idle_action ()
 Called periodically from run loop.
 
virtual void initconn (sock &conn_sock, thread *thread)
 Initializes a connection.
 
virtual void termconn (sock &conn_sock, thread *thread)
 Finalizes a connection.
 
- Protected Member Functions inherited from mlib::thread
 thread (const std::string &name=std::string(), DWORD stack_size=0, PSECURITY_DESCRIPTOR sd=NULL, bool inherit=false)
 Protected constructor for use of thread-derived objects.
 
virtual void term ()
 Finalization function called after run.
 
- Protected Member Functions inherited from mlib::syncbase
 syncbase (const std::string &name)
 Protected constructor.
 
void set_handle (HANDLE h)
 Change object's handle. Closes the previous one.
 

Friends

class connection
 

Additional Inherited Members

- Public Types inherited from mlib::thread
enum class  state {
  ready , starting , running , ending ,
  finished
}
 Execution state of a thread. More...
 
- Protected Attributes inherited from mlib::thread
unsigned int exitcode
 exit code
 

Detailed Description

Small multi-threaded HTTP server.

This class is derived from mlib::tcpserver class and implements a basic HTTP server.

After construction, the main server thread has to be started by calling start() function. When started, the server binds to the listening socket and creates new http::connection objects for each incoming client. All the protocol is then handled by the connection (or derived) object.

A HTTP server can be integrated to an application by adding specific handlers and user variables. Handlers are user functions called in response to client requests. There are two types of handlers:

  • global handlers registered using the add_handler() function. These are called by the client connection thread immediately after validating a client request.
  • post handlers registered using the add_post_handler() function. These are called only for POST or PUT requests.

User variables can be added by calling the add_var() function. The content of those variables is then returned in response to SSI echo directives.

Member Enumeration Documentation

◆ vtype

enum mlib::http::server::vtype
protected

SSI variables type.

Enumerator
VT_UNKNOWN 

illegal

VT_BOOL 

bool*

VT_CHAR 

char*

VT_STRING 

std::string*

VT_SHORT 

short int*

VT_USHORT 

unsigned short*

VT_INT 

int*

VT_UINT 

unsigned int*

VT_LONG 

long*

VT_ULONG 

unsigned long*

VT_FLOAT 

float*

VT_DOUBLE 

double*

Constructor & Destructor Documentation

◆ server()

mlib::http::server::server ( unsigned short port = 0,
unsigned int maxconn = 0 )
explicit

Constructor.

Parameters
portlistening port
maxconnmaximum number of incoming connections. If 0 the number of connections is unlimited

If port is 0, when the server is started it will bind to an available port on local interface only.

  • document root is current folder
  • default url is HTTP_DEFAULT
  • server name is HTTP_SERVER_NAME

Member Function Documentation

◆ add_alias()

void mlib::http::server::add_alias ( const std::string & uri,
const std::string & path )

Maps a local file path to an URI resource path.

Parameters
tgt_pathURI resource path
pathmapped local file path

The mapping is always relative to server's root folder (docroot).

◆ add_handler()

void mlib::http::server::add_handler ( const std::string & uri,
uri_handler func,
void * info = 0 )

Add or modify an URI handler function.

Parameters
uriURI address
funchandler function
infohandler specific information

When a HTTP client requests the URI, the connection object that services the client connection will invoke the user-defined handler function passing the connection object and the handler specific information.

Example:

int say_hello (http::connection& client, void *)
{
client.serve_buffer ("Hello world!");
return HTTP_OK;
}
//...
http::server my_server(8080);
my_server.add_handler ("/greeting", say_hello, nullptr);
Representation of a HTTP client connection request.
int serve_buffer(const BYTE *buffer, size_t sz)
Send the content of a buffer.
Definition httpd.cpp:726
Small multi-threaded HTTP server.
Definition httpd.h:154
#define HTTP_OK
Success.
Definition httpd.h:21

In response to a request to http://localhost:8080/greeting, the server will display the greeting message.

Note
These handlers are invoked irrespective of the HTTP method (GET, POST, DELETE, etc.).

◆ add_mime_type()

void mlib::http::server::add_mime_type ( const std::string & ext,
const std::string & type,
bool shtml = false )
static

Add/change content of table matching MIME types to file extensions.

Parameters
extfilename extension
typeMIME type
shtmltrue if SSI processing should be enabled for this file type

◆ add_ohdr()

void mlib::http::server::add_ohdr ( const std::string & hdr,
const std::string & value )

Add or modify a server response header.

Parameters
hdrHeader name
valueHeader value

Server response headers are always sent as part of the HTTP answer. In addition each connection object can add it's own headers.

◆ add_post_handler()

void mlib::http::server::add_post_handler ( const std::string & uri,
uri_handler func,
void * info = 0 )

Add or modify an POST handler function.

Parameters
tgt_pathURI address
funchandler function
infohandler specific information

These handlers work just like the handlers defined using the add_handler() function, except that they are invoked only for POST or PUT requests.

◆ add_realm()

void mlib::http::server::add_realm ( const char * realm,
const char * uri )

Add a new access realm.

Realms are assigned to specific tgt_path paths and their access can be restricted to specified users.

Parameters
realmprotection realm
tgt_pathstarting path

◆ add_user()

bool mlib::http::server::add_user ( const char * realm,
const char * username,
const char * pwd )

Add a new user to a relm or modifies password for an existing user.

Parameters
realmaccess realm
usernameuser name
pwduser password
Returns
true if successful or false if realm doesn't exist

◆ add_var()

void mlib::http::server::add_var ( const std::string & name,
vtype t,
const void * addr,
const char * fmt = nullptr,
double multiplier = 1. )
protected

Add or modify a user variable.

Parameters
namevariable name (the name used in SSI construct)
addraddress of content \
fmtsprintf format string
multiplierfor numeric variables, resulting value is multiplied by this factor

User variables are accessible through SSI constructs like:

  <!--#echo var="name" -->

When the page is served the SSI construct is replaced by the current value of the named variable, eventually multiplied by multiplier factor and formatted as text using the fmt string. If format string is NULL, a format appropriate for the variable type is used

◆ authenticate()

bool mlib::http::server::authenticate ( const std::string & realm,
const std::string & user,
const std::string & pwd )

Verify user credentials for a realm.

Returns
true if user is authorized for the realm

◆ delete_mime_type()

void mlib::http::server::delete_mime_type ( const std::string & ext)
static

Remove a file type from the MIME type table.

Parameters
extfilename extension

◆ find_alias()

bool mlib::http::server::find_alias ( const std::string & res,
std::filesystem::path & path )
protected

Retrieve the local file path mapped to a resource.

Parameters
resresource path
pathlocal path
Returns
true if resource was remapped.

After processing the alias table, any part of the original resource that was not mapped is appended to the resulting path. For instance if the alias table contains an entry mapping "doc" to "documentation" and docroot is set as "c:\\local_folder\\", a resource like "/doc/project1/filename.html" will be mapped to "c:\local_folder\documentation\project1\filename.html". Note that mapping is only lexical. The function does not check if the resource exists. Remapping is "greedy". If the alias table contains mappings for "doc" and "doc/new", a resource like "/doc/new/manual.html" will use the mapping for "/doc/new"

◆ get_var()

const string mlib::http::server::get_var ( const std::string & name)

Return the current string representation of a variable.

Parameters
namevariable name

◆ guess_mimetype()

const std::string & mlib::http::server::guess_mimetype ( const std::filesystem::path & fn,
bool & shtml )
protected

Guess MIME type of a file and if SSI replacement should be enabled based on file extension.

Parameters
fnfile name
shtmlreturn true if SSI replacement should be enabled for this file type
Returns
MIME type

◆ invoke_handler()

int mlib::http::server::invoke_handler ( connection & client)
protected

Invoke a user defined URI handler.

Parameters
clientconnection thread
Returns
the result of calling the user handler or 0 if there is no handler set for the URI.

◆ invoke_post_handler()

int mlib::http::server::invoke_post_handler ( connection & client)
protected

Invoke a user defined handler in response to a POST or PUT request.

Parameters
clientconnection thread
Returns
the result of calling the user handler or 0 if there is no handler set for the URI.

◆ is_protected()

bool mlib::http::server::is_protected ( const std::string & uri,
std::string & realm )

Find the realm with longest matching path that covers an URI.

Parameters
tgt_pathURI to check
realmmatching realm
Returns
true if URI is covered by a realm

◆ make_thread()

connection * mlib::http::server::make_thread ( sock & connection)
protectedvirtual

Create an new mlib::http::connection object in response to a new client connection request.

Derived classes can override this function to return objects derived from mlib::http::connection class.

Reimplemented from mlib::tcpserver.

◆ name()

void mlib::http::server::name ( const char * nam)

Change server name.

Parameters
namnew server name string

This string is returned in the "Server" HTTP header.

◆ remove_ohdr()

void mlib::http::server::remove_ohdr ( const std::string & hdr)

Remove a server response header.

Parameters
hdrHeader name

◆ try_varlock()

bool mlib::http::server::try_varlock ( )
inline

Try to acquire lock on server's variables.

Returns
true if lock was acquired

The documentation for this class was generated from the following files: