Bredbandskollen CLI  1.2
Asynchronous network task engine
Public Member Functions | Static Public Member Functions | Protected Attributes | List of all members
WebServerTask Class Reference

API for HTTP servers. More...

#include <webservertask.h>

Inheritance diagram for WebServerTask:
Inheritance graph
[legend]
Collaboration diagram for WebServerTask:
Collaboration graph
[legend]

Public Member Functions

 WebServerTask (const std::string &name, const TaskConfig &cfg=TaskConfig())
 
double start () override
 
std::string headers (const std::string &code)
 
std::string setCookie (const std::string &name, const std::string &val, long expiry=0, const std::string &path="/", std::string domain="") const
 Return a string that may be inserted into the HTTP response headers. More...
 
virtual HttpState newGetRequest (HttpServerConnection *, const std::string &)
 
virtual size_t sendResponseData (HttpServerConnection *, size_t)
 
virtual HttpState newPostRequest (HttpServerConnection *conn, const std::string &uri)
 
virtual bool partialPostData (HttpServerConnection *conn, const char *buffer, size_t len)
 Retrieve part of a post message from client. More...
 
virtual HttpState lastPostData (HttpServerConnection *conn, const char *buffer, size_t len)
 Retrieve last part of a post message from client.
 
virtual bool newWsRequest (HttpServerConnection *conn, const std::string &uri)
 Request from client for a websocket upgrade. More...
 
virtual void wsHandshakeFinished (HttpServerConnection *conn, const std::string &uri)
 
virtual HttpState preflightRequest (HttpServerConnection *, const std::string &)
 Override this to implement a response to a preflight (OPTIONS) request.
 
void connAdded (SocketConnection *conn) override
 
void connRemoved (SocketConnection *conn) override
 
void setFixedHeaders (const std::string &hdr)
 One or more HTTP response header lines that always should be sent. More...
 
SocketConnectionnewClient (int fd, const char *ip, uint16_t port, ServerSocket *) final
 
std::string webRoot () const
 
void setWebRoot (const std::string &path)
 
void newWorkerChannel (SocketReceiver *srv, unsigned int chan) override
 
- Public Member Functions inherited from HttpTask
 HttpTask (const std::string &name)
 
virtual bool wsTextMessage (HttpConnection *, const std::string &msg)
 Incoming websocket text message. Return false to kill connection.
 
virtual bool wsBinMessage (HttpConnection *, const std::string &msg)
 Incoming websocket binary message. Return false to kill connection.
 
virtual bool wsBinHeader (HttpConnection *, size_t)
 Called when headers of a binary message are read. More...
 
virtual bool wsTextHeader (HttpConnection *, size_t)
 Called when headers of a text message are read. More...
 
virtual bool wsBinData (HttpConnection *, const char *, size_t)
 Incoming partial websocket binary message. More...
 
virtual bool wsTextData (HttpConnection *, const char *, size_t)
 Incoming partial websocket text message. More...
 
virtual size_t sendWsData (HttpConnection *conn)
 
- Public Member Functions inherited from Task
 Task (const std::string &task_name)
 Create a task with the given name. More...
 
virtual ~Task ()
 
virtual double timerEvent ()
 
void resetTimer (double s)
 Run timerEvent after s seconds instead of previous value.
 
bool finishedOK () const
 Return true if the task has finished normally. More...
 
bool wasKilled () const
 Return true if the task is finished and was aborted by another task. More...
 
bool wasError () const
 Return true if the task terminated with an error. More...
 
bool wasTimeout () const
 Return true if the task terminated with a timeout. More...
 
bool hasStarted () const
 
void killChildTaskWhenFinished ()
 
virtual bool adoptConnection (Socket *conn)
 
virtual void serverAdded (ServerSocket *)
 
virtual void serverRemoved (ServerSocket *)
 
std::string result () const
 To get the "result" of the task after it has finished.
 
std::set< Socket * > getMyConnections () const
 Return all current connections.
 
bool isActive (Socket *conn) const
 Return true if the connection still exists.
 
void wakeUp ()
 Restart all idle connections.
 
bool wakeUpConnection (SocketConnection *s)
 If s is idle, restart it and return true. Otherwise return false.
 
void cancelConnection (SocketConnection *s)
 Terminate and remove a connection.
 
std::string message () const
 Return the current (outgoing) message.
 
bool startObserving (Task *to)
 
void executeHandler (Task *receiver, const std::string &message)
 
double elapsed () const
 Return number of seconds since the task was started. More...
 
virtual TaskcreateWorkerTask (unsigned int wno)
 
virtual void finishWorkerTask (unsigned int)
 
virtual void workerMessage (SocketReceiver *, const char *buf, size_t len)
 Called if parent/worker sends a message through a SocketReceiver:
 
virtual PollState connectionReady (SocketConnection *)
 
virtual PollState msgFromConnection (SocketConnection *, const std::string &)
 
uint64_t bytesSent () const
 Number of bytes sent through SocketConnection objects owned by me.
 
uint64_t bytesReceived () const
 Number of bytes received through SocketConnection objects owned by me.
 
void resetByteCount ()
 Reset the values for the methods Task::bytesSent and Task::bytesReceived.
 
void notifyBytesSent (uint64_t n)
 Notify the task that data has been sent on its behalf. More...
 
void notifyBytesReceived (uint64_t n)
 Notify the task that data has been received on its behalf. More...
 
- Public Member Functions inherited from Logger
 Logger (std::string label)
 
std::string label () const
 Return the object's log label.
 
void resetLabel (const std::string &new_label)
 Modify the object's log label.
 

Static Public Member Functions

static std::string corsHeader (HttpServerConnection *conn, const std::string &domain)
 
- Static Public Member Functions inherited from Logger
static void setLogFile (std::ostream &stream)
 Set global log destination. More...
 
static void reopenLogFile (const std::string &filename)
 If current log is a file (ofstream), reopen it with new filename:
 
static void setLogLimit (unsigned int loglines=0, unsigned int warnlines=0, unsigned int errlines=0)
 Set max number of lines of info/warn/err log. More...
 
static void sayTime (std::ostream &stream)
 Write current local time to the given stream.
 
static bool inError ()
 Return true if any error has been logged (globally since start)
 
static std::ostream & err_log (const std::string &label)
 Write a line of error log. More...
 
static std::ostream & warn_log (const std::string &label)
 Write a line of warning log. More...
 
static std::ostream & log (const std::string &label)
 Write a line of info log. More...
 
static void flushLogFile ()
 
static void pauseLogging ()
 Disable all log output until next call to Logger::setLogFile.
 
static double secondsSince (const TimePoint &t)
 
static double secondsTo (const TimePoint &t)
 
static int64_t msSince (const TimePoint &t)
 
static int64_t msTo (const TimePoint &t)
 
static bool hasExpired (const TimePoint &t)
 Return true if current time is after the given TimePoint.
 
static TimePoint timeNow ()
 Return current time.
 
static TimePoint timeAfter (double s)
 Return current time plus s seconds.
 
static TimePoint timeMax ()
 Return a very distant time.
 
static std::chrono::microseconds toUs (double t)
 Convert s (seconds) to std::chrono::microseconds.
 
static std::string dateString (time_t t=0)
 Return local time, formatted as 2023-10-14T09:38:47+0200.
 
static std::string dateString2 (time_t t=0)
 Return local time, formatted as Sat, 14 Oct 2023 09:38:47.
 
static std::string createHashKey (unsigned int length=20)
 Return a random string. More...
 

Protected Attributes

TaskConfig the_config
 

Additional Inherited Members

- Protected Member Functions inherited from Task
bool addConnection (SocketConnection *conn)
 
bool addConnected (SocketConnection *conn)
 
bool addServer (ServerSocket *conn)
 As Task::addConnected, but with a server connection.
 
bool parseListen (const TaskConfig &tc, const std::string &log_label)
 
virtual bool tlsSetKey (ServerSocket *conn, const std::string &crt_path, const std::string &key_path, const std::string &password)
 Use SSL certificate for a listening socket.
 
void setResult (const std::string &res)
 
virtual void setError (const std::string &msg)
 
virtual void setTimeout ()
 
void setMessage (const std::string &msg)
 
virtual void taskFinished (Task *task)
 
virtual void taskMessage (Task *task)
 
virtual void handleExecution (Task *sender, const std::string &message)
 Callback to execute code on behalf of another Task.
 
bool terminated () const
 Return true if task is finished. More...
 
void addNewTask (Task *task, Task *parent=nullptr)
 Insert another Task for execution by the EventLoop.
 
void addNewThread (Task *task, const std::string &name="ThreadLoop", std::ostream *log_file=nullptr, Task *parent=nullptr)
 Run task in a new thread.
 
void getMyTasks (std::set< Task * > &tset)
 Add all my child tasks to the given set.
 
void abortMyTasks ()
 Terminate all my child tasks.
 
void abortTask (Task *task)
 Terminate a task.
 
void abortAllTasks ()
 Terminate all tasks and exit the EventLoop.
 
int runProcess (const char *const argv[])
 
virtual void processFinished (int pid, int wstatus)
 Will be called to notify when an external process has terminated.
 
WorkerProcesscreateWorker (std::ostream *log_file=nullptr, unsigned int channels=1, unsigned int wno=0)
 Run task returned by this->createWorkerTask in a child process. Return nullptr on failure.
 
WorkerProcesscreateWorker (const std::string &log_file_name, unsigned int channels=1, unsigned int wno=0)
 Run task returned by this->createWorkerTask in a child process. Return nullptr on failure.
 
- Protected Member Functions inherited from Logger
std::ostream & errno_log () const
 Write a line of error log after a failed system call has set the global errno to a non-zero value. More...
 
std::ostream & err_log () const
 Write a line of error log. More...
 
std::ostream & warn_log () const
 Write a line of warning log. More...
 
std::ostream & log () const
 Write a line of info log. More...
 
std::ostream & dbg_log () const
 Write a line of debug log. More...
 

Detailed Description

API for HTTP servers.

Member Function Documentation

◆ connAdded()

void WebServerTask::connAdded ( SocketConnection )
inlineoverridevirtual

This will be called to notify us when a new client socket object has been successfully added to this task. If you need to know that, override this method.

Reimplemented from Task.

Reimplemented in WSBlistener.

◆ connRemoved()

void WebServerTask::connRemoved ( SocketConnection )
inlineoverridevirtual

This will be called when a client socket object has been removed from this task, just before it is deleted. If you need to know that, override this method.

Reimplemented from Task.

Reimplemented in WSBlistener.

◆ corsHeader()

std::string WebServerTask::corsHeader ( HttpServerConnection conn,
const std::string &  domain 
)
static

Return Access-Control-Allow-Origin header if the conn's current request originates from domain (or a subdomain to it), otherwise return "".

◆ newClient()

SocketConnection * WebServerTask::newClient ( int  ,
const char *  ,
uint16_t  ,
ServerSocket  
)
finalvirtual

Ignore this unless the task is a server task. If a new remote connection is made through any ServerSocket object owned by us, the client socket, ip address and port number will be passed to the below method. Override it to create and return an object of a subclass to SocketConnection, otherwise the client socket will be closed. The object will be owned by the implementation and will be deleted when the connection has been closed. You must create the object with new.

Reimplemented from Task.

◆ newGetRequest()

virtual HttpState WebServerTask::newGetRequest ( HttpServerConnection ,
const std::string &   
)
inlinevirtual

When you overload this, call sendHttpResponse and return WAITING_FOR_REQUEST (or CLOSE), or call sendHttpResponseHeader and return SENDING_RESPONSE. In the latter case, your overloaded sendResponseData method will be called regularly until all is sent.

◆ newWorkerChannel()

void WebServerTask::newWorkerChannel ( SocketReceiver ,
unsigned int   
)
overridevirtual

Called during startup of worker process, once for each SocketReceiver object. Will be called before serverAdded with the same SocketReceiver. Overload this if your worker process has two or more SocketReceiver objects with different confguration (i.e. different SSL keys).

Reimplemented from Task.

◆ newWsRequest()

bool WebServerTask::newWsRequest ( HttpServerConnection conn,
const std::string &  uri 
)
virtual

Request from client for a websocket upgrade.

Return true to accept, false to close.

Reimplemented in WSBlistener.

◆ partialPostData()

bool WebServerTask::partialPostData ( HttpServerConnection conn,
const char *  buffer,
size_t  len 
)
virtual

Retrieve part of a post message from client.

Return true to continue, false to close the connection.

◆ sendResponseData()

virtual size_t WebServerTask::sendResponseData ( HttpServerConnection ,
size_t   
)
inlinevirtual

Overload this if you really have to take control over how the response is sent. Send up to bytes_left bytes through conn, return exactly the number of bytes written. To get it correct, you should just do

return conn->sendData(...) 

◆ setCookie()

std::string WebServerTask::setCookie ( const std::string &  name,
const std::string &  val,
long  expiry = 0,
const std::string &  path = "/",
std::string  domain = "" 
) const

Return a string that may be inserted into the HTTP response headers.

Let expiry be 0 for a session cookie, < 0 to delete cookie, otherwise expiry should be the cookie's max-time in seconds. If domain is empty, the cookie_domain config parameter will be used. Example:

conn->sendHttpResponse(headers("200 OK",
                               setCookie("lang", "en", 86400)), 

◆ setFixedHeaders()

void WebServerTask::setFixedHeaders ( const std::string &  hdr)
inline

One or more HTTP response header lines that always should be sent.

Terminate each line with \r
.

◆ start()

double WebServerTask::start ( )
overridevirtual

When the EventLoop starts executing a task, it will call its start method. All non-trivial initialization, e.g. creating new socket connections, should be performed in the start method.

If the task needs a timer, the start method must return the number of seconds until timerEvent should be called, or <= 0 if you don't want it to be called.

Reimplemented from Task.

◆ wsHandshakeFinished()

void WebServerTask::wsHandshakeFinished ( HttpServerConnection conn,
const std::string &  uri 
)
virtual

If you want to send data immediately after a websocket connection has been established (i.e. before the client has asked for anything), call conn->notifyWsHandshake() in the newWsRequest method; then the below method will be called after the handshake:


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