MLIB
Loading...
Searching...
No Matches
mlib::httpd Class Reference

Small multi-threaded HTTP server. More...

#include <httpd.h>

Inheritance diagram for mlib::httpd:
mlib::tcpserver mlib::thread mlib::syncbase

Public Member Functions

 httpd (unsigned short port=0, unsigned int maxconn=0)
 Constructor.
 
 ~httpd ()
 Destructor.
 
void add_ohdr (const char *hdr, const char *value)
 Add or modify a server response header.
 
void remove_ohdr (const char *hdr)
 Remove a server response header.
 
void add_handler (const char *uri, uri_handler func, void *info=0)
 Add or modify an URI 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.
 
void add_var (const char *name, const char *fmt, void *addr, double multiplier=1.)
 Add or modify a user variable.
 
std::string get_var (const char *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 char *path)
 Set server root path.
 
const char * docroot () const
 Return current file origin.
 
void add_alias (const char *uri, const char *path)
 Maps a local file path to a path in the URI space.
 
void default_uri (const char *name)
 
const char * default_uri ()
 
void add_mime_type (const char *ext, const char *type, bool shtml=false)
 Add/change content of table matching MIME types to file extensions.
 
void delete_mime_type (const char *ext)
 Remove a file type from the MIME type table.
 
bool is_protected (const char *uri, std::string &realm)
 Find the longest match realm that covers an uri.
 
bool authenticate (const char *realm, const char *user, const char *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.
 
virtual void name (const std::string &nam)
 Change 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.
 

Protected Member Functions

int invoke_handler (const char *uri, http_connection &client)
 Invoke a user defined URI handler.
 
bool find_alias (const char *uri, char *path)
 Retrieve the local file path mapped to an URI.
 
const char * guess_mimetype (const char *file, bool &shtml)
 Guess MIME type of a file and if SSI replacement should be enabled based on file extension.
 
http_connectionmake_thread (sock &connection)
 Create an new http_connection object for a new incoming connection.
 
- 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 http_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 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 http_connection (or derived) class.

A HTTP server can be integrated to an application by adding specific url handlers and user variables. URL handlers are registered by calling the add_handler() function.

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.

Constructor & Destructor Documentation

◆ httpd()

mlib::httpd::httpd ( 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 HTTPD_DEFAULT
  • server name is HTTPD_SERVER_NAME

Member Function Documentation

◆ add_alias()

void mlib::httpd::add_alias ( const char *  uri,
const char *  path 
)

Maps a local file path to a path in the URI space.

Parameters
uriname in URI space
pathmapped local file path

◆ add_handler()

void mlib::httpd::add_handler ( const char *  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 will invoke the user-defined handler function passing the uri, the connection info and the handler specific information.

◆ add_mime_type()

void mlib::httpd::add_mime_type ( const char *  ext,
const char *  type,
bool  shtml = false 
)

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::httpd::add_ohdr ( const char *  hdr,
const char *  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_realm()

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

Add a new access realm.

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

Parameters
realmprotection realm
uristarting path

◆ add_user()

bool mlib::httpd::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::httpd::add_var ( const char *  name,
const char *  fmt,
void *  addr,
double  multiplier = 1. 
)

Add or modify a user variable.

Parameters
namevariable name (the name used in SSI construct)
fmtsprintf format string
addraddress of content
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.

◆ authenticate()

bool mlib::httpd::authenticate ( const char *  realm,
const char *  user,
const char *  pwd 
)

Verify user credentials for a realm.

Returns
true if user is authorized for the realm

◆ delete_mime_type()

void mlib::httpd::delete_mime_type ( const char *  ext)

Remove a file type from the MIME type table.

Parameters
extfilename extension

◆ find_alias()

bool mlib::httpd::find_alias ( const char *  uri,
char *  path 
)
protected

Retrieve the local file path mapped to an URI.

Parameters
uriURI path
pathlocal path
Returns
true if URI was successfully mapped.

After processing the alias table, any part of the original URI 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\\", an URI like "/doc/project1/filename.html" will be mapped to "c:\local_folder\documentation\project1\filename.html".

◆ get_var()

string mlib::httpd::get_var ( const char *  name)

Return the current string representation of a variable.

Parameters
namevariable name

◆ guess_mimetype()

const char * mlib::httpd::guess_mimetype ( const char *  file,
bool &  shtml 
)
protected

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

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

◆ invoke_handler()

int mlib::httpd::invoke_handler ( const char *  uri,
http_connection client 
)
protected

Invoke a user defined URI handler.

Parameters
uriURI that triggered the handler invocation
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::httpd::is_protected ( const char *  uri,
std::string &  realm 
)

Find the longest match realm that covers an uri.

Parameters
uriuri to check
realmmatching realm
Returns
true if uri is covered by a realm

◆ make_thread()

http_connection * mlib::httpd::make_thread ( sock connection)
protectedvirtual

Create an new http_connection object for a new incoming connection.

Derived classes can override this function to return objects derived from http_connection class.

Reimplemented from mlib::tcpserver.

◆ name()

void mlib::httpd::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::httpd::remove_ohdr ( const char *  hdr)

Remove a server response header.

Parameters
hdrHeader name

◆ try_varlock()

bool mlib::httpd::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: