lws_plat_service_tsi: accessing context before checking for NULL
[platform/upstream/libwebsockets.git] / README.lwsws.md
1 Notes about lwsws
2 =================
3
4 @section lwsws Libwebsockets Web Server
5
6 lwsws is an implementation of a very lightweight, ws-capable generic web
7 server, which uses libwebsockets to implement everything underneath.
8
9 If you are basically implementing a standalone server with lws, you can avoid
10 reinventing the wheel and use a debugged server including lws.
11
12
13 @section lwswsb Build
14
15 Just enable -DLWS_WITH_LWSWS=1 at cmake-time.
16
17 It enables libuv and plugin support automatically.
18
19 NOTICE on Ubuntu, the default libuv package is called "libuv-0.10".  This is ancient.
20
21 You should replace this with libuv1 and libuv1-dev before proceeding.
22
23 @section lwswsc Lwsws Configuration
24
25 lwsws uses JSON config files, they're pure JSON except:
26
27  - '#' may be used to turn the rest of the line into a comment.
28
29  - There's also a single substitution, if a string contains "_lws_ddir_", then that is
30 replaced with the LWS install data directory path, eg, "/usr/share" or whatever was
31 set when LWS was built + installed.  That lets you refer to installed paths without
32 having to change the config if your install path was different.
33
34 There is a single file intended for global settings
35
36 /etc/lwsws/conf
37 ```
38         # these are the server global settings
39         # stuff related to vhosts should go in one
40         # file per vhost in ../conf.d/
41
42         {
43           "global": {
44            "uid": "48",  # apache user
45            "gid": "48",  # apache user
46            "count-threads": "1",
47            "server-string": "myserver v1", # returned in http headers
48            "ws-pingpong-secs": "200", # confirm idle established ws connections this often
49            "init-ssl": "yes"
50          }
51         }
52 ```
53 and a config directory intended to take one file per vhost
54
55 /etc/lwsws/conf.d/warmcat.com
56 ```
57         {
58                 "vhosts": [{
59                         "name": "warmcat.com",
60                         "port": "443",
61                         "interface": "eth0",  # optional
62                         "host-ssl-key": "/etc/pki/tls/private/warmcat.com.key",  # if given enable ssl
63                         "host-ssl-cert": "/etc/pki/tls/certs/warmcat.com.crt",
64                         "host-ssl-ca": "/etc/pki/tls/certs/warmcat.com.cer",
65                         "mounts": [{  # autoserve
66                                 "mountpoint": "/",
67                                 "origin": "file:///var/www/warmcat.com",
68                                 "default": "index.html"
69                         }]
70                 }]
71         }
72 ```
73 To get started quickly, an example config reproducing the old test server
74 on port 7681, non-SSL is provided.  To set it up
75 ```
76         # mkdir -p /etc/lwsws/conf.d /var/log/lwsws
77         # cp ./lwsws/etc-lwsws-conf-EXAMPLE /etc/lwsws/conf
78         # cp ./lwsws/etc-lwsws-conf.d-localhost-EXAMPLE /etc/lwsws/conf.d/test-server
79         # sudo lwsws
80 ```
81
82 @section lwsogo Other Global Options
83
84  - `reject-service-keywords` allows you to return an HTTP error code and message of your choice
85 if a keyword is found in the user agent
86
87 ```
88    "reject-service-keywords": [{
89         "scumbot": "404 Not Found"
90    }]
91 ```
92
93 @section lwswsv Lwsws Vhosts
94
95 One server can run many vhosts, where SSL is in use SNI is used to match
96 the connection to a vhost and its vhost-specific SSL keys during SSL
97 negotiation.
98
99 Listing multiple vhosts looks something like this
100 ```
101         {
102          "vhosts": [ {
103              "name": "localhost",
104              "port": "443",
105              "host-ssl-key":  "/etc/pki/tls/private/libwebsockets.org.key",
106              "host-ssl-cert": "/etc/pki/tls/certs/libwebsockets.org.crt",
107              "host-ssl-ca":   "/etc/pki/tls/certs/libwebsockets.org.cer",
108              "mounts": [{
109                "mountpoint": "/",
110                "origin": "file:///var/www/libwebsockets.org",
111                "default": "index.html"
112                }, {
113                 "mountpoint": "/testserver",
114                 "origin": "file:///usr/local/share/libwebsockets-test-server",
115                 "default": "test.html"
116                }],
117              # which protocols are enabled for this vhost, and optional
118              # vhost-specific config options for the protocol
119              #
120              "ws-protocols": [{
121                "warmcat,timezoom": {
122                  "status": "ok"
123                }
124              }]
125             },
126             {
127             "name": "localhost",
128             "port": "7681",
129              "host-ssl-key":  "/etc/pki/tls/private/libwebsockets.org.key",
130              "host-ssl-cert": "/etc/pki/tls/certs/libwebsockets.org.crt",
131              "host-ssl-ca":   "/etc/pki/tls/certs/libwebsockets.org.cer",
132              "mounts": [{
133                "mountpoint": "/",
134                "origin": ">https://localhost"
135              }]
136            },
137             {
138             "name": "localhost",
139             "port": "80",
140              "mounts": [{
141                "mountpoint": "/",
142                "origin": ">https://localhost"
143              }]
144            }
145         
146           ]
147         }
148 ```
149
150 That sets up three vhosts all called "localhost" on ports 443 and 7681 with SSL, and port 80 without SSL but with a forced redirect to https://localhost
151
152
153 @section lwswsvn Lwsws Vhost name and port sharing
154
155 The vhost name field is used to match on incoming SNI or Host: header, so it
156 must always be the host name used to reach the vhost externally.
157
158  - Vhosts may have the same name and different ports, these will each create a
159 listening socket on the appropriate port.
160
161  - Vhosts may also have the same port and different name: these will be treated as
162 true vhosts on one listening socket and the active vhost decided at SSL
163 negotiation time (via SNI) or if no SSL, then after the Host: header from
164 the client has been parsed.
165
166
167 @section lwswspr Lwsws Protocols
168
169 Vhosts by default have available the union of any initial protocols from context creation time, and
170 any protocols exposed by plugins.
171
172 Vhosts can select which plugins they want to offer and give them per-vhost settings using this syntax
173 ```
174              "ws-protocols": [{
175                "warmcat-timezoom": {
176                  "status": "ok"
177                }
178              }]
179 ```
180
181 The "x":"y" parameters like "status":"ok" are made available to the protocol during its per-vhost
182 LWS_CALLBACK_PROTOCOL_INIT (@in is a pointer to a linked list of struct lws_protocol_vhost_options
183 containing the name and value pointers).
184
185 To indicate that a protocol should be used when no Protocol: header is sent
186 by the client, you can use "default": "1"
187 ```
188              "ws-protocols": [{
189                "warmcat-timezoom": {
190                  "status": "ok",
191                  "default": "1"
192                }
193              }]
194 ```
195
196
197 @section lwswsovo Lwsws Other vhost options
198
199  - If the three options `host-ssl-cert`, `host-ssl-ca` and `host-ssl-key` are given, then the vhost supports SSL.
200
201  Each vhost may have its own certs, SNI is used during the initial connection negotiation to figure out which certs to use by the server name it's asking for from the request DNS name.
202
203  - `keeplive-timeout` (in secs) defaults to 60 for lwsws, it may be set as a vhost option
204
205  - `interface` lets you specify which network interface to listen on, if not given listens on all
206
207  - "`unix-socket`": "1" causes the unix socket specified in the interface option to be used instead of an INET socket
208
209  - "`sts`": "1" causes lwsws to send a Strict Transport Security header with responses that informs the client he should never accept to connect to this address using http.  This is needed to get the A+ security rating from SSL Labs for your server.
210
211  - "`access-log`": "filepath"   sets where apache-compatible access logs will be written
212
213  - `"enable-client-ssl"`: `"1"` enables the vhost's client SSL context, you will need this if you plan to create client conections on the vhost that will use SSL.  You don't need it if you only want http / ws client connections.
214
215  - "`ciphers`": "<cipher list>"   sets the allowed list of ciphers and key exchange protocols for the vhost.  The default list is restricted to only those providing PFS (Perfect Forward Secrecy) on the author's Fedora system.
216  
217  If you need to allow weaker ciphers,you can provide an alternative list here per-vhost.
218  
219  - "`ecdh-curve`": "<curve name>"   The default ecdh curve is "prime256v1", but you can override it here, per-vhost
220
221  - "`noipv6`": "on"  Disable ipv6 completely for this vhost
222
223  - "`ipv6only`": "on"  Only allow ipv6 on this vhost / "off" only allow ipv4 on this vhost
224
225  - "`ssl-option-set`": "<decimal>"  Sets the SSL option flag value for the vhost.
226  It may be used multiple times and OR's the flags together.
227  
228  The values are derived from /usr/include/openssl/ssl.h
229 ```
230          # define SSL_OP_NO_TLSv1_1                               0x10000000L
231 ```
232  
233  would equate to
234  
235 ```
236          "`ssl-option-set`": "268435456"
237  ```
238  - "`ssl-option-clear'": "<decimal>"   Clears the SSL option flag value for the vhost.
239  It may be used multiple times and OR's the flags together.
240
241  - "`headers':: [{ "header1": "h1value", "header2": "h2value" }] 
242
243 allows you to set arbitrary headers on every file served by the vhost
244
245 recommended vhost headers for good client security are
246
247 ```
248                    "headers": [{
249                         "Content-Security-Policy": "script-src 'self'",
250                         "X-Content-Type-Options": "nosniff",
251                         "X-XSS-Protection": "1; mode=block",
252                         "X-Frame-Options": "SAMEORIGIN"
253                  }]
254
255 ```
256
257 @section lwswsm Lwsws Mounts
258
259 Where mounts are given in the vhost definition, then directory contents may
260 be auto-served if it matches the mountpoint.
261
262 Mount protocols are used to control what kind of translation happens
263
264  - file://  serve the uri using the remainder of the url past the mountpoint based on the origin directory.
265
266  Eg, with this mountpoint
267 ```
268                {
269                 "mountpoint": "/",
270                 "origin": "file:///var/www/mysite.com",
271                 "default": "/"
272                }
273 ```
274  The uri /file.jpg would serve /var/www/mysite.com/file.jpg, since / matched.
275
276  - ^http:// or ^https://  these cause any url matching the mountpoint to issue a redirect to the origin url
277
278  - cgi://   this causes any matching url to be given to the named cgi, eg
279 ```
280                {
281                 "mountpoint": "/git",
282                 "origin": "cgi:///var/www/cgi-bin/cgit",
283                 "default": "/"
284                }, {
285                 "mountpoint": "/cgit-data",
286                 "origin": "file:///usr/share/cgit",
287                 "default": "/"
288                },
289 ```
290  would cause the url /git/myrepo to pass "myrepo" to the cgi /var/www/cgi-bin/cgit and send the results to the client.
291
292
293
294 @section lwswsomo Lwsws Other mount options
295
296 1) Some protocols may want "per-mount options" in name:value format.  You can
297 provide them using "pmo"
298
299                {
300                 "mountpoint": "/stuff",
301                 "origin": "callback://myprotocol",
302                 "pmo": [{
303                         "myname": "myvalue"
304                 }]
305                }
306
307 2) When using a cgi:// protcol origin at a mountpoint, you may also give cgi environment variables specific to the mountpoint like this
308 ```
309                {
310                 "mountpoint": "/git",
311                 "origin": "cgi:///var/www/cgi-bin/cgit",
312                 "default": "/",
313                 "cgi-env": [{
314                         "CGIT_CONFIG": "/etc/cgitrc/libwebsockets.org"
315                 }]
316                }
317 ```
318  This allows you to customize one cgi depending on the mountpoint (and / or vhost).
319
320 3) It's also possible to set the cgi timeout (in secs) per cgi:// mount, like this
321 ```
322         "cgi-timeout": "30"
323 ```
324 4) `callback://` protocol may be used when defining a mount to associate a
325 named protocol callback with the URL namespace area.  For example
326 ```
327                {
328                 "mountpoint": "/formtest",
329                 "origin": "callback://protocol-post-demo"
330                }
331 ```
332 All handling of client access to /formtest[anything] will be passed to the
333 callback registered to the protocol "protocol-post-demo".
334
335 This is useful for handling POST http body content or general non-cgi http
336 payload generation inside a plugin.
337
338 See the related notes in README.coding.md
339
340 5) Cache policy of the files in the mount can also be set.  If no
341 options are given, the content is marked uncacheable.
342 ```
343                {
344                 "mountpoint": "/",
345                 "origin": "file:///var/www/mysite.com",
346                 "cache-max-age": "60",      # seconds
347                 "cache-reuse": "1",         # allow reuse at client at all
348                 "cache-revalidate": "1",    # check it with server each time
349                 "cache-intermediaries": "1" # allow intermediary caches to hold
350                }
351 ```
352
353 6) You can also define a list of additional mimetypes per-mount
354 ```
355                 "extra-mimetypes": {
356                          ".zip": "application/zip",
357                          ".doc": "text/evil"
358                  }
359 ```
360
361 Normally a file suffix MUST match one of the canned mimetypes or one of the extra
362 mimetypes, or the file is not served.  This adds a little bit of security because
363 even if there is a bug somewhere and the mount dirs are circumvented, lws will not
364 serve, eg, /etc/passwd.
365
366 If you provide an extra mimetype entry
367
368                         "*": ""
369
370 Then any file is served, if the mimetype was not known then it is served without a
371 Content-Type: header.
372
373 7) A mount can be protected by HTTP Basic Auth.  This only makes sense when using
374 https, since otherwise the password can be sniffed.
375
376 You can add a `basic-auth` entry on a mount like this`
377
378 ```
379 {
380         "mountpoint": "/basic-auth",
381         "origin": "file://_lws_ddir_/libwebsockets-test-server/private",
382         "basic-auth": "/var/www/balogins-private"
383 }
384 ```
385
386 Before serving anything, lws will signal to the browser that a username / password
387 combination is required, and it will pop up a dialog.  When the user has filled it
388 in, lwsws checks the user:password string against the text file named in the `basic-auth`
389 entry.
390
391 The file should contain user:pass one per line
392
393 ```
394 testuser:testpass
395 myuser:hispass
396 ```
397
398 The file should be readable by lwsws, and for a little bit of extra security not
399 have a file suffix, so lws would reject to serve it even if it could find it on
400 a mount.
401
402
403 @section lwswspl Lwsws Plugins
404
405 Protcols and extensions may also be provided from "plugins", these are
406 lightweight dynamic libraries.  They are scanned for at init time, and
407 any protocols and extensions found are added to the list given at context
408 creation time.
409
410 Protocols receive init (LWS_CALLBACK_PROTOCOL_INIT) and destruction
411 (LWS_CALLBACK_PROTOCOL_DESTROY) callbacks per-vhost, and there are arrangements
412 they can make per-vhost allocations and get hold of the correct pointer from
413 the wsi at the callback.
414
415 This allows a protocol to choose to strictly segregate data on a per-vhost
416 basis, and also allows the plugin to handle its own initialization and
417 context storage.
418
419 To help that happen conveniently, there are some new apis
420
421  - lws_vhost_get(wsi)
422  - lws_protocol_get(wsi)
423  - lws_callback_on_writable_all_protocol_vhost(vhost, protocol)
424  - lws_protocol_vh_priv_zalloc(vhost, protocol, size)
425  - lws_protocol_vh_priv_get(vhost, protocol)
426  
427 dumb increment, mirror and status protocol plugins are provided as examples.
428
429
430 @section lwswsplaplp Additional plugin search paths
431
432 Packages that have their own lws plugins can install them in their own
433 preferred dir and ask lwsws to scan there by using a config fragment
434 like this, in its own conf.d/ file managed by the other package
435 ```
436         {
437           "global": {
438            "plugin-dir": "/usr/local/share/coherent-timeline/plugins"
439           }
440         }
441 ```
442
443 @section lwswsssp lws-server-status plugin
444
445 One provided protocol can be used to monitor the server status.
446
447 Enable the protocol like this on a vhost's ws-protocols section
448 ```
449                "lws-server-status": {
450                  "status": "ok",
451                  "update-ms": "5000"
452                }
453 ```
454 `"update-ms"` is used to control how often updated JSON is sent on a ws link.
455
456 And map the provided HTML into the vhost in the mounts section
457 ```
458                {
459                 "mountpoint": "/server-status",
460                 "origin": "file:///usr/local/share/libwebsockets-test-server/server-status",
461                 "default": "server-status.html"
462                }
463 ```
464 You might choose to put it on its own vhost which has "interface": "lo", so it's not
465 externally visible, or use the Basic Auth support to require authentication to
466 access it.
467
468 `"hide-vhosts": "{0 | 1}"` lets you control if information about your vhosts is included.
469 Since this includes mounts, you might not want to leak that information, mount names,
470 etc.
471
472 `"filespath":"{path}"` lets you give a server filepath which is read and sent to the browser
473 on each refresh.  For example, you can provide server temperature information on most
474 Linux systems by giving an appropriate path down /sys.
475
476 This may be given multiple times.
477
478
479 @section lwswsreload Lwsws Configuration Reload
480
481 You may send lwsws a `HUP` signal, by, eg
482
483 ```
484 $ sudo killall -HUP lwsws
485 ```
486
487 This causes lwsws to "deprecate" the existing lwsws process, and remove and close all of
488 its listen sockets, but otherwise allowing it to continue to run, until all
489 of its open connections close.
490
491 When a deprecated lwsws process has no open connections left, it is destroyed
492 automatically.
493
494 After sending the SIGHUP to the main lwsws process, a new lwsws process, which can
495 pick up the newly-available listen sockets, and use the current configuration
496 files, is automatically started.
497
498 The new configuration may differ from the original one in arbitrary ways, the new
499 context is created from scratch each time without reference to the original one.
500
501 Notes
502
503 1) Protocols that provide a "shared world" like mirror will have as many "worlds"
504 as there are lwsws processes still active.  People connected to a deprecated lwsws
505 process remain connected to the existing peers.
506
507 But any new connections will apply to the new lwsws process, which does not share
508 per-vhost "shared world" data with the deprecated process.  That means no new
509 connections on the deprecated context, ie a "shrinking world" for those guys, and a
510 "growing world" for people who connect after the SIGHUP.
511
512 2) The new lwsws process owes nothing to the previous one.  It starts with fresh
513 plugins, fresh configuration, fresh root privileges if that how you start it.
514
515 The plugins may have been updated in arbitrary ways including struct size changes
516 etc, and lwsws or lws may also have been updated arbitrarily.
517
518 3) A root parent process is left up that is not able to do anything except
519 respond to SIGHUP or SIGTERM.  Actual serving and network listening etc happens
520 in child processes which use the privileges set in the lwsws config files.
521
522 @section lwswssysd Lwsws Integration with Systemd
523
524 lwsws needs a service file like this as `/usr/lib/systemd/system/lwsws.service`
525 ```
526 [Unit]
527 Description=Libwebsockets Web Server
528 After=syslog.target
529
530 [Service]
531 ExecStart=/usr/local/bin/lwsws 
532 ExecReload=/usr/bin/killall -s SIGHUP lwsws ; sleep 1 ; /usr/local/bin/lwsws
533 StandardError=null
534
535 [Install]
536 WantedBy=multi-user.target
537 ```
538
539 You can find this prepared in `./lwsws/usr-lib-systemd-system-lwsws.service`
540
541
542 @section lwswslr Lwsws Integration with logrotate
543
544 For correct operation with logrotate, `/etc/logrotate.d/lwsws` (if that's
545 where we're putting the logs) should contain
546 ```
547         /var/log/lwsws/*log {
548             copytruncate
549             missingok
550             notifempty
551             delaycompress
552         }
553 ```
554 You can find this prepared in `/lwsws/etc-logrotate.d-lwsws`
555
556 Prepare the log directory like this
557
558 ```
559         sudo mkdir /var/log/lwsws
560         sudo chmod 700 /var/log/lwsws
561 ```