b64decode correct decode of some strings
[platform/upstream/libwebsockets.git] / README.coding.md
1 Daemonization
2 -------------
3
4 There's a helper api `lws_daemonize` built by default that does everything you
5 need to daemonize well, including creating a lock file.  If you're making
6 what's basically a daemon, just call this early in your init to fork to a
7 headless background process and exit the starting process.
8
9 Notice stdout, stderr, stdin are all redirected to /dev/null to enforce your
10 daemon is headless, so you'll need to sort out alternative logging, by, eg,
11 syslog.
12
13
14 Maximum number of connections
15 -----------------------------
16
17 The maximum number of connections the library can deal with is decided when
18 it starts by querying the OS to find out how many file descriptors it is
19 allowed to open (1024 on Fedora for example).  It then allocates arrays that
20 allow up to that many connections, minus whatever other file descriptors are
21 in use by the user code.
22
23 If you want to restrict that allocation, or increase it, you can use ulimit or
24 similar to change the avaiable number of file descriptors, and when restarted
25 **libwebsockets** will adapt accordingly.
26
27
28 Libwebsockets is singlethreaded
29 -------------------------------
30
31 Directly performing websocket actions from other threads is not allowed.
32 Aside from the internal data being inconsistent in `forked()` processes,
33 the scope of a `wsi` (`struct websocket`) can end at any time during service
34 with the socket closing and the `wsi` freed.
35
36 Websocket write activities should only take place in the
37 `LWS_CALLBACK_SERVER_WRITEABLE` callback as described below.
38
39 Only live connections appear in the user callbacks, so this removes any
40 possibility of trying to used closed and freed wsis.
41
42 If you need to service other socket or file descriptors as well as the
43 websocket ones, you can combine them together with the websocket ones
44 in one poll loop, see "External Polling Loop support" below, and
45 still do it all in one thread / process context.
46
47 If you insist on trying to use it from multiple threads, take special care if
48 you might simultaneously create more than one context from different threads.
49
50 SSL_library_init() is called from the context create api and it also is not
51 reentrant.  So at least create the contexts sequentially.
52
53
54 Only send data when socket writeable
55 ------------------------------------
56
57 You should only send data on a websocket connection from the user callback
58 `LWS_CALLBACK_SERVER_WRITEABLE` (or `LWS_CALLBACK_CLIENT_WRITEABLE` for
59 clients).
60
61 If you want to send something, do not just send it but request a callback
62 when the socket is writeable using
63
64  - `lws_callback_on_writable(context, wsi)`` for a specific `wsi`, or
65  - `lws_callback_on_writable_all_protocol(protocol)` for all connections
66 using that protocol to get a callback when next writeable.
67
68 Usually you will get called back immediately next time around the service
69 loop, but if your peer is slow or temporarily inactive the callback will be
70 delayed accordingly.  Generating what to write and sending it should be done
71 in the ...WRITEABLE callback.
72
73 See the test server code for an example of how to do this.
74
75
76 Do not rely on only your own WRITEABLE requests appearing
77 ---------------------------------------------------------
78
79 Libwebsockets may generate additional `LWS_CALLBACK_CLIENT_WRITEABLE` events
80 if it met network conditions where it had to buffer your send data internally.
81
82 So your code for `LWS_CALLBACK_CLIENT_WRITEABLE` needs to own the decision
83 about what to send, it can't assume that just because the writeable callback
84 came it really is time to send something.
85
86 It's quite possible you get an 'extra' writeable callback at any time and
87 just need to `return 0` and wait for the expected callback later.
88
89
90 Closing connections from the user side
91 --------------------------------------
92
93 When you want to close a connection, you do it by returning `-1` from a
94 callback for that connection.
95
96 You can provoke a callback by calling `lws_callback_on_writable` on
97 the wsi, then notice in the callback you want to close it and just return -1.
98 But usually, the decision to close is made in a callback already and returning
99 -1 is simple.
100
101 If the socket knows the connection is dead, because the peer closed or there
102 was an affirmitive network error like a FIN coming, then **libwebsockets**  will
103 take care of closing the connection automatically.
104
105 If you have a silently dead connection, it's possible to enter a state where
106 the send pipe on the connection is choked but no ack will ever come, so the
107 dead connection will never become writeable.  To cover that, you can use TCP
108 keepalives (see later in this document)
109
110
111 Fragmented messages
112 -------------------
113
114 To support fragmented messages you need to check for the final
115 frame of a message with `lws_is_final_fragment`. This
116 check can be combined with `libwebsockets_remaining_packet_payload`
117 to gather the whole contents of a message, eg:
118
119 ```
120     case LWS_CALLBACK_RECEIVE:
121     {
122         Client * const client = (Client *)user;
123         const size_t remaining = lws_remaining_packet_payload(wsi);
124
125         if (!remaining && lws_is_final_fragment(wsi)) {
126             if (client->HasFragments()) {
127                 client->AppendMessageFragment(in, len, 0);
128                 in = (void *)client->GetMessage();
129                 len = client->GetMessageLength();
130             }
131
132             client->ProcessMessage((char *)in, len, wsi);
133             client->ResetMessage();
134         } else
135             client->AppendMessageFragment(in, len, remaining);
136     }
137     break;
138 ```
139
140 The test app libwebsockets-test-fraggle sources also show how to
141 deal with fragmented messages.
142
143
144 Debug Logging
145 -------------
146
147 Also using `lws_set_log_level` api you may provide a custom callback to actually
148 emit the log string.  By default, this points to an internal emit function
149 that sends to stderr.  Setting it to `NULL` leaves it as it is instead.
150
151 A helper function `lwsl_emit_syslog()` is exported from the library to simplify
152 logging to syslog.  You still need to use `setlogmask`, `openlog` and `closelog`
153 in your user code.
154
155 The logging apis are made available for user code.
156
157 - `lwsl_err(...)`
158 - `lwsl_warn(...)`
159 - `lwsl_notice(...)`
160 - `lwsl_info(...)`
161 - `lwsl_debug(...)`
162
163 The difference between notice and info is that notice will be logged by default
164 whereas info is ignored by default.
165
166
167 External Polling Loop support
168 -----------------------------
169
170 **libwebsockets** maintains an internal `poll()` array for all of its
171 sockets, but you can instead integrate the sockets into an
172 external polling array.  That's needed if **libwebsockets** will
173 cooperate with an existing poll array maintained by another
174 server.
175
176 Four callbacks `LWS_CALLBACK_ADD_POLL_FD`, `LWS_CALLBACK_DEL_POLL_FD`,
177 `LWS_CALLBACK_SET_MODE_POLL_FD` and `LWS_CALLBACK_CLEAR_MODE_POLL_FD`
178 appear in the callback for protocol 0 and allow interface code to
179 manage socket descriptors in other poll loops.
180
181 You can pass all pollfds that need service to `lws_service_fd()`, even
182 if the socket or file does not belong to **libwebsockets** it is safe.
183
184 If **libwebsocket** handled it, it zeros the pollfd `revents` field before returning.
185 So you can let **libwebsockets** try and if `pollfd->revents` is nonzero on return,
186 you know it needs handling by your code.
187
188
189 Using with in c++ apps
190 ----------------------
191
192 The library is ready for use by C++ apps.  You can get started quickly by
193 copying the test server
194
195 ```bash
196 $ cp test-server/test-server.c test.cpp
197 ```
198
199 and building it in C++ like this
200
201 ```bash
202 $ g++ -DINSTALL_DATADIR=\"/usr/share\" -ocpptest test.cpp -lwebsockets
203 ```
204
205 `INSTALL_DATADIR` is only needed because the test server uses it as shipped, if
206 you remove the references to it in your app you don't need to define it on
207 the g++ line either.
208
209
210 Availability of header information
211 ----------------------------------
212
213 From v1.2 of the library onwards, the HTTP header content is `free()`d as soon
214 as the websocket connection is established.  For websocket servers, you can
215 copy interesting headers by handling `LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION`
216 callback, for clients there's a new callback just for this purpose
217 `LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH`.
218
219
220 TCP Keepalive
221 -------------
222
223 It is possible for a connection which is not being used to send to die
224 silently somewhere between the peer and the side not sending.  In this case
225 by default TCP will just not report anything and you will never get any more
226 incoming data or sign the link is dead until you try to send.
227
228 To deal with getting a notification of that situation, you can choose to
229 enable TCP keepalives on all **libwebsockets** sockets, when you create the
230 context.
231
232 To enable keepalive, set the ka_time member of the context creation parameter
233 struct to a nonzero value (in seconds) at context creation time.  You should
234 also fill ka_probes and ka_interval in that case.
235
236 With keepalive enabled, the TCP layer will send control packets that should
237 stimulate a response from the peer without affecting link traffic.  If the
238 response is not coming, the socket will announce an error at `poll()` forcing
239 a close.
240
241 Note that BSDs don't support keepalive time / probes / interval per-socket
242 like Linux does.  On those systems you can enable keepalive by a nonzero
243 value in `ka_time`, but the systemwide kernel settings for the time / probes/
244 interval are used, regardless of what nonzero value is in `ka_time`.
245
246 Optimizing SSL connections
247 --------------------------
248
249 There's a member `ssl_cipher_list` in the `lws_context_creation_info` struct
250 which allows the user code to restrict the possible cipher selection at
251 context-creation time.
252
253 You might want to look into that to stop the ssl peers selecting a cipher which
254 is too computationally expensive.  To use it, point it to a string like
255
256 `"RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL"`
257
258 if left `NULL`, then the "DEFAULT" set of ciphers are all possible to select.
259
260
261 Async nature of client connections
262 ----------------------------------
263
264 When you call `lws_client_connect_info(..)` and get a `wsi` back, it does not
265 mean your connection is active.  It just means it started trying to connect.
266
267 Your client connection is actually active only when you receive
268 `LWS_CALLBACK_CLIENT_ESTABLISHED` for it.
269
270 There's a 5 second timeout for the connection, and it may give up or die for
271 other reasons, if any of that happens you'll get a
272 `LWS_CALLBACK_CLIENT_CONNECTION_ERROR` callback on protocol 0 instead for the
273 `wsi`.
274
275 After attempting the connection and getting back a non-`NULL` `wsi` you should
276 loop calling `lws_service()` until one of the above callbacks occurs.
277
278 As usual, see [test-client.c](test-server/test-client.c) for example code.
279
280 Lws platform-independent file access apis
281 -----------------------------------------
282
283 lws now exposes his internal platform file abstraction in a way that can be
284 both used by user code to make it platform-agnostic, and be overridden or
285 subclassed by user code.  This allows things like handling the URI "directory
286 space" as a virtual filesystem that may or may not be backed by a regular
287 filesystem.  One example use is serving files from inside large compressed
288 archive storage without having to unpack anything except the file being
289 requested.
290
291 The test server shows how to use it, basically the platform-specific part of
292 lws prepares a file operations structure that lives in the lws context.
293
294 The user code can get a pointer to the file operations struct
295
296 LWS_VISIBLE LWS_EXTERN struct lws_plat_file_ops *
297 `lws_get_fops`(struct lws_context *context);
298
299 and then can use helpers to also leverage these platform-independent
300 file handling apis
301
302 static inline lws_filefd_type
303 `lws_plat_file_open`(struct lws *wsi, const char *filename, unsigned long *filelen, int flags)
304
305 static inline int
306 `lws_plat_file_close`(struct lws *wsi, lws_filefd_type fd)
307
308 static inline unsigned long
309 `lws_plat_file_seek_cur`(struct lws *wsi, lws_filefd_type fd, long offset_from_cur_pos)
310
311 static inline int
312 `lws_plat_file_read`(struct lws *wsi, lws_filefd_type fd, unsigned long *amount, unsigned char *buf, unsigned long len)
313
314 static inline int
315 `lws_plat_file_write`(struct lws *wsi, lws_filefd_type fd, unsigned long *amount, unsigned char *buf, unsigned long len)
316                     
317 The user code can also override or subclass the file operations, to either
318 wrap or replace them.  An example is shown in test server.
319
320 ECDH Support
321 ------------
322
323 ECDH Certs are now supported.  Enable the CMake option
324
325 cmake .. -DLWS_SSL_SERVER_WITH_ECDH_CERT=1 
326
327 **and** the info->options flag
328
329 LWS_SERVER_OPTION_SSL_ECDH
330
331 to build in support and select it at runtime.
332
333 SMP / Multithreaded service
334 ---------------------------
335
336 SMP support is integrated into LWS without any internal threading.  It's
337 very simple to use, libwebsockets-test-server-pthread shows how to do it,
338 use -j <n> argument there to control the number of service threads up to 32.
339
340 Two new members are added to the info struct
341
342         unsigned int count_threads;
343         unsigned int fd_limit_per_thread;
344         
345 leave them at the default 0 to get the normal singlethreaded service loop.
346
347 Set count_threads to n to tell lws you will have n simultaneous service threads
348 operating on the context.
349
350 There is still a single listen socket on one port, no matter how many
351 service threads.
352
353 When a connection is made, it is accepted by the service thread with the least
354 connections active to perform load balancing.
355
356 The user code is responsible for spawning n threads running the service loop
357 associated to a specific tsi (Thread Service Index, 0 .. n - 1).  See
358 the libwebsockets-test-server-pthread for how to do.
359
360 If you leave fd_limit_per_thread at 0, then the process limit of fds is shared
361 between the service threads; if you process was allowed 1024 fds overall then
362 each thread is limited to 1024 / n.
363
364 You can set fd_limit_per_thread to a nonzero number to control this manually, eg
365 the overall supported fd limit is less than the process allowance.
366
367 You can control the context basic data allocation for multithreading from Cmake
368 using -DLWS_MAX_SMP=, if not given it's set to 32.  The serv_buf allocation
369 for the threads (currently 4096) is made at runtime only for active threads.
370
371 Because lws will limit the requested number of actual threads supported
372 according to LWS_MAX_SMP, there is an api lws_get_count_threads(context) to
373 discover how many threads were actually allowed when the context was created.
374
375 It's required to implement locking in the user code in the same way that
376 libwebsockets-test-server-pthread does it, for the FD locking callbacks.
377
378 There is no knowledge or dependency in lws itself about pthreads.  How the
379 locking is implemented is entirely up to the user code.
380
381
382 Libev / Libuv support
383 ---------------------
384
385 You can select either or both
386
387 -DLWS_WITH_LIBEV=1
388 -DLWS_WITH_LIBUV=1
389
390 at cmake configure-time.  The user application may use one of the
391 context init options flags
392
393 LWS_SERVER_OPTION_LIBEV
394 LWS_SERVER_OPTION_LIBUV
395
396 to indicate it will use either of the event libraries.