1Embedding CivetWeb 2========= 3 4CivetWeb is primarily designed so applications can easily add HTTP and HTTPS server as well as WebSocket (WS and WSS) server functionality. 5For example, a C/C++ application could use CivetWeb to enable a web service and configuration interface, to add a HTML5 data visualization interface, for automation or remote control, as a protocol gateway or as a HTTP/WebSocket client for firewall traversal. 6 7It can also be used as a stand-alone executable. It can deliver static files and offers built-in server side Lua, JavaScript and CGI support. Some instructions how to build the stand-alone server can be found in [Building.md](https://github.com/civetweb/civetweb/blob/master/docs/Building.md). 8 9 10Files 11------ 12 13There is just a small set of files to compile in to the application, 14but if a library is desired, see [Building.md](https://github.com/CivetWeb/CivetWeb/blob/master/docs/Building.md) 15 16 17#### Regarding the INL file extension 18The *INL* file extension represents code that is statically included inline in a source file. Slightly different from C++ where it means "inline" code which is technically not the same as static code. CivetWeb overloads this extension for the sake of clarity as opposed to having .c extensions on files that should not be directly compiled. 19 20 21#### HTTP Server Source Files 22These files constitute the CivetWeb library. They do not contain a `main` function, 23but all functions required to run a HTTP server. 24 25 - HTTP server API 26 - include/civetweb.h 27 - C implementation 28 - src/civetweb.c 29 - src/md5.inl (MD5 calculation) 30 - src/sha1.inl (SHA calculation) 31 - src/handle\_form.inl (HTML form handling functions) 32 - src/timer.inl (optional timer support) 33 - Optional: C++ wrapper 34 - include/CivetServer.h (C++ interface) 35 - src/CivetServer.cpp (C++ wrapper implementation) 36 - Optional: Third party components 37 - src/third\_party/* (third party components, mainly used for the standalone server) 38 - src/mod\_*.inl (modules to access third party components from civetweb) 39 40 41Note: The C++ wrapper uses the official C interface (civetweb.h) without adding any features to the server itself. Several features available in the C interface are missing in the C++ interface. While all features should be accessible using the C interface, this is not a design goal of the C++ interface. 42 43 44#### Additional Source Files for Executables 45These files can be used to build a server executable. They contain a `main` function 46starting the HTTP server. 47 48 - Stand-alone C server 49 - src/main.c 50 - Reference embedded C server 51 - examples/embedded\_c/embedded\_c.c 52 - Reference embedded C++ server 53 - examples/embedded\_cpp/embedded\_cpp.cpp 54 55Note: The "embedded" example is actively maintained, updated, extended and tested. Other examples in the examples/ folder might be outdated and remain there for reference. 56 57 58Quick Start 59------ 60 61By default, the server will automatically serve up files like a normal HTTP server. An embedded server is most likely going to overload this functionality. 62 63### C 64 - Include the C interface ```civetweb.h```. 65 - Use `mg_start()` to start the server. 66 - Use *options* to select the port and document root among other things. 67 - Use *callbacks* to add your own hooks. 68 - Use `mg_set_request_handler()` to easily add your own request handlers. 69 - Use `mg_stop()` to stop the server. 70 71### C++ 72 - Note that CivetWeb is Clean C, and C++ interface ```CivetServer.h``` is only a wrapper layer around the C interface. 73 Not all CivetWeb features available in C are also available in C++. 74 - Create CivetHandlers for each URI. 75 - Register the handlers with `CivetServer::addHandler()` 76 - `CivetServer` starts on construction and stops on destruction. 77 - Use constructor *options* to select the port and document root among other things. 78 - Use constructor *callbacks* to add your own hooks. 79 80Alternative quick start: Have a look at the examples embedded\_c and embedded\_cpp 81 82 83Feature selection 84------ 85 86CivetWeb is highly customizable at build time, in addition to configuration at start time. 87 88##### start time options 89Start time options are passed to `mg_start`. They are documented in the [UserManual.md](https://github.com/civetweb/civetweb/blob/master/docs/UserManual.md). 90 91##### callbacks 92Pointers to callback functions are passed to `mg_start` as well. They are documented in [civetweb.h](https://github.com/civetweb/civetweb/blob/master/include/civetweb.h) and the callbacks [API documentation](https://github.com/civetweb/civetweb/blob/master/docs/api/mg_callbacks.md). 93 94##### compiler defines 95Several features can be turned "on" or "off" by setting compile defines. CivetWeb builds with a reasonable default feature set. Optional features not including in the default can be added by adding a `USE\_<feature>` define. Default features can be removed by adding a `NO_<feature>` define. E.g., to build with Lua support, set `#define USE_LUA` (-DUSE_LUA), to build without CGI support set `#define NO_CGI` (-DNO_CGI). A list of feature defines is available in [Building.md](https://github.com/civetweb/civetweb/blob/master/docs/Building.md) - some versions may have additional, undocumented feature defines. Undocumented defines may become unavailable in future versions without notice. 96 97##### externally provided functions 98In some special cases, it might be meaningful to completely replace an internal function in [civetweb.c](https://github.com/civetweb/civetweb/blob/master/src/civetweb.c) with your own implementation. 99Since CivetWeb is free and open source software covered by the MIT license, you can feel free to just edit civetweb.c according to your needs. 100However, this might be annoying when updating the server, pulling new features or bug fixes from the main repository. For some selected functions, it is possible to provide your own implementation using a `MG_EXTERNAL_FUNCTION_<internal_function_name>` define. For details on this mechanism, please look directly into the source code [civetweb.c](https://github.com/civetweb/civetweb/blob/master/src/civetweb.c). Interfaces and even names of internal functions may change without notice - when you use these defines, you have to check this every time you update CivetWeb. It might still be less effort than to apply your patches every time. 101This customization option is currently in an evaluation phase. In case you need additional function defines, please create an issue on GitHub explaining your use case, to discuss if this would be an appropriate solution - in general, other customization options are preferred. 102 103 104Lua Support 105------ 106 107Lua is a server side include functionality. Files ending in .lua will be processed with Lua. 108 109##### Add the following CFLAGS 110 111 - `-DLUA_COMPAT_ALL` 112 - `-DUSE_LUA` 113 - `-DUSE_LUA_SQLITE3` 114 - `-DUSE_LUA_FILE_SYSTEM` 115 116##### Add the following sources 117 118 - src/mod\_lua.inl 119 - src/third\_party/lua-5.2.4/src 120 + lapi.c 121 + lauxlib.c 122 + lbaselib.c 123 + lbitlib.c 124 + lcode.c 125 + lcorolib.c 126 + lctype.c 127 + ldblib.c 128 + ldebug.c 129 + ldo.c 130 + ldump.c 131 + lfunc.c 132 + lgc.c 133 + linit.c 134 + liolib.c 135 + llex.c 136 + lmathlib.c 137 + lmem.c 138 + loadlib.c 139 + lobject.c 140 + lopcodes.c 141 + loslib.c 142 + lparser.c 143 + lstate.c 144 + lstring.c 145 + lstrlib.c 146 + ltable.c 147 + ltablib.c 148 + ltm.c 149 + lundump.c 150 + lvm.c 151 + lzio.c 152 - src/third\_party/sqlite3.c 153 - src/third\_party/sqlite3.h 154 - src/third\_party/lsqlite3.c 155 - src/third\_party/lfs.c 156 - src/third\_party/lfs.h 157 158This build is valid for Lua version Lua 5.2. It is also possible to build with Lua 5.1 (including LuaJIT) or Lua 5.3. 159 160 161JavaScript Support 162------ 163 164CivetWeb can be built with server side JavaScript support by including the Duktape library. 165 166 167CivetWeb internals 168------ 169 170CivetWeb is multithreaded web server. `mg_start()` function allocates 171web server context (`struct mg_context`), which holds all information 172about web server instance: 173 174- configuration options. Note that CivetWeb makes internal copies of 175 passed options. 176- SSL context, if any 177- user-defined callbacks 178- opened listening sockets 179- a queue for accepted sockets 180- mutexes and condition variables for inter-thread synchronization 181 182When `mg_start()` returns, all initialization is guaranteed to be complete 183(e.g. listening ports are opened, SSL is initialized, etc). `mg_start()` starts 184some threads: a master thread, that accepts new connections, and several 185worker threads, that process accepted connections. The number of worker threads 186is configurable via `num_threads` configuration option. That number puts a 187limit on number of simultaneous requests that can be handled by CivetWeb. 188If you embed CivetWeb into a program that uses SSL outside CivetWeb as well, 189you may need to initialize SSL before calling `mg_start()`, and set the pre- 190processor define `SSL_ALREADY_INITIALIZED`. This is not required if SSL is 191used only within CivetWeb. 192 193When master thread accepts new a connection, a new accepted socket (described 194by `struct socket`) it placed into the accepted sockets queue, 195which has size of `MGSQLEN` (default 20). 196Any idle worker thread can grab accepted sockets from that queue. 197If all worker threads are busy, master thread can accept and queue up to 19820 more TCP connections, filling up the queue. 199In the attempt to queue even more accepted connection, the master thread blocks 200until there is space in the queue. When the master thread is blocked on a 201full queue, the operating system can also queue incoming connection. 202The number is limited by the `listen()` call parameter, 203which is `SOMAXCONN` and depends on the platform. 204 205Worker threads are running in an infinite loop, which in a simplified form 206looks something like this: 207 208```C 209 static void *worker_thread() { 210 while (consume_socket()) { 211 process_new_connection(); 212 } 213 } 214``` 215 216Function `consume_socket()` gets a new accepted socket from the CivetWeb socket 217queue, atomically removing it from the queue. If the queue is empty, 218`consume_socket()` blocks and waits until a new socket is placed in the queue 219by the master thread. 220 221`process_new_connection()` actually processes the 222connection, i.e. reads the request, parses it, and performs appropriate action 223depending on the parsed request. 224 225Master thread uses `poll()` and `accept()` to accept new connections on 226listening sockets. `poll()` is used to avoid `FD_SETSIZE` limitation of 227`select()`. Since there are only a few listening sockets, there is no reason 228to use hi-performance alternatives like `epoll()` or `kqueue()`. Worker 229threads use blocking IO on accepted sockets for reading and writing data. 230All accepted sockets have `SO_RCVTIMEO` and `SO_SNDTIMEO` socket options set 231(controlled by the `request_timeout_ms` CivetWeb option, 30 seconds default) 232which specifies a read/write timeout on client connections. 233 234 235A minimal example 236------ 237 238Initializing a HTTP server 239```C 240{ 241 /* Server context handle */ 242 struct mg_context *ctx; 243 244 /* Initialize the library */ 245 mg_init_library(0); 246 247 /* Start the server */ 248 ctx = mg_start(NULL, 0, NULL); 249 250 /* Add some handler */ 251 mg_set_request_handler(ctx, "/hello", handler, "Hello world"); 252 253 ... Run the application ... 254 255 /* Stop the server */ 256 mg_stop(ctx); 257 258 /* Un-initialize the library */ 259 mg_exit_library(); 260} 261``` 262 263A simple callback 264```C 265static int 266handler(struct mg_connection *conn, void *ignored) 267{ 268 const char *msg = "Hello world"; 269 unsigned long len = (unsigned long)strlen(msg); 270 271 mg_printf(conn, 272 "HTTP/1.1 200 OK\r\n" 273 "Content-Length: %lu\r\n" 274 "Content-Type: text/plain\r\n" 275 "Connection: close\r\n\r\n", 276 len); 277 278 mg_write(conn, msg, len); 279 280 return 200; 281} 282``` 283 284