Enable LWS_WITH_SERVER_STATUS option
[platform/upstream/libwebsockets.git] / README.coding.md
1 Notes about coding with lws
2 ===========================
3
4 @section dae Daemonization
5
6 There's a helper api `lws_daemonize` built by default that does everything you
7 need to daemonize well, including creating a lock file.  If you're making
8 what's basically a daemon, just call this early in your init to fork to a
9 headless background process and exit the starting process.
10
11 Notice stdout, stderr, stdin are all redirected to /dev/null to enforce your
12 daemon is headless, so you'll need to sort out alternative logging, by, eg,
13 syslog.
14
15
16 @section conns Maximum number of connections
17
18 The maximum number of connections the library can deal with is decided when
19 it starts by querying the OS to find out how many file descriptors it is
20 allowed to open (1024 on Fedora for example).  It then allocates arrays that
21 allow up to that many connections, minus whatever other file descriptors are
22 in use by the user code.
23
24 If you want to restrict that allocation, or increase it, you can use ulimit or
25 similar to change the available number of file descriptors, and when restarted
26 **libwebsockets** will adapt accordingly.
27
28
29 @section evtloop Libwebsockets is singlethreaded
30
31 Libwebsockets works in a serialized event loop, in a single thread.
32
33 Directly performing websocket actions from other threads is not allowed.
34 Aside from the internal data being inconsistent in `forked()` processes,
35 the scope of a `wsi` (`struct websocket`) can end at any time during service
36 with the socket closing and the `wsi` freed.
37
38 Websocket write activities should only take place in the
39 `LWS_CALLBACK_SERVER_WRITEABLE` callback as described below.
40
41 [This network-programming necessity to link the issue of new data to
42 the peer taking the previous data is not obvious to all users so let's
43 repeat that in other words:
44
45 ***ONLY DO LWS_WRITE FROM THE WRITEABLE CALLBACK***
46
47 There is another network-programming truism that surprises some people which
48 is if the sink for the data cannot accept more:
49
50 ***YOU MUST PERFORM RX FLOW CONTROL***
51
52 See the mirror protocol implementations for example code.
53
54 Only live connections appear in the user callbacks, so this removes any
55 possibility of trying to used closed and freed wsis.
56
57 If you need to service other socket or file descriptors as well as the
58 websocket ones, you can combine them together with the websocket ones
59 in one poll loop, see "External Polling Loop support" below, and
60 still do it all in one thread / process context.
61
62 If you insist on trying to use it from multiple threads, take special care if
63 you might simultaneously create more than one context from different threads.
64
65 SSL_library_init() is called from the context create api and it also is not
66 reentrant.  So at least create the contexts sequentially.
67
68
69 @section writeable Only send data when socket writeable
70
71 You should only send data on a websocket connection from the user callback
72 `LWS_CALLBACK_SERVER_WRITEABLE` (or `LWS_CALLBACK_CLIENT_WRITEABLE` for
73 clients).
74
75 If you want to send something, do not just send it but request a callback
76 when the socket is writeable using
77
78  - `lws_callback_on_writable(context, wsi)` for a specific `wsi`, or
79  
80  - `lws_callback_on_writable_all_protocol(protocol)` for all connections
81 using that protocol to get a callback when next writeable.
82
83 Usually you will get called back immediately next time around the service
84 loop, but if your peer is slow or temporarily inactive the callback will be
85 delayed accordingly.  Generating what to write and sending it should be done
86 in the ...WRITEABLE callback.
87
88 See the test server code for an example of how to do this.
89
90
91 @section otherwr Do not rely on only your own WRITEABLE requests appearing
92
93 Libwebsockets may generate additional `LWS_CALLBACK_CLIENT_WRITEABLE` events
94 if it met network conditions where it had to buffer your send data internally.
95
96 So your code for `LWS_CALLBACK_CLIENT_WRITEABLE` needs to own the decision
97 about what to send, it can't assume that just because the writeable callback
98 came it really is time to send something.
99
100 It's quite possible you get an 'extra' writeable callback at any time and
101 just need to `return 0` and wait for the expected callback later.
102
103
104 @section closing Closing connections from the user side
105
106 When you want to close a connection, you do it by returning `-1` from a
107 callback for that connection.
108
109 You can provoke a callback by calling `lws_callback_on_writable` on
110 the wsi, then notice in the callback you want to close it and just return -1.
111 But usually, the decision to close is made in a callback already and returning
112 -1 is simple.
113
114 If the socket knows the connection is dead, because the peer closed or there
115 was an affirmitive network error like a FIN coming, then **libwebsockets**  will
116 take care of closing the connection automatically.
117
118 If you have a silently dead connection, it's possible to enter a state where
119 the send pipe on the connection is choked but no ack will ever come, so the
120 dead connection will never become writeable.  To cover that, you can use TCP
121 keepalives (see later in this document) or pings.
122
123 @section gzip Serving from inside a zip file
124
125 Lws now supports serving gzipped files from inside a zip container.  Thanks to
126 Per Bothner for contributing the code.
127
128 This has the advtantage that if the client can accept GZIP encoding, lws can
129 simply send the gzip-compressed file from inside the zip file with no further
130 processing, saving time and bandwidth.
131
132 In the case the client can't understand gzip compression, lws automatically
133 decompressed the file and sends it normally.
134
135 Clients with limited storage and RAM will find this useful; the memory needed
136 for the inflate case is constrained so that only one input buffer at a time
137 is ever in memory.
138
139 To use this feature, ensure LWS_WITH_ZIP_FOPS is enabled at CMake (it is by
140 default).
141
142 `libwebsockets-test-server-v2.0` includes a mount using this technology
143 already, run that test server and navigate to http://localhost:7681/ziptest/candide.html
144
145 This will serve the book Candide in html, together with two jpgs, all from
146 inside a .zip file in /usr/[local/]share-libwebsockets-test-server/candide.zip
147
148 Usage is otherwise automatic, if you arrange a mount that points to the zipfile,
149 eg, "/ziptest" -> "mypath/test.zip", then URLs like `/ziptest/index.html` will be
150 servied from `index.html` inside `mypath/test.zip`
151
152 @section frags Fragmented messages
153
154 To support fragmented messages you need to check for the final
155 frame of a message with `lws_is_final_fragment`. This
156 check can be combined with `libwebsockets_remaining_packet_payload`
157 to gather the whole contents of a message, eg:
158
159 ```
160             case LWS_CALLBACK_RECEIVE:
161             {
162                 Client * const client = (Client *)user;
163                 const size_t remaining = lws_remaining_packet_payload(wsi);
164         
165                 if (!remaining && lws_is_final_fragment(wsi)) {
166                     if (client->HasFragments()) {
167                         client->AppendMessageFragment(in, len, 0);
168                         in = (void *)client->GetMessage();
169                         len = client->GetMessageLength();
170                     }
171         
172                     client->ProcessMessage((char *)in, len, wsi);
173                     client->ResetMessage();
174                 } else
175                     client->AppendMessageFragment(in, len, remaining);
176             }
177             break;
178 ```
179
180 The test app libwebsockets-test-fraggle sources also show how to
181 deal with fragmented messages.
182
183
184 @section debuglog Debug Logging
185
186 Also using `lws_set_log_level` api you may provide a custom callback to actually
187 emit the log string.  By default, this points to an internal emit function
188 that sends to stderr.  Setting it to `NULL` leaves it as it is instead.
189
190 A helper function `lwsl_emit_syslog()` is exported from the library to simplify
191 logging to syslog.  You still need to use `setlogmask`, `openlog` and `closelog`
192 in your user code.
193
194 The logging apis are made available for user code.
195
196 - `lwsl_err(...)`
197 - `lwsl_warn(...)`
198 - `lwsl_notice(...)`
199 - `lwsl_info(...)`
200 - `lwsl_debug(...)`
201
202 The difference between notice and info is that notice will be logged by default
203 whereas info is ignored by default.
204
205 If you are not building with _DEBUG defined, ie, without this
206
207 ```
208         $ cmake .. -DCMAKE_BUILD_TYPE=DEBUG
209 ```
210
211 then log levels below notice do not actually get compiled in.
212
213
214
215 @section extpoll External Polling Loop support
216
217 **libwebsockets** maintains an internal `poll()` array for all of its
218 sockets, but you can instead integrate the sockets into an
219 external polling array.  That's needed if **libwebsockets** will
220 cooperate with an existing poll array maintained by another
221 server.
222
223 Four callbacks `LWS_CALLBACK_ADD_POLL_FD`, `LWS_CALLBACK_DEL_POLL_FD`,
224 `LWS_CALLBACK_SET_MODE_POLL_FD` and `LWS_CALLBACK_CLEAR_MODE_POLL_FD`
225 appear in the callback for protocol 0 and allow interface code to
226 manage socket descriptors in other poll loops.
227
228 You can pass all pollfds that need service to `lws_service_fd()`, even
229 if the socket or file does not belong to **libwebsockets** it is safe.
230
231 If **libwebsocket** handled it, it zeros the pollfd `revents` field before returning.
232 So you can let **libwebsockets** try and if `pollfd->revents` is nonzero on return,
233 you know it needs handling by your code.
234
235 Also note that when integrating a foreign event loop like libev or libuv where
236 it doesn't natively use poll() semantics, and you must return a fake pollfd
237 reflecting the real event:
238
239  - be sure you set .events to .revents value as well in the synthesized pollfd
240
241  - check the built-in support for the event loop if possible (eg, ./lib/libuv.c)
242    to see how it interfaces to lws
243    
244  - use LWS_POLLHUP / LWS_POLLIN / LWS_POLLOUT from libwebsockets.h to avoid
245    losing windows compatibility
246
247
248 @section cpp Using with in c++ apps
249
250 The library is ready for use by C++ apps.  You can get started quickly by
251 copying the test server
252
253 ```
254         $ cp test-server/test-server.c test.cpp
255 ```
256
257 and building it in C++ like this
258
259 ```
260         $ g++ -DINSTALL_DATADIR=\"/usr/share\" -ocpptest test.cpp -lwebsockets
261 ```
262
263 `INSTALL_DATADIR` is only needed because the test server uses it as shipped, if
264 you remove the references to it in your app you don't need to define it on
265 the g++ line either.
266
267
268 @section headerinfo Availability of header information
269
270 HTTP Header information is managed by a pool of "ah" structs.  These are a
271 limited resource so there is pressure to free the headers and return the ah to
272 the pool for reuse.
273
274 For that reason header information on HTTP connections that get upgraded to
275 websockets is lost after the ESTABLISHED callback.  Anything important that
276 isn't processed by user code before then should be copied out for later.
277
278 For HTTP connections that don't upgrade, header info remains available the
279 whole time.
280
281
282 @section ka TCP Keepalive
283
284 It is possible for a connection which is not being used to send to die
285 silently somewhere between the peer and the side not sending.  In this case
286 by default TCP will just not report anything and you will never get any more
287 incoming data or sign the link is dead until you try to send.
288
289 To deal with getting a notification of that situation, you can choose to
290 enable TCP keepalives on all **libwebsockets** sockets, when you create the
291 context.
292
293 To enable keepalive, set the ka_time member of the context creation parameter
294 struct to a nonzero value (in seconds) at context creation time.  You should
295 also fill ka_probes and ka_interval in that case.
296
297 With keepalive enabled, the TCP layer will send control packets that should
298 stimulate a response from the peer without affecting link traffic.  If the
299 response is not coming, the socket will announce an error at `poll()` forcing
300 a close.
301
302 Note that BSDs don't support keepalive time / probes / interval per-socket
303 like Linux does.  On those systems you can enable keepalive by a nonzero
304 value in `ka_time`, but the systemwide kernel settings for the time / probes/
305 interval are used, regardless of what nonzero value is in `ka_time`.
306
307
308 @section sslopt Optimizing SSL connections
309
310 There's a member `ssl_cipher_list` in the `lws_context_creation_info` struct
311 which allows the user code to restrict the possible cipher selection at
312 context-creation time.
313
314 You might want to look into that to stop the ssl peers selecting a cipher which
315 is too computationally expensive.  To use it, point it to a string like
316
317         `"RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL"`
318
319 if left `NULL`, then the "DEFAULT" set of ciphers are all possible to select.
320
321 You can also set it to `"ALL"` to allow everything (including insecure ciphers).
322
323
324 @section clientasync Async nature of client connections
325
326 When you call `lws_client_connect_info(..)` and get a `wsi` back, it does not
327 mean your connection is active.  It just means it started trying to connect.
328
329 Your client connection is actually active only when you receive
330 `LWS_CALLBACK_CLIENT_ESTABLISHED` for it.
331
332 There's a 5 second timeout for the connection, and it may give up or die for
333 other reasons, if any of that happens you'll get a
334 `LWS_CALLBACK_CLIENT_CONNECTION_ERROR` callback on protocol 0 instead for the
335 `wsi`.
336
337 After attempting the connection and getting back a non-`NULL` `wsi` you should
338 loop calling `lws_service()` until one of the above callbacks occurs.
339
340 As usual, see [test-client.c](test-server/test-client.c) for example code.
341
342 Notice that the client connection api tries to progress the connection
343 somewhat before returning.  That means it's possible to get callbacks like
344 CONNECTION_ERROR on the new connection before your user code had a chance to
345 get the wsi returned to identify it (in fact if the connection did fail early,
346 NULL will be returned instead of the wsi anyway).
347
348 To avoid that problem, you can fill in `pwsi` in the client connection info
349 struct to point to a struct lws that get filled in early by the client
350 connection api with the related wsi.  You can then check for that in the
351 callback to confirm the identity of the failing client connection.
352
353
354 @section fileapi Lws platform-independent file access apis
355
356 lws now exposes his internal platform file abstraction in a way that can be
357 both used by user code to make it platform-agnostic, and be overridden or
358 subclassed by user code.  This allows things like handling the URI "directory
359 space" as a virtual filesystem that may or may not be backed by a regular
360 filesystem.  One example use is serving files from inside large compressed
361 archive storage without having to unpack anything except the file being
362 requested.
363
364 The test server shows how to use it, basically the platform-specific part of
365 lws prepares a file operations structure that lives in the lws context.
366
367 The user code can get a pointer to the file operations struct
368
369 ```
370         LWS_VISIBLE LWS_EXTERN struct lws_plat_file_ops *
371                 `lws_get_fops`(struct lws_context *context);
372 ```
373
374 and then can use helpers to also leverage these platform-independent
375 file handling apis
376
377 ```
378         lws_fop_fd_t
379         `lws_plat_file_open`(struct lws_plat_file_ops *fops, const char *filename,
380                            lws_fop_flags_t *flags)
381         int
382         `lws_plat_file_close`(lws_fop_fd_t fop_fd)
383
384         unsigned long
385         `lws_plat_file_seek_cur`(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
386
387         int
388         `lws_plat_file_read`(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
389                    uint8_t *buf, lws_filepos_t len)
390
391         int
392         `lws_plat_file_write`(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
393                    uint8_t *buf, lws_filepos_t len )
394 ```
395
396 Generic helpers are provided which provide access to generic fops information or
397 call through to the above fops
398
399 ```
400 lws_filepos_t
401 lws_vfs_tell(lws_fop_fd_t fop_fd);
402
403 lws_filepos_t
404 lws_vfs_get_length(lws_fop_fd_t fop_fd);
405
406 uint32_t
407 lws_vfs_get_mod_time(lws_fop_fd_t fop_fd);
408
409 lws_fileofs_t
410 lws_vfs_file_seek_set(lws_fop_fd_t fop_fd, lws_fileofs_t offset);
411
412 lws_fileofs_t
413 lws_vfs_file_seek_end(lws_fop_fd_t fop_fd, lws_fileofs_t offset);
414 ```
415
416
417 The user code can also override or subclass the file operations, to either
418 wrap or replace them.  An example is shown in test server.
419
420 ### Changes from v2.1 and before fops
421
422 There are several changes:
423
424 1) Pre-2.2 fops directly used platform file descriptors.  Current fops returns and accepts a wrapper type lws_fop_fd_t which is a pointer to a malloc'd struct containing information specific to the filesystem implementation.
425
426 2) Pre-2.2 fops bound the fops to a wsi.  This is completely removed, you just give a pointer to the fops struct that applies to this file when you open it.  Afterwards, the operations in the fops just need the lws_fop_fd_t returned from the open.
427
428 3) Everything is wrapped in typedefs.  See lws-plat-unix.c for examples of how to implement.
429
430 4) Position in the file, File Length, and a copy of Flags left after open are now generically held in the fop_fd.
431 VFS implementation must set and manage this generic information now.  See the implementations in lws-plat-unix.c for
432 examples.
433
434 5) The file length is no longer set at a pointer provided by the open() fop.  The api `lws_vfs_get_length()` is provided to
435 get the file length after open.
436
437 6) If your file namespace is virtual, ie, is not reachable by platform fops directly, you must set LWS_FOP_FLAG_VIRTUAL
438 on the flags during open.
439
440 7) There is an optional `mod_time` uint32_t member in the generic fop_fd.  If you are able to set it during open, you
441 should indicate it by setting `LWS_FOP_FLAG_MOD_TIME_VALID` on the flags.
442
443 @section rawfd RAW file descriptor polling
444
445 LWS allows you to include generic platform file descriptors in the lws service / poll / event loop.
446
447 Open your fd normally and then
448
449 ```
450         lws_sock_file_fd_type u;
451
452         u.filefd = your_open_file_fd;
453
454         if (!lws_adopt_descriptor_vhost(vhost, 0, u,
455                                         "protocol-name-to-bind-to",
456                                         optional_wsi_parent_or_NULL)) {
457                 // failed
458         }
459
460         // OK
461 ```
462
463 A wsi is created for the file fd that acts like other wsi, you will get these
464 callbacks on the named protocol
465
466 ```
467         LWS_CALLBACK_RAW_ADOPT_FILE
468         LWS_CALLBACK_RAW_RX_FILE
469         LWS_CALLBACK_RAW_WRITEABLE_FILE
470         LWS_CALLBACK_RAW_CLOSE_FILE
471 ```
472
473 starting with LWS_CALLBACK_RAW_ADOPT_FILE.
474
475 `protocol-lws-raw-test` plugin provides a method for testing this with
476 `libwebsockets-test-server-v2.0`:
477
478 The plugin creates a FIFO on your system called "/tmp/lws-test-raw"
479
480 You can feed it data through the FIFO like this
481
482 ```
483   $ sudo sh -c "echo hello > /tmp/lws-test-raw"
484 ```
485
486 This plugin simply prints the data.  But it does it through the lws event
487 loop / service poll.
488
489 @section rawsrvsocket RAW server socket descriptor polling
490
491 You can also enable your vhost to accept RAW socket connections, in addition to
492 HTTP[s] and WS[s].  If the first bytes written on the connection are not a
493 valid HTTP method, then the connection switches to RAW mode.
494
495 This is disabled by default, you enable it by setting the `.options` flag
496 LWS_SERVER_OPTION_FALLBACK_TO_RAW when creating the vhost.
497
498 RAW mode socket connections receive the following callbacks
499
500 ```
501         LWS_CALLBACK_RAW_ADOPT
502         LWS_CALLBACK_RAW_RX
503         LWS_CALLBACK_RAW_WRITEABLE
504         LWS_CALLBACK_RAW_CLOSE
505 ```
506
507 You can control which protocol on your vhost handles these RAW mode
508 incoming connections by marking the selected protocol with a pvo `raw`, eg
509
510 ```
511         "protocol-lws-raw-test": {
512                  "status": "ok",
513                  "raw": "1"
514         },
515 ```
516
517 The "raw" pvo marks this protocol as being used for RAW connections.
518
519 `protocol-lws-raw-test` plugin provides a method for testing this with
520 `libwebsockets-test-server-v2.0`:
521
522 Run libwebsockets-test-server-v2.0 and connect to it by telnet, eg
523
524 ```
525     $ telnet 127.0.0.1 7681
526 ```
527
528 type something that isn't a valid HTTP method and enter, before the
529 connection times out.  The connection will switch to RAW mode using this
530 protocol, and pass the unused rx as a raw RX callback.
531     
532 The test protocol echos back what was typed on telnet to telnet.
533
534 @section rawclientsocket RAW client socket descriptor polling
535
536 You can now also open RAW socket connections in client mode.
537
538 Follow the usual method for creating a client connection, but set the
539 `info.method` to "RAW".  When the connection is made, the wsi will be
540 converted to RAW mode and operate using the same callbacks as the
541 server RAW sockets described above.
542
543 The libwebsockets-test-client supports this using raw:// URLS.  To
544 test, open a netcat listener in one window
545
546 ```
547  $ nc -l 9999
548 ```
549
550 and in another window, connect to it using the test client
551
552 ```
553  $ libwebsockets-test-client raw://127.0.0.1:9999
554 ```
555
556 The connection should succeed, and text typed in the netcat window (including a CRLF)
557 will be received in the client.
558
559 @section ecdh ECDH Support
560
561 ECDH Certs are now supported.  Enable the CMake option
562
563         cmake .. -DLWS_SSL_SERVER_WITH_ECDH_CERT=1 
564
565 **and** the info->options flag
566
567         LWS_SERVER_OPTION_SSL_ECDH
568
569 to build in support and select it at runtime.
570
571 @section sslinfo SSL info callbacks
572
573 OpenSSL allows you to receive callbacks for various events defined in a
574 bitmask in openssl/ssl.h.  The events include stuff like TLS Alerts.
575
576 By default, lws doesn't register for these callbacks.
577
578 However if you set the info.ssl_info_event_mask to nonzero (ie, set some
579 of the bits in it like `SSL_CB_ALERT` at vhost creation time, then
580 connections to that vhost will call back using LWS_CALLBACK_SSL_INFO
581 for the wsi, and the `in` parameter will be pointing to a struct of
582 related args:
583
584 ```
585 struct lws_ssl_info {
586         int where;
587         int ret;
588 };
589 ```
590
591 The default callback handler in lws has a handler for LWS_CALLBACK_SSL_INFO
592 which prints the related information,  You can test it using the switch
593 -S -s  on `libwebsockets-test-server-v2.0`.
594
595 Returning nonzero from the callback will close the wsi.
596
597 @section smp SMP / Multithreaded service
598
599 SMP support is integrated into LWS without any internal threading.  It's
600 very simple to use, libwebsockets-test-server-pthread shows how to do it,
601 use -j <n> argument there to control the number of service threads up to 32.
602
603 Two new members are added to the info struct
604
605         unsigned int count_threads;
606         unsigned int fd_limit_per_thread;
607         
608 leave them at the default 0 to get the normal singlethreaded service loop.
609
610 Set count_threads to n to tell lws you will have n simultaneous service threads
611 operating on the context.
612
613 There is still a single listen socket on one port, no matter how many
614 service threads.
615
616 When a connection is made, it is accepted by the service thread with the least
617 connections active to perform load balancing.
618
619 The user code is responsible for spawning n threads running the service loop
620 associated to a specific tsi (Thread Service Index, 0 .. n - 1).  See
621 the libwebsockets-test-server-pthread for how to do.
622
623 If you leave fd_limit_per_thread at 0, then the process limit of fds is shared
624 between the service threads; if you process was allowed 1024 fds overall then
625 each thread is limited to 1024 / n.
626
627 You can set fd_limit_per_thread to a nonzero number to control this manually, eg
628 the overall supported fd limit is less than the process allowance.
629
630 You can control the context basic data allocation for multithreading from Cmake
631 using -DLWS_MAX_SMP=, if not given it's set to 32.  The serv_buf allocation
632 for the threads (currently 4096) is made at runtime only for active threads.
633
634 Because lws will limit the requested number of actual threads supported
635 according to LWS_MAX_SMP, there is an api lws_get_count_threads(context) to
636 discover how many threads were actually allowed when the context was created.
637
638 It's required to implement locking in the user code in the same way that
639 libwebsockets-test-server-pthread does it, for the FD locking callbacks.
640
641 There is no knowledge or dependency in lws itself about pthreads.  How the
642 locking is implemented is entirely up to the user code.
643
644
645 @section libevuv Libev / Libuv support
646
647 You can select either or both
648
649         -DLWS_WITH_LIBEV=1
650         -DLWS_WITH_LIBUV=1
651
652 at cmake configure-time.  The user application may use one of the
653 context init options flags
654
655         LWS_SERVER_OPTION_LIBEV
656         LWS_SERVER_OPTION_LIBUV
657
658 to indicate it will use either of the event libraries.
659
660
661 @section extopts Extension option control from user code
662
663 User code may set per-connection extension options now, using a new api
664 `lws_set_extension_option()`.
665
666 This should be called from the ESTABLISHED callback like this
667 ```
668          lws_set_extension_option(wsi, "permessage-deflate",
669                                   "rx_buf_size", "12"); /* 1 << 12 */
670 ```
671
672 If the extension is not active (missing or not negotiated for the
673 connection, or extensions are disabled on the library) the call is
674 just returns -1.  Otherwise the connection's extension has its
675 named option changed.
676
677 The extension may decide to alter or disallow the change, in the
678 example above permessage-deflate restricts the size of his rx
679 output buffer also considering the protocol's rx_buf_size member.
680
681
682 @section httpsclient Client connections as HTTP[S] rather than WS[S]
683
684 You may open a generic http client connection using the same
685 struct lws_client_connect_info used to create client ws[s]
686 connections.
687
688 To stay in http[s], set the optional info member "method" to
689 point to the string "GET" instead of the default NULL.
690
691 After the server headers are processed, when payload from the
692 server is available the callback LWS_CALLBACK_RECEIVE_CLIENT_HTTP
693 will be made.
694
695 You can choose whether to process the data immediately, or
696 queue a callback when an outgoing socket is writeable to provide
697 flow control, and process the data in the writable callback.
698
699 Either way you use the api `lws_http_client_read()` to access the
700 data, eg
701
702 ```
703         case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:
704                 {
705                         char buffer[1024 + LWS_PRE];
706                         char *px = buffer + LWS_PRE;
707                         int lenx = sizeof(buffer) - LWS_PRE;
708
709                         lwsl_notice("LWS_CALLBACK_RECEIVE_CLIENT_HTTP\n");
710
711                         /*
712                          * Often you need to flow control this by something
713                          * else being writable.  In that case call the api
714                          * to get a callback when writable here, and do the
715                          * pending client read in the writeable callback of
716                          * the output.
717                          */
718                         if (lws_http_client_read(wsi, &px, &lenx) < 0)
719                                 return -1;
720                         while (lenx--)
721                                 putchar(*px++);
722                 }
723                 break;
724 ```
725
726 Notice that if you will use SSL client connections on a vhost, you must
727 prepare the client SSL context for the vhost after creating the vhost, since
728 this is not normally done if the vhost was set up to listen / serve.  Call
729 the api lws_init_vhost_client_ssl() to also allow client SSL on the vhost.
730
731
732
733 @section vhosts Using lws vhosts
734
735 If you set LWS_SERVER_OPTION_EXPLICIT_VHOSTS options flag when you create
736 your context, it won't create a default vhost using the info struct
737 members for compatibility.  Instead you can call lws_create_vhost()
738 afterwards to attach one or more vhosts manually.
739
740 ```
741         LWS_VISIBLE struct lws_vhost *
742         lws_create_vhost(struct lws_context *context,
743                          struct lws_context_creation_info *info);
744 ```
745
746 lws_create_vhost() uses the same info struct as lws_create_context(),
747 it ignores members related to context and uses the ones meaningful
748 for vhost (marked with VH in libwebsockets.h).
749
750 ```
751         struct lws_context_creation_info {
752                 int port;                                       /* VH */
753                 const char *iface;                              /* VH */
754                 const struct lws_protocols *protocols;          /* VH */
755                 const struct lws_extension *extensions;         /* VH */
756         ...
757 ```
758
759 When you attach the vhost, if the vhost's port already has a listen socket
760 then both vhosts share it and use SNI (is SSL in use) or the Host: header
761 from the client to select the right one.  Or if no other vhost already
762 listening the a new listen socket is created.
763
764 There are some new members but mainly it's stuff you used to set at
765 context creation time.
766
767
768 @section sni How lws matches hostname or SNI to a vhost
769
770 LWS first strips any trailing :port number.
771
772 Then it tries to find an exact name match for a vhost listening on the correct
773 port, ie, if SNI or the Host: header provided abc.com:1234, it will match on a
774 vhost named abc.com that is listening on port 1234.
775
776 If there is no exact match, lws will consider wildcard matches, for example
777 if cats.abc.com:1234 is provided by the client by SNI or Host: header, it will
778 accept a vhost "abc.com" listening on port 1234.  If there was a better, exact,
779 match, it will have been chosen in preference to this.
780
781 Connections with SSL will still have the client go on to check the
782 certificate allows wildcards and error out if not.
783  
784
785
786 @section mounts Using lws mounts on a vhost
787
788 The last argument to lws_create_vhost() lets you associate a linked
789 list of lws_http_mount structures with that vhost's URL 'namespace', in
790 a similar way that unix lets you mount filesystems into areas of your /
791 filesystem how you like and deal with the contents transparently.
792
793 ```
794         struct lws_http_mount {
795                 struct lws_http_mount *mount_next;
796                 const char *mountpoint; /* mountpoint in http pathspace, eg, "/" */
797                 const char *origin; /* path to be mounted, eg, "/var/www/warmcat.com" */
798                 const char *def; /* default target, eg, "index.html" */
799         
800                 struct lws_protocol_vhost_options *cgienv;
801         
802                 int cgi_timeout;
803                 int cache_max_age;
804         
805                 unsigned int cache_reusable:1;
806                 unsigned int cache_revalidate:1;
807                 unsigned int cache_intermediaries:1;
808         
809                 unsigned char origin_protocol;
810                 unsigned char mountpoint_len;
811         };
812 ```
813
814 The last mount structure should have a NULL mount_next, otherwise it should
815 point to the 'next' mount structure in your list.
816
817 Both the mount structures and the strings must persist until the context is
818 destroyed, since they are not copied but used in place.
819
820 `.origin_protocol` should be one of
821
822 ```
823         enum {
824                 LWSMPRO_HTTP,
825                 LWSMPRO_HTTPS,
826                 LWSMPRO_FILE,
827                 LWSMPRO_CGI,
828                 LWSMPRO_REDIR_HTTP,
829                 LWSMPRO_REDIR_HTTPS,
830                 LWSMPRO_CALLBACK,
831         };
832 ```
833
834  - LWSMPRO_FILE is used for mapping url namespace to a filesystem directory and
835 serve it automatically.
836
837  - LWSMPRO_CGI associates the url namespace with the given CGI executable, which
838 runs when the URL is accessed and the output provided to the client.
839
840  - LWSMPRO_REDIR_HTTP and LWSMPRO_REDIR_HTTPS auto-redirect clients to the given
841 origin URL.
842
843  - LWSMPRO_CALLBACK causes the http connection to attach to the callback
844 associated with the named protocol (which may be a plugin).
845
846
847 @section mountcallback Operation of LWSMPRO_CALLBACK mounts
848
849 The feature provided by CALLBACK type mounts is binding a part of the URL
850 namespace to a named protocol callback handler.
851
852 This allows protocol plugins to handle areas of the URL namespace.  For example
853 in test-server-v2.0.c, the URL area "/formtest" is associated with the plugin
854 providing "protocol-post-demo" like this
855
856 ```
857         static const struct lws_http_mount mount_post = {
858                 NULL,           /* linked-list pointer to next*/
859                 "/formtest",            /* mountpoint in URL namespace on this vhost */
860                 "protocol-post-demo",   /* handler */
861                 NULL,   /* default filename if none given */
862                 NULL,
863                 0,
864                 0,
865                 0,
866                 0,
867                 0,
868                 LWSMPRO_CALLBACK,       /* origin points to a callback */
869                 9,                      /* strlen("/formtest"), ie length of the mountpoint */
870         };
871 ```
872
873 Client access to /formtest[anything] will be passed to the callback registered
874 with the named protocol, which in this case is provided by a protocol plugin.
875
876 Access by all methods, eg, GET and POST are handled by the callback.
877
878 protocol-post-demo deals with accepting and responding to the html form that
879 is in the test server HTML.
880
881 When a connection accesses a URL related to a CALLBACK type mount, the
882 connection protocol is changed until the next access on the connection to a
883 URL outside the same CALLBACK mount area.  User space on the connection is
884 arranged to be the size of the new protocol user space allocation as given in
885 the protocol struct.
886
887 This allocation is only deleted / replaced when the connection accesses a
888 URL region with a different protocol (or the default protocols[0] if no
889 CALLBACK area matches it).
890
891 @section BINDTODEV SO_BIND_TO_DEVICE
892
893 The .bind_iface flag in the context / vhost creation struct lets you
894 declare that you want all traffic for listen and transport on that
895 vhost to be strictly bound to the network interface named in .iface.
896
897 This Linux-only feature requires SO_BIND_TO_DEVICE, which in turn
898 requires CAP_NET_RAW capability... root has this capability.
899
900 However this feature needs to apply the binding also to accepted
901 sockets during normal operation, which implies the server must run
902 the whole time as root.
903
904 You can avoid this by using the Linux capabilities feature to have
905 the unprivileged user inherit just the CAP_NET_RAW capability.
906
907 You can confirm this with the test server
908
909
910 ```
911  $ sudo /usr/local/bin/libwebsockets-test-server -u agreen -i eno1 -k
912 ```
913
914 The part that ensures the capability is inherited by the unprivileged
915 user is
916
917 ```
918 #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
919                         info.caps[0] = CAP_NET_RAW;
920                         info.count_caps = 1;
921 #endif
922 ```
923
924
925 @section dim Dimming webpage when connection lost
926
927 The lws test plugins' html provides useful feedback on the webpage about if it
928 is still connected to the server, by greying out the page if not.  You can
929 also add this to your own html easily
930
931  - include lws-common.js from your HEAD section
932  
933    <script src="/lws-common.js"></script>
934    
935  - dim the page during initialization, in a script section on your page
936  
937    lws_gray_out(true,{'zindex':'499'});
938    
939  - in your ws onOpen(), remove the dimming
940  
941    lws_gray_out(false);
942    
943  - in your ws onClose(), reapply the dimming
944  
945    lws_gray_out(true,{'zindex':'499'});