blob: ed51c3e20e1c23693123bfdeb0f8c1bd84ffd037 [file] [log] [blame]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>libwebsockets: Notes about coding with lws</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="libwebsockets.org-logo.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">libwebsockets
</div>
<div id="projectbrief">Lightweight C library for HTML5 websockets</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.12 -->
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',false,false,'search.php','Search');
});
</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('md_README_8coding.html','');});
</script>
<div id="doc-content">
<div class="header">
<div class="headertitle">
<div class="title">Notes about coding with lws </div> </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><h1><a class="anchor" id="dae"></a>
Daemonization</h1>
<p>There's a helper api <code>lws_daemonize</code> built by default that does everything you need to daemonize well, including creating a lock file. If you're making what's basically a daemon, just call this early in your init to fork to a headless background process and exit the starting process.</p>
<p>Notice stdout, stderr, stdin are all redirected to /dev/null to enforce your daemon is headless, so you'll need to sort out alternative logging, by, eg, syslog.</p>
<h1><a class="anchor" id="conns"></a>
Maximum number of connections</h1>
<p>The maximum number of connections the library can deal with is decided when it starts by querying the OS to find out how many file descriptors it is allowed to open (1024 on Fedora for example). It then allocates arrays that allow up to that many connections, minus whatever other file descriptors are in use by the user code.</p>
<p>If you want to restrict that allocation, or increase it, you can use ulimit or similar to change the available number of file descriptors, and when restarted <b>libwebsockets</b> will adapt accordingly.</p>
<h1><a class="anchor" id="evtloop"></a>
Libwebsockets is singlethreaded</h1>
<p>Libwebsockets works in a serialized event loop, in a single thread.</p>
<p>Directly performing websocket actions from other threads is not allowed. Aside from the internal data being inconsistent in <code>forked()</code> processes, the scope of a <code>wsi</code> (<code>struct websocket</code>) can end at any time during service with the socket closing and the <code>wsi</code> freed.</p>
<p>Websocket write activities should only take place in the <code>LWS_CALLBACK_SERVER_WRITEABLE</code> callback as described below.</p>
<p>[This network-programming necessity to link the issue of new data to the peer taking the previous data is not obvious to all users so let's repeat that in other words:</p>
<p>***ONLY DO LWS_WRITE FROM THE WRITEABLE CALLBACK***</p>
<p>There is another network-programming truism that surprises some people which is if the sink for the data cannot accept more:</p>
<p>***YOU MUST PERFORM RX FLOW CONTROL***</p>
<p>See the mirror protocol implementations for example code.</p>
<p>Only live connections appear in the user callbacks, so this removes any possibility of trying to used closed and freed wsis.</p>
<p>If you need to service other socket or file descriptors as well as the websocket ones, you can combine them together with the websocket ones in one poll loop, see "External Polling Loop support" below, and still do it all in one thread / process context.</p>
<p>If you insist on trying to use it from multiple threads, take special care if you might simultaneously create more than one context from different threads.</p>
<p>SSL_library_init() is called from the context create api and it also is not reentrant. So at least create the contexts sequentially.</p>
<h1><a class="anchor" id="writeable"></a>
Only send data when socket writeable</h1>
<p>You should only send data on a websocket connection from the user callback <code>LWS_CALLBACK_SERVER_WRITEABLE</code> (or <code>LWS_CALLBACK_CLIENT_WRITEABLE</code> for clients).</p>
<p>If you want to send something, do not just send it but request a callback when the socket is writeable using</p>
<ul>
<li><code>lws_callback_on_writable(context, wsi)</code> for a specific <code>wsi</code>, or</li>
<li><code>lws_callback_on_writable_all_protocol(protocol)</code> for all connections using that protocol to get a callback when next writeable.</li>
</ul>
<p>Usually you will get called back immediately next time around the service loop, but if your peer is slow or temporarily inactive the callback will be delayed accordingly. Generating what to write and sending it should be done in the ...WRITEABLE callback.</p>
<p>See the test server code for an example of how to do this.</p>
<h1><a class="anchor" id="otherwr"></a>
Do not rely on only your own WRITEABLE requests appearing</h1>
<p>Libwebsockets may generate additional <code>LWS_CALLBACK_CLIENT_WRITEABLE</code> events if it met network conditions where it had to buffer your send data internally.</p>
<p>So your code for <code>LWS_CALLBACK_CLIENT_WRITEABLE</code> needs to own the decision about what to send, it can't assume that just because the writeable callback came it really is time to send something.</p>
<p>It's quite possible you get an 'extra' writeable callback at any time and just need to <code>return 0</code> and wait for the expected callback later.</p>
<h1><a class="anchor" id="closing"></a>
Closing connections from the user side</h1>
<p>When you want to close a connection, you do it by returning <code>-1</code> from a callback for that connection.</p>
<p>You can provoke a callback by calling <code>lws_callback_on_writable</code> on the wsi, then notice in the callback you want to close it and just return -1. But usually, the decision to close is made in a callback already and returning -1 is simple.</p>
<p>If the socket knows the connection is dead, because the peer closed or there was an affirmitive network error like a FIN coming, then <b>libwebsockets</b> will take care of closing the connection automatically.</p>
<p>If you have a silently dead connection, it's possible to enter a state where the send pipe on the connection is choked but no ack will ever come, so the dead connection will never become writeable. To cover that, you can use TCP keepalives (see later in this document) or pings.</p>
<h1><a class="anchor" id="frags"></a>
Fragmented messages</h1>
<p>To support fragmented messages you need to check for the final frame of a message with <code>lws_is_final_fragment</code>. This check can be combined with <code>libwebsockets_remaining_packet_payload</code> to gather the whole contents of a message, eg:</p>
<div class="fragment"><div class="line">case LWS_CALLBACK_RECEIVE:</div><div class="line">{</div><div class="line"> Client * const client = (Client *)user;</div><div class="line"> const size_t remaining = lws_remaining_packet_payload(wsi);</div><div class="line"></div><div class="line"> if (!remaining &amp;&amp; lws_is_final_fragment(wsi)) {</div><div class="line"> if (client-&gt;HasFragments()) {</div><div class="line"> client-&gt;AppendMessageFragment(in, len, 0);</div><div class="line"> in = (void *)client-&gt;GetMessage();</div><div class="line"> len = client-&gt;GetMessageLength();</div><div class="line"> }</div><div class="line"></div><div class="line"> client-&gt;ProcessMessage((char *)in, len, wsi);</div><div class="line"> client-&gt;ResetMessage();</div><div class="line"> } else</div><div class="line"> client-&gt;AppendMessageFragment(in, len, remaining);</div><div class="line">}</div><div class="line">break;</div></div><!-- fragment --><p>The test app libwebsockets-test-fraggle sources also show how to deal with fragmented messages.</p>
<h1><a class="anchor" id="debuglog"></a>
Debug Logging</h1>
<p>Also using <code>lws_set_log_level</code> api you may provide a custom callback to actually emit the log string. By default, this points to an internal emit function that sends to stderr. Setting it to <code>NULL</code> leaves it as it is instead.</p>
<p>A helper function <code><a class="el" href="group__log.html#gab7c0fc936cc9f1eb58e2bb234c15147c">lwsl_emit_syslog()</a></code> is exported from the library to simplify logging to syslog. You still need to use <code>setlogmask</code>, <code>openlog</code> and <code>closelog</code> in your user code.</p>
<p>The logging apis are made available for user code.</p>
<ul>
<li><code>lwsl_err(...)</code></li>
<li><code>lwsl_warn(...)</code></li>
<li><code>lwsl_notice(...)</code></li>
<li><code>lwsl_info(...)</code></li>
<li><code>lwsl_debug(...)</code></li>
</ul>
<p>The difference between notice and info is that notice will be logged by default whereas info is ignored by default.</p>
<p>If you are not building with _DEBUG defined, ie, without this</p>
<div class="fragment"><div class="line">$ cmake .. -DCMAKE_BUILD_TYPE=DEBUG</div></div><!-- fragment --><p>then log levels below notice do not actually get compiled in.</p>
<h1><a class="anchor" id="extpoll"></a>
External Polling Loop support</h1>
<p><b>libwebsockets</b> maintains an internal <code>poll()</code> array for all of its sockets, but you can instead integrate the sockets into an external polling array. That's needed if <b>libwebsockets</b> will cooperate with an existing poll array maintained by another server.</p>
<p>Four callbacks <code>LWS_CALLBACK_ADD_POLL_FD</code>, <code>LWS_CALLBACK_DEL_POLL_FD</code>, <code>LWS_CALLBACK_SET_MODE_POLL_FD</code> and <code>LWS_CALLBACK_CLEAR_MODE_POLL_FD</code> appear in the callback for protocol 0 and allow interface code to manage socket descriptors in other poll loops.</p>
<p>You can pass all pollfds that need service to <code><a class="el" href="group__service.html#gad82efa5466d14a9f05aa06416375b28d">lws_service_fd()</a></code>, even if the socket or file does not belong to <b>libwebsockets</b> it is safe.</p>
<p>If <b>libwebsocket</b> handled it, it zeros the pollfd <code>revents</code> field before returning. So you can let <b>libwebsockets</b> try and if <code>pollfd-&gt;revents</code> is nonzero on return, you know it needs handling by your code.</p>
<p>Also note that when integrating a foreign event loop like libev or libuv where it doesn't natively use poll() semantics, and you must return a fake pollfd reflecting the real event:</p>
<ul>
<li>be sure you set .events to .revents value as well in the synthesized pollfd</li>
<li>check the built-in support for the event loop if possible (eg, ./lib/libuv.c) to see how it interfaces to lws</li>
<li>use LWS_POLLHUP / LWS_POLLIN / LWS_POLLOUT from <a class="el" href="libwebsockets_8h.html">libwebsockets.h</a> to avoid losing windows compatibility</li>
</ul>
<h1><a class="anchor" id="cpp"></a>
Using with in c++ apps</h1>
<p>The library is ready for use by C++ apps. You can get started quickly by copying the test server</p>
<div class="fragment"><div class="line">$ cp test-server/test-server.c test.cpp</div></div><!-- fragment --><p>and building it in C++ like this</p>
<div class="fragment"><div class="line">$ g++ -DINSTALL_DATADIR=\&quot;/usr/share\&quot; -ocpptest test.cpp -lwebsockets</div></div><!-- fragment --><p><code>INSTALL_DATADIR</code> is only needed because the test server uses it as shipped, if you remove the references to it in your app you don't need to define it on the g++ line either.</p>
<h1><a class="anchor" id="headerinfo"></a>
Availability of header information</h1>
<p>HTTP Header information is managed by a pool of "ah" structs. These are a limited resource so there is pressure to free the headers and return the ah to the pool for reuse.</p>
<p>For that reason header information on HTTP connections that get upgraded to websockets is lost after the ESTABLISHED callback. Anything important that isn't processed by user code before then should be copied out for later.</p>
<p>For HTTP connections that don't upgrade, header info remains available the whole time.</p>
<h1><a class="anchor" id="ka"></a>
TCP Keepalive</h1>
<p>It is possible for a connection which is not being used to send to die silently somewhere between the peer and the side not sending. In this case by default TCP will just not report anything and you will never get any more incoming data or sign the link is dead until you try to send.</p>
<p>To deal with getting a notification of that situation, you can choose to enable TCP keepalives on all <b>libwebsockets</b> sockets, when you create the context.</p>
<p>To enable keepalive, set the ka_time member of the context creation parameter struct to a nonzero value (in seconds) at context creation time. You should also fill ka_probes and ka_interval in that case.</p>
<p>With keepalive enabled, the TCP layer will send control packets that should stimulate a response from the peer without affecting link traffic. If the response is not coming, the socket will announce an error at <code>poll()</code> forcing a close.</p>
<p>Note that BSDs don't support keepalive time / probes / interval per-socket like Linux does. On those systems you can enable keepalive by a nonzero value in <code>ka_time</code>, but the systemwide kernel settings for the time / probes/ interval are used, regardless of what nonzero value is in <code>ka_time</code>.</p>
<h1><a class="anchor" id="sslopt"></a>
Optimizing SSL connections</h1>
<p>There's a member <code>ssl_cipher_list</code> in the <code><a class="el" href="structlws__context__creation__info.html">lws_context_creation_info</a></code> struct which allows the user code to restrict the possible cipher selection at context-creation time.</p>
<p>You might want to look into that to stop the ssl peers selecting a cipher which is too computationally expensive. To use it, point it to a string like </p><pre class="fragment"> `"RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL"`
</pre><p>if left <code>NULL</code>, then the "DEFAULT" set of ciphers are all possible to select.</p>
<p>You can also set it to <code>"ALL"</code> to allow everything (including insecure ciphers).</p>
<h1><a class="anchor" id="clientasync"></a>
Async nature of client connections</h1>
<p>When you call <code><a class="el" href="structlws__client__connect__info.html">lws_client_connect_info</a>(..)</code> and get a <code>wsi</code> back, it does not mean your connection is active. It just means it started trying to connect.</p>
<p>Your client connection is actually active only when you receive <code>LWS_CALLBACK_CLIENT_ESTABLISHED</code> for it.</p>
<p>There's a 5 second timeout for the connection, and it may give up or die for other reasons, if any of that happens you'll get a <code>LWS_CALLBACK_CLIENT_CONNECTION_ERROR</code> callback on protocol 0 instead for the <code>wsi</code>.</p>
<p>After attempting the connection and getting back a non-<code>NULL</code> <code>wsi</code> you should loop calling <code><a class="el" href="group__service.html#gaf95bd0c663d6516a0c80047d9b1167a8">lws_service()</a></code> until one of the above callbacks occurs.</p>
<p>As usual, see <a href="test-server/test-client.c">test-client.c</a> for example code.</p>
<p>Notice that the client connection api tries to progress the connection somewhat before returning. That means it's possible to get callbacks like CONNECTION_ERROR on the new connection before your user code had a chance to get the wsi returned to identify it (in fact if the connection did fail early, NULL will be returned instead of the wsi anyway).</p>
<p>To avoid that problem, you can fill in <code>pwsi</code> in the client connection info struct to point to a struct lws that get filled in early by the client connection api with the related wsi. You can then check for that in the callback to confirm the identity of the failing client connection.</p>
<h1><a class="anchor" id="fileapi"></a>
Lws platform-independent file access apis</h1>
<p>lws now exposes his internal platform file abstraction in a way that can be both used by user code to make it platform-agnostic, and be overridden or subclassed by user code. This allows things like handling the URI "directory
space" as a virtual filesystem that may or may not be backed by a regular filesystem. One example use is serving files from inside large compressed archive storage without having to unpack anything except the file being requested.</p>
<p>The test server shows how to use it, basically the platform-specific part of lws prepares a file operations structure that lives in the lws context.</p>
<p>The user code can get a pointer to the file operations struct</p>
<div class="fragment"><div class="line">LWS_VISIBLE LWS_EXTERN struct lws_plat_file_ops *</div><div class="line"> `lws_get_fops`(struct lws_context *context);</div></div><!-- fragment --><p>and then can use helpers to also leverage these platform-independent file handling apis</p>
<div class="fragment"><div class="line">static inline lws_filefd_type</div><div class="line">`lws_plat_file_open`(struct lws *wsi, const char *filename, unsigned long *filelen, int flags)</div><div class="line"></div><div class="line">static inline int</div><div class="line">`lws_plat_file_close`(struct lws *wsi, lws_filefd_type fd)</div><div class="line"></div><div class="line">static inline unsigned long</div><div class="line">`lws_plat_file_seek_cur`(struct lws *wsi, lws_filefd_type fd, long offset_from_cur_pos)</div><div class="line"></div><div class="line">static inline int</div><div class="line">`lws_plat_file_read`(struct lws *wsi, lws_filefd_type fd, unsigned long *amount, unsigned char *buf, unsigned long len)</div><div class="line"></div><div class="line">static inline int</div><div class="line">`lws_plat_file_write`(struct lws *wsi, lws_filefd_type fd, unsigned long *amount, unsigned char *buf, unsigned long len)</div></div><!-- fragment --><p>The user code can also override or subclass the file operations, to either wrap or replace them. An example is shown in test server.</p>
<h1><a class="anchor" id="ecdh"></a>
ECDH Support</h1>
<p>ECDH Certs are now supported. Enable the CMake option </p><pre class="fragment"> cmake .. -DLWS_SSL_SERVER_WITH_ECDH_CERT=1
</pre><p><b>and</b> the info-&gt;options flag </p><pre class="fragment"> LWS_SERVER_OPTION_SSL_ECDH
</pre><p>to build in support and select it at runtime.</p>
<h1><a class="anchor" id="smp"></a>
SMP / Multithreaded service</h1>
<p>SMP support is integrated into LWS without any internal threading. It's very simple to use, libwebsockets-test-server-pthread shows how to do it, use -j &lt;n&gt; argument there to control the number of service threads up to 32.</p>
<p>Two new members are added to the info struct </p><pre class="fragment"> unsigned int count_threads;
unsigned int fd_limit_per_thread;
</pre><p>leave them at the default 0 to get the normal singlethreaded service loop.</p>
<p>Set count_threads to n to tell lws you will have n simultaneous service threads operating on the context.</p>
<p>There is still a single listen socket on one port, no matter how many service threads.</p>
<p>When a connection is made, it is accepted by the service thread with the least connections active to perform load balancing.</p>
<p>The user code is responsible for spawning n threads running the service loop associated to a specific tsi (Thread Service Index, 0 .. n - 1). See the libwebsockets-test-server-pthread for how to do.</p>
<p>If you leave fd_limit_per_thread at 0, then the process limit of fds is shared between the service threads; if you process was allowed 1024 fds overall then each thread is limited to 1024 / n.</p>
<p>You can set fd_limit_per_thread to a nonzero number to control this manually, eg the overall supported fd limit is less than the process allowance.</p>
<p>You can control the context basic data allocation for multithreading from Cmake using -DLWS_MAX_SMP=, if not given it's set to 32. The serv_buf allocation for the threads (currently 4096) is made at runtime only for active threads.</p>
<p>Because lws will limit the requested number of actual threads supported according to LWS_MAX_SMP, there is an api lws_get_count_threads(context) to discover how many threads were actually allowed when the context was created.</p>
<p>It's required to implement locking in the user code in the same way that libwebsockets-test-server-pthread does it, for the FD locking callbacks.</p>
<p>There is no knowledge or dependency in lws itself about pthreads. How the locking is implemented is entirely up to the user code.</p>
<h1><a class="anchor" id="libevuv"></a>
Libev / Libuv support</h1>
<p>You can select either or both </p><pre class="fragment"> -DLWS_WITH_LIBEV=1
-DLWS_WITH_LIBUV=1
</pre><p>at cmake configure-time. The user application may use one of the context init options flags </p><pre class="fragment"> LWS_SERVER_OPTION_LIBEV
LWS_SERVER_OPTION_LIBUV
</pre><p>to indicate it will use either of the event libraries.</p>
<h1><a class="anchor" id="extopts"></a>
Extension option control from user code</h1>
<p>User code may set per-connection extension options now, using a new api <code><a class="el" href="group__extensions.html#gae0e24e1768f83a7fb07896ce975704b9">lws_set_extension_option()</a></code>.</p>
<p>This should be called from the ESTABLISHED callback like this </p><div class="fragment"><div class="line">lws_set_extension_option(wsi, &quot;permessage-deflate&quot;,</div><div class="line"> &quot;rx_buf_size&quot;, &quot;12&quot;); /* 1 &lt;&lt; 12 */</div></div><!-- fragment --><p>If the extension is not active (missing or not negotiated for the connection, or extensions are disabled on the library) the call is just returns -1. Otherwise the connection's extension has its named option changed.</p>
<p>The extension may decide to alter or disallow the change, in the example above permessage-deflate restricts the size of his rx output buffer also considering the protocol's rx_buf_size member.</p>
<h1><a class="anchor" id="httpsclient"></a>
Client connections as HTTP[S] rather than WS[S]</h1>
<p>You may open a generic http client connection using the same struct <a class="el" href="structlws__client__connect__info.html">lws_client_connect_info</a> used to create client ws[s] connections.</p>
<p>To stay in http[s], set the optional info member "method" to point to the string "GET" instead of the default NULL.</p>
<p>After the server headers are processed, when payload from the server is available the callback LWS_CALLBACK_RECEIVE_CLIENT_HTTP will be made.</p>
<p>You can choose whether to process the data immediately, or queue a callback when an outgoing socket is writeable to provide flow control, and process the data in the writable callback.</p>
<p>Either way you use the api <code>lws_http_client_read()</code> to access the data, eg</p>
<div class="fragment"><div class="line">case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:</div><div class="line"> {</div><div class="line"> char buffer[1024 + LWS_PRE];</div><div class="line"> char *px = buffer + LWS_PRE;</div><div class="line"> int lenx = sizeof(buffer) - LWS_PRE;</div><div class="line"></div><div class="line"> lwsl_notice(&quot;LWS_CALLBACK_RECEIVE_CLIENT_HTTP\n&quot;);</div><div class="line"></div><div class="line"> /*</div><div class="line"> * Often you need to flow control this by something</div><div class="line"> * else being writable. In that case call the api</div><div class="line"> * to get a callback when writable here, and do the</div><div class="line"> * pending client read in the writeable callback of</div><div class="line"> * the output.</div><div class="line"> */</div><div class="line"> if (lws_http_client_read(wsi, &amp;px, &amp;lenx) &lt; 0)</div><div class="line"> return -1;</div><div class="line"> while (lenx--)</div><div class="line"> putchar(*px++);</div><div class="line"> }</div><div class="line"> break;</div></div><!-- fragment --><p>Notice that if you will use SSL client connections on a vhost, you must prepare the client SSL context for the vhost after creating the vhost, since this is not normally done if the vhost was set up to listen / serve. Call the api <a class="el" href="group__client.html#ga4f44b8230e6732816ca5cd8d1aaaf340">lws_init_vhost_client_ssl()</a> to also allow client SSL on the vhost.</p>
<h1><a class="anchor" id="vhosts"></a>
Using lws vhosts</h1>
<p>If you set LWS_SERVER_OPTION_EXPLICIT_VHOSTS options flag when you create your context, it won't create a default vhost using the info struct members for compatibility. Instead you can call <a class="el" href="group__context-and-vhost.html#ga0c54c667ccd9b8b3dddcd123ca72f87c">lws_create_vhost()</a> afterwards to attach one or more vhosts manually.</p>
<div class="fragment"><div class="line">LWS_VISIBLE struct lws_vhost *</div><div class="line">lws_create_vhost(struct lws_context *context,</div><div class="line"> struct lws_context_creation_info *info);</div></div><!-- fragment --><p><a class="el" href="group__context-and-vhost.html#ga0c54c667ccd9b8b3dddcd123ca72f87c">lws_create_vhost()</a> uses the same info struct as <a class="el" href="group__context-and-vhost.html#gaf2fff58562caab7510c41eeac85a8648">lws_create_context()</a>, it ignores members related to context and uses the ones meaningful for vhost (marked with VH in <a class="el" href="libwebsockets_8h.html">libwebsockets.h</a>).</p>
<div class="fragment"><div class="line">struct lws_context_creation_info {</div><div class="line"> int port; /* VH */</div><div class="line"> const char *iface; /* VH */</div><div class="line"> const struct lws_protocols *protocols; /* VH */</div><div class="line"> const struct lws_extension *extensions; /* VH */</div><div class="line">...</div></div><!-- fragment --><p>When you attach the vhost, if the vhost's port already has a listen socket then both vhosts share it and use SNI (is SSL in use) or the Host: header from the client to select the right one. Or if no other vhost already listening the a new listen socket is created.</p>
<p>There are some new members but mainly it's stuff you used to set at context creation time.</p>
<h1><a class="anchor" id="sni"></a>
How lws matches hostname or SNI to a vhost</h1>
<p>LWS first strips any trailing :port number.</p>
<p>Then it tries to find an exact name match for a vhost listening on the correct port, ie, if SNI or the Host: header provided abc.com:1234, it will match on a vhost named abc.com that is listening on port 1234.</p>
<p>If there is no exact match, lws will consider wildcard matches, for example if cats.abc.com:1234 is provided by the client by SNI or Host: header, it will accept a vhost "abc.com" listening on port 1234. If there was a better, exact, match, it will have been chosen in preference to this.</p>
<p>Connections with SSL will still have the client go on to check the certificate allows wildcards and error out if not.</p>
<h1><a class="anchor" id="mounts"></a>
Using lws mounts on a vhost</h1>
<p>The last argument to <a class="el" href="group__context-and-vhost.html#ga0c54c667ccd9b8b3dddcd123ca72f87c">lws_create_vhost()</a> lets you associate a linked list of <a class="el" href="structlws__http__mount.html">lws_http_mount</a> structures with that vhost's URL 'namespace', in a similar way that unix lets you mount filesystems into areas of your / filesystem how you like and deal with the contents transparently.</p>
<div class="fragment"><div class="line">struct lws_http_mount {</div><div class="line"> struct lws_http_mount *mount_next;</div><div class="line"> const char *mountpoint; /* mountpoint in http pathspace, eg, &quot;/&quot; */</div><div class="line"> const char *origin; /* path to be mounted, eg, &quot;/var/www/warmcat.com&quot; */</div><div class="line"> const char *def; /* default target, eg, &quot;index.html&quot; */</div><div class="line"></div><div class="line"> struct lws_protocol_vhost_options *cgienv;</div><div class="line"></div><div class="line"> int cgi_timeout;</div><div class="line"> int cache_max_age;</div><div class="line"></div><div class="line"> unsigned int cache_reusable:1;</div><div class="line"> unsigned int cache_revalidate:1;</div><div class="line"> unsigned int cache_intermediaries:1;</div><div class="line"></div><div class="line"> unsigned char origin_protocol;</div><div class="line"> unsigned char mountpoint_len;</div><div class="line">};</div></div><!-- fragment --><p>The last mount structure should have a NULL mount_next, otherwise it should point to the 'next' mount structure in your list.</p>
<p>Both the mount structures and the strings must persist until the context is destroyed, since they are not copied but used in place.</p>
<p><code>.origin_protocol</code> should be one of</p>
<div class="fragment"><div class="line">enum {</div><div class="line"> LWSMPRO_HTTP,</div><div class="line"> LWSMPRO_HTTPS,</div><div class="line"> LWSMPRO_FILE,</div><div class="line"> LWSMPRO_CGI,</div><div class="line"> LWSMPRO_REDIR_HTTP,</div><div class="line"> LWSMPRO_REDIR_HTTPS,</div><div class="line"> LWSMPRO_CALLBACK,</div><div class="line">};</div></div><!-- fragment --><ul>
<li>LWSMPRO_FILE is used for mapping url namespace to a filesystem directory and serve it automatically.</li>
<li>LWSMPRO_CGI associates the url namespace with the given CGI executable, which runs when the URL is accessed and the output provided to the client.</li>
<li>LWSMPRO_REDIR_HTTP and LWSMPRO_REDIR_HTTPS auto-redirect clients to the given origin URL.</li>
<li>LWSMPRO_CALLBACK causes the http connection to attach to the callback associated with the named protocol (which may be a plugin).</li>
</ul>
<h1><a class="anchor" id="mountcallback"></a>
Operation of LWSMPRO_CALLBACK mounts</h1>
<p>The feature provided by CALLBACK type mounts is binding a part of the URL namespace to a named protocol callback handler.</p>
<p>This allows protocol plugins to handle areas of the URL namespace. For example in test-server-v2.0.c, the URL area "/formtest" is associated with the plugin providing "protocol-post-demo" like this</p>
<div class="fragment"><div class="line">static const struct lws_http_mount mount_post = {</div><div class="line"> NULL, /* linked-list pointer to next*/</div><div class="line"> &quot;/formtest&quot;, /* mountpoint in URL namespace on this vhost */</div><div class="line"> &quot;protocol-post-demo&quot;, /* handler */</div><div class="line"> NULL, /* default filename if none given */</div><div class="line"> NULL,</div><div class="line"> 0,</div><div class="line"> 0,</div><div class="line"> 0,</div><div class="line"> 0,</div><div class="line"> 0,</div><div class="line"> LWSMPRO_CALLBACK, /* origin points to a callback */</div><div class="line"> 9, /* strlen(&quot;/formtest&quot;), ie length of the mountpoint */</div><div class="line">};</div></div><!-- fragment --><p>Client access to /formtest[anything] will be passed to the callback registered with the named protocol, which in this case is provided by a protocol plugin.</p>
<p>Access by all methods, eg, GET and POST are handled by the callback.</p>
<p>protocol-post-demo deals with accepting and responding to the html form that is in the test server HTML.</p>
<p>When a connection accesses a URL related to a CALLBACK type mount, the connection protocol is changed until the next access on the connection to a URL outside the same CALLBACK mount area. User space on the connection is arranged to be the size of the new protocol user space allocation as given in the protocol struct.</p>
<p>This allocation is only deleted / replaced when the connection accesses a URL region with a different protocol (or the default protocols[0] if no CALLBACK area matches it).</p>
<h1><a class="anchor" id="dim"></a>
Dimming webpage when connection lost</h1>
<p>The lws test plugins' html provides useful feedback on the webpage about if it is still connected to the server, by greying out the page if not. You can also add this to your own html easily</p>
<ul>
<li><p class="startli">include lws-common.js from your HEAD section</p>
<p class="startli">&lt;script src="/lws-common.js"&gt;&lt;/script&gt;</p>
</li>
<li><p class="startli">dim the page during initialization, in a script section on your page</p>
<p class="startli">lws_gray_out(true,{'zindex':'499'});</p>
</li>
<li><p class="startli">in your ws onOpen(), remove the dimming</p>
<p class="startli">lws_gray_out(false);</p>
</li>
<li><p class="startli">in your ws onClose(), reapply the dimming</p>
<p class="startli">lws_gray_out(true,{'zindex':'499'}); </p>
</li>
</ul>
</div></div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.12 </li>
</ul>
</div>
</body>
</html>