libwebsockets
Lightweight C library for HTML5 websockets
lws-misc.h
Go to the documentation of this file.
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010 - 2021 Andy Green <andy@warmcat.com>
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to
8  * deal in the Software without restriction, including without limitation the
9  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10  * sell copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22  * IN THE SOFTWARE.
23  */
24 
25 #if defined(LWS_WITH_SPAWN)
26 
27 #if defined(WIN32) || defined(_WIN32)
28 #else
29 #include <sys/wait.h>
30 #include <sys/times.h>
31 #endif
32 #endif
33 
34 #if defined(__OpenBSD__)
35 #include <sys/siginfo.h>
36 #endif
37 
38 /** \defgroup misc Miscellaneous APIs
39 * ##Miscellaneous APIs
40 *
41 * Various APIs outside of other categories
42 */
43 ///@{
44 
45 struct lws_buflist;
46 
47 /**
48  * lws_buflist_append_segment(): add buffer to buflist at head
49  *
50  * \param head: list head
51  * \param buf: buffer to stash
52  * \param len: length of buffer to stash
53  *
54  * Returns -1 on OOM, 1 if this was the first segment on the list, and 0 if
55  * it was a subsequent segment.
56  */
57 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
58 lws_buflist_append_segment(struct lws_buflist **head, const uint8_t *buf,
59  size_t len);
60 /**
61  * lws_buflist_next_segment_len(): number of bytes left in current segment
62  *
63  * \param head: list head
64  * \param buf: if non-NULL, *buf is written with the address of the start of
65  * the remaining data in the segment
66  *
67  * Returns the number of bytes left in the current segment. 0 indicates
68  * that the buflist is empty (there are no segments on the buflist).
69  */
70 LWS_VISIBLE LWS_EXTERN size_t
71 lws_buflist_next_segment_len(struct lws_buflist **head, uint8_t **buf);
72 
73 /**
74  * lws_buflist_use_segment(): remove len bytes from the current segment
75  *
76  * \param head: list head
77  * \param len: number of bytes to mark as used
78  *
79  * If len is less than the remaining length of the current segment, the position
80  * in the current segment is simply advanced and it returns.
81  *
82  * If len uses up the remaining length of the current segment, then the segment
83  * is deleted and the list head moves to the next segment if any.
84  *
85  * Returns the number of bytes left in the current segment. 0 indicates
86  * that the buflist is empty (there are no segments on the buflist).
87  */
88 LWS_VISIBLE LWS_EXTERN size_t
89 lws_buflist_use_segment(struct lws_buflist **head, size_t len);
90 
91 /**
92  * lws_buflist_total_len(): Get the total size of the buflist
93  *
94  * \param head: list head
95  *
96  * Returns the total number of bytes held on all segments of the buflist
97  */
98 LWS_VISIBLE LWS_EXTERN size_t
99 lws_buflist_total_len(struct lws_buflist **head);
100 
101 /**
102  * lws_buflist_linear_copy(): copy everything out as one without consuming
103  *
104  * \param head: list head
105  * \param ofs: start offset into buflist in bytes
106  * \param buf: buffer to copy linearly into
107  * \param len: length of buffer available
108  *
109  * Returns -1 if len is too small, or bytes copied. Happy to do partial
110  * copies, returns 0 when there are no more bytes to copy.
111  */
112 LWS_VISIBLE LWS_EXTERN int
113 lws_buflist_linear_copy(struct lws_buflist **head, size_t ofs, uint8_t *buf,
114  size_t len);
115 
116 /**
117  * lws_buflist_linear_use(): copy and consume from buflist head
118  *
119  * \param head: list head
120  * \param buf: buffer to copy linearly into
121  * \param len: length of buffer available
122  *
123  * Copies a possibly fragmented buflist from the head into the linear output
124  * buffer \p buf for up to length \p len, and consumes the buflist content that
125  * was copied out.
126  *
127  * Since it was consumed, calling again will resume copying out and consuming
128  * from as far as it got the first time.
129  *
130  * Returns the number of bytes written into \p buf.
131  */
132 LWS_VISIBLE LWS_EXTERN int
133 lws_buflist_linear_use(struct lws_buflist **head, uint8_t *buf, size_t len);
134 
135 /**
136  * lws_buflist_fragment_use(): copy and consume <= 1 frag from buflist head
137  *
138  * \param head: list head
139  * \param buf: buffer to copy linearly into
140  * \param len: length of buffer available
141  * \param frag_first: pointer to char written on exit to if this is start of frag
142  * \param frag_fin: pointer to char written on exit to if this is end of frag
143  *
144  * Copies all or part of the fragment at the start of a buflist from the head
145  * into the output buffer \p buf for up to length \p len, and consumes the
146  * buflist content that was copied out.
147  *
148  * Since it was consumed, calling again will resume copying out and consuming
149  * from as far as it got the first time.
150  *
151  * Returns the number of bytes written into \p buf.
152  */
153 LWS_VISIBLE LWS_EXTERN int
154 lws_buflist_fragment_use(struct lws_buflist **head, uint8_t *buf,
155  size_t len, char *frag_first, char *frag_fin);
156 
157 /**
158  * lws_buflist_destroy_all_segments(): free all segments on the list
159  *
160  * \param head: list head
161  *
162  * This frees everything on the list unconditionally. *head is always
163  * NULL after this.
164  */
165 LWS_VISIBLE LWS_EXTERN void
166 lws_buflist_destroy_all_segments(struct lws_buflist **head);
167 
168 /**
169  * lws_buflist_describe(): debug helper logging buflist status
170  *
171  * \param head: list head
172  * \param id: pointer shown in debug list
173  * \param reason: reason string show in debug list
174  *
175  * Iterates through the buflist segments showing position and size.
176  * This only exists when lws was built in debug mode
177  */
178 LWS_VISIBLE LWS_EXTERN void
179 lws_buflist_describe(struct lws_buflist **head, void *id, const char *reason);
180 
181 
182 /*
183  * Optional helpers for closely-managed stream flow control. These are useful
184  * when there is no memory for large rx buffers and instead tx credit is being
185  * used to regulate the server sending data.
186  *
187  * When combined with stateful consumption-on-demand, this can be very effective
188  * at managing data flows through restricted circumstances. These helpers
189  * implement a golden implementation that can be bound to a stream in its priv
190  * data.
191  *
192  * The helper is sophisticated enough to contain a buflist to manage overflows
193  * on heap and preferentially drain it. RX goes through heap to guarantee the
194  * consumer can exit cleanly at any time.
195  */
196 
197 enum {
198  LWSDLOFLOW_STATE_READ, /* default, we want input */
199  LWSDLOFLOW_STATE_READ_COMPLETED, /* we do not need further rx, every-
200  * thing is locally buffered or used */
201  LWSDLOFLOW_STATE_READ_FAILED, /* operation has fatal error */
202 };
203 
204 struct lws_ss_handle;
205 
206 typedef struct lws_flow {
208 
209  struct lws_ss_handle *h;
210  struct lws_buflist *bl;
211 
212  const uint8_t *data;
213  size_t len; /* bytes left in data */
214  uint32_t blseglen; /* bytes issued */
216 
218 } lws_flow_t;
219 
220 /**
221  * lws_flow_feed() - consume waiting data if ready for it
222  *
223  * \param flow: pointer to the flow struct managing waiting data
224  *
225  * This will bring out waiting data from the flow buflist when it is needed.
226  */
227 LWS_VISIBLE LWS_EXTERN lws_stateful_ret_t
228 lws_flow_feed(lws_flow_t *flow);
229 
230 /**
231  * lws_flow_req() - request remote data if we have run low
232  *
233  * \param flow: pointer to the flow struct managing waiting data
234  *
235  * When the estimated remote tx credit is below flow->window, accounting for
236  * what is in the buflist, add to the peer tx credit so it can send us more.
237  */
238 LWS_VISIBLE LWS_EXTERN lws_stateful_ret_t
239 lws_flow_req(lws_flow_t *flow);
240 
241 /**
242  * lws_ptr_diff(): helper to report distance between pointers as an int
243  *
244  * \param head: the pointer with the larger address
245  * \param tail: the pointer with the smaller address
246  *
247  * This helper gives you an int representing the number of bytes further
248  * forward the first pointer is compared to the second pointer.
249  */
250 #define lws_ptr_diff(head, tail)
251  ((int)((char *)(head) - (char *)(tail)))
252 
253 #define lws_ptr_diff_size_t(head, tail)
254  ((size_t)(ssize_t)((char *)(head) - (char *)(tail)))
255 
256 /**
257  * lws_snprintf(): snprintf that truncates the returned length too
258  *
259  * \param str: destination buffer
260  * \param size: bytes left in destination buffer
261  * \param format: format string
262  * \param ...: args for format
263  *
264  * This lets you correctly truncate buffers by concatenating lengths, if you
265  * reach the limit the reported length doesn't exceed the limit.
266  */
267 LWS_VISIBLE LWS_EXTERN int
268 lws_snprintf(char *str, size_t size, const char *format, ...) LWS_FORMAT(3);
269 
270 /**
271  * lws_strncpy(): strncpy that guarantees NUL on truncated copy
272  *
273  * \param dest: destination buffer
274  * \param src: source buffer
275  * \param size: bytes left in destination buffer
276  *
277  * This lets you correctly truncate buffers by concatenating lengths, if you
278  * reach the limit the reported length doesn't exceed the limit.
279  */
280 LWS_VISIBLE LWS_EXTERN char *
281 lws_strncpy(char *dest, const char *src, size_t size);
282 
283 /*
284  * Variation where we want to use the smaller of two lengths, useful when the
285  * source string is not NUL terminated
286  */
287 #define lws_strnncpy(dest, src, size1, destsize)
288  lws_strncpy(dest, src, (size_t)(size1 + 1) < (size_t)(destsize) ?
289  (size_t)(size1 + 1) : (size_t)(destsize))
290 
291 /**
292  * lws_nstrstr(): like strstr for length-based strings without terminating NUL
293  *
294  * \param buf: the string to search
295  * \param len: the length of the string to search
296  * \param name: the substring to search for
297  * \param nl: the length of name
298  *
299  * Returns NULL if \p name is not present in \p buf. Otherwise returns the
300  * address of the first instance of \p name in \p buf.
301  *
302  * Neither buf nor name need to be NUL-terminated.
303  */
304 LWS_VISIBLE LWS_EXTERN const char *
305 lws_nstrstr(const char *buf, size_t len, const char *name, size_t nl);
306 
307 /**
308  * lws_json_simple_find(): dumb JSON string parser
309  *
310  * \param buf: the JSON to search
311  * \param len: the length of the JSON to search
312  * \param name: the name field to search the JSON for, eg, "\"myname\":"
313  * \param alen: set to the length of the argument part if non-NULL return
314  *
315  * Either returns NULL if \p name is not present in buf, or returns a pointer
316  * to the argument body of the first instance of \p name, and sets *alen to the
317  * length of the argument body.
318  *
319  * This can cheaply handle fishing out, eg, myarg from {"myname": "myarg"} by
320  * searching for "\"myname\":". It will return a pointer to myarg and set *alen
321  * to 5. It equally handles args like "myname": true, or "myname":false, and
322  * null or numbers are all returned as delimited strings.
323  *
324  * Anything more complicated like the value is a subobject or array, you should
325  * parse it using a full parser like lejp. This is suitable is the JSON is
326  * and will remain short and simple, and contains well-known names amongst other
327  * extensible JSON members.
328  */
329 LWS_VISIBLE LWS_EXTERN const char *
330 lws_json_simple_find(const char *buf, size_t len, const char *name, size_t *alen);
331 
332 /**
333  * lws_json_simple_strcmp(): dumb JSON string comparison
334  *
335  * \param buf: the JSON to search
336  * \param len: the length of the JSON to search
337  * \param name: the name field to search the JSON for, eg, "\"myname\":"
338  * \param comp: return a strcmp of this and the discovered argument
339  *
340  * Helper that combines lws_json_simple_find() with strcmp() if it was found.
341  * If the \p name was not found, returns -1. Otherwise returns a strcmp()
342  * between what was found and \p comp, ie, return 0 if they match or something
343  * else if they don't.
344  *
345  * If the JSON is relatively simple and you want to target constrained
346  * devices, this can be a good choice. If the JSON may be complex, you
347  * should use a full JSON parser.
348  */
349 LWS_VISIBLE LWS_EXTERN int
350 lws_json_simple_strcmp(const char *buf, size_t len, const char *name, const char *comp);
351 
352 /**
353  * lws_hex_len_to_byte_array(): convert hex string like 0123456789ab into byte data
354  *
355  * \param h: incoming hex string
356  * \param hlen: number of chars to process at \p h
357  * \param dest: array to fill with binary decodes of hex pairs from h
358  * \param max: maximum number of bytes dest can hold, must be at least half
359  * the size of strlen(h)
360  *
361  * This converts hex strings into an array of 8-bit representations, ie the
362  * input "abcd" produces two bytes of value 0xab and 0xcd.
363  *
364  * Returns number of bytes produced into \p dest, or -1 on error.
365  *
366  * Errors include non-hex chars and an odd count of hex chars in the input
367  * string.
368  */
369 LWS_VISIBLE LWS_EXTERN int
370 lws_hex_len_to_byte_array(const char *h, size_t hlen, uint8_t *dest, int max);
371 
372 /**
373  * lws_hex_to_byte_array(): convert hex string like 0123456789ab into byte data
374  *
375  * \param h: incoming NUL-terminated hex string
376  * \param dest: array to fill with binary decodes of hex pairs from h
377  * \param max: maximum number of bytes dest can hold, must be at least half
378  * the size of strlen(h)
379  *
380  * This converts hex strings into an array of 8-bit representations, ie the
381  * input "abcd" produces two bytes of value 0xab and 0xcd.
382  *
383  * Returns number of bytes produced into \p dest, or -1 on error.
384  *
385  * Errors include non-hex chars and an odd count of hex chars in the input
386  * string.
387  */
388 LWS_VISIBLE LWS_EXTERN int
389 lws_hex_to_byte_array(const char *h, uint8_t *dest, int max);
390 
391 /**
392  * lws_hex_from_byte_array(): render byte array as hex char string
393  *
394  * \param src: incoming binary source array
395  * \param slen: length of src in bytes
396  * \param dest: array to fill with hex chars representing src
397  * \param len: max extent of dest
398  *
399  * This converts binary data of length slen at src, into a hex string at dest
400  * of maximum length len. Even if truncated, the result will be NUL-terminated.
401  */
402 LWS_VISIBLE LWS_EXTERN void
403 lws_hex_from_byte_array(const uint8_t *src, size_t slen, char *dest, size_t len);
404 
405 /**
406  * lws_hex_random(): generate len - 1 or - 2 characters of random ascii hex
407  *
408  * \param context: the lws_context used to get the random
409  * \param dest: destination for hex ascii chars
410  * \param len: the number of bytes the buffer dest points to can hold
411  *
412  * This creates random ascii-hex strings up to a given length, with a
413  * terminating NUL.
414  *
415  * There will not be any characters produced that are not 0-9, a-f, so it's
416  * safe to go straight into, eg, JSON.
417  */
418 LWS_VISIBLE LWS_EXTERN int
419 lws_hex_random(struct lws_context *context, char *dest, size_t len);
420 
421 /*
422  * lws_timingsafe_bcmp(): constant time memcmp
423  *
424  * \param a: first buffer
425  * \param b: second buffer
426  * \param len: count of bytes to compare
427  *
428  * Return 0 if the two buffers are the same, else nonzero.
429  *
430  * Always compares all of the buffer before returning, so it can't be used as
431  * a timing oracle.
432  */
433 
434 LWS_VISIBLE LWS_EXTERN int
435 lws_timingsafe_bcmp(const void *a, const void *b, uint32_t len);
436 
437 /**
438  * lws_get_random(): fill a buffer with platform random data
439  *
440  * \param context: the lws context
441  * \param buf: buffer to fill
442  * \param len: how much to fill
443  *
444  * Fills buf with len bytes of random. Returns the number of bytes set, if
445  * not equal to len, then getting the random failed.
446  */
447 LWS_VISIBLE LWS_EXTERN size_t
448 lws_get_random(struct lws_context *context, void *buf, size_t len);
449 /**
450  * lws_daemonize(): make current process run in the background
451  *
452  * \param _lock_path: the filepath to write the lock file
453  *
454  * Spawn lws as a background process, taking care of various things
455  */
456 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
457 lws_daemonize(const char *_lock_path);
458 /**
459  * lws_get_library_version(): return string describing the version of lws
460  *
461  * On unix, also includes the git describe
462  */
463 LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
464 lws_get_library_version(void);
465 
466 /**
467  * lws_wsi_user() - get the user data associated with the connection
468  * \param wsi: lws connection
469  *
470  * Not normally needed since it's passed into the callback
471  */
472 LWS_VISIBLE LWS_EXTERN void *
473 lws_wsi_user(struct lws *wsi);
474 
475 /**
476  * lws_wsi_tsi() - get the service thread index the wsi is bound to
477  * \param wsi: lws connection
478  *
479  * Only useful is LWS_MAX_SMP > 1
480  */
481 LWS_VISIBLE LWS_EXTERN int
482 lws_wsi_tsi(struct lws *wsi);
483 
484 /**
485  * lws_set_wsi_user() - set the user data associated with the client connection
486  * \param wsi: lws connection
487  * \param user: user data
488  *
489  * By default lws allocates this and it's not legal to externally set it
490  * yourself. However client connections may have it set externally when the
491  * connection is created... if so, this api can be used to modify it at
492  * runtime additionally.
493  */
494 LWS_VISIBLE LWS_EXTERN void
495 lws_set_wsi_user(struct lws *wsi, void *user);
496 
497 /**
498  * lws_parse_uri: cut up prot:/ads:port/path into pieces
499  * Notice it does so by dropping '\0' into input string
500  * and the leading / on the path is consequently lost
501  *
502  * \param p: incoming uri string.. will get written to
503  * \param prot: result pointer for protocol part (https://)
504  * \param ads: result pointer for address part
505  * \param port: result pointer for port part
506  * \param path: result pointer for path part
507  *
508  * You may also refer to unix socket addresses, using a '+' at the start of
509  * the address. In this case, the address should end with ':', which is
510  * treated as the separator between the address and path (the normal separator
511  * '/' is a valid part of the socket path). Eg,
512  *
513  * http://+/var/run/mysocket:/my/path
514  *
515  * If the first character after the + is '@', it's interpreted by lws client
516  * processing as meaning to use linux abstract namespace sockets, the @ is
517  * replaced with a '\0' before use.
518  */
519 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
520 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
521  const char **path);
522 /**
523  * lws_cmdline_option(): simple commandline parser
524  *
525  * \param argc: count of argument strings
526  * \param argv: argument strings
527  * \param val: string to find
528  *
529  * Returns NULL if the string \p val is not found in the arguments.
530  *
531  * If it is found, then it returns a pointer to the next character after \p val.
532  * So if \p val is "-d", then for the commandlines "myapp -d15" and
533  * "myapp -d 15", in both cases the return will point to the "15".
534  *
535  * In the case there is no argument, like "myapp -d", the return will
536  * either point to the '\\0' at the end of -d, or to the start of the
537  * next argument, ie, will be non-NULL.
538  */
539 LWS_VISIBLE LWS_EXTERN const char *
540 lws_cmdline_option(int argc, const char **argv, const char *val);
541 
542 /**
543  * lws_cmdline_option_handle_builtin(): apply standard cmdline options
544  *
545  * \param argc: count of argument strings
546  * \param argv: argument strings
547  * \param info: context creation info
548  *
549  * Applies standard options to the context creation info to save them having
550  * to be (unevenly) copied into the minimal examples.
551  *
552  * Applies default log levels that can be overriden by -d
553  */
554 LWS_VISIBLE LWS_EXTERN void
555 lws_cmdline_option_handle_builtin(int argc, const char **argv,
556  struct lws_context_creation_info *info);
557 
558 /**
559  * lws_now_secs(): return seconds since 1970-1-1
560  */
561 LWS_VISIBLE LWS_EXTERN unsigned long
563 
564 /**
565  * lws_now_usecs(): return useconds since 1970-1-1
566  */
567 LWS_VISIBLE LWS_EXTERN lws_usec_t
568 lws_now_usecs(void);
569 
570 /**
571  * lws_get_context - Allow getting lws_context from a Websocket connection
572  * instance
573  *
574  * With this function, users can access context in the callback function.
575  * Otherwise users may have to declare context as a global variable.
576  *
577  * \param wsi: Websocket connection instance
578  */
579 LWS_VISIBLE LWS_EXTERN struct lws_context * LWS_WARN_UNUSED_RESULT
580 lws_get_context(const struct lws *wsi);
581 
582 /**
583  * lws_get_vhost_listen_port - Find out the port number a vhost is listening on
584  *
585  * In the case you passed 0 for the port number at context creation time, you
586  * can discover the port number that was actually chosen for the vhost using
587  * this api.
588  *
589  * \param vhost: Vhost to get listen port from
590  */
591 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
592 lws_get_vhost_listen_port(struct lws_vhost *vhost);
593 
594 /**
595  * lws_get_count_threads(): how many service threads the context uses
596  *
597  * \param context: the lws context
598  *
599  * By default this is always 1, if you asked for more than lws can handle it
600  * will clip the number of threads. So you can use this to find out how many
601  * threads are actually in use.
602  */
603 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
604 lws_get_count_threads(struct lws_context *context);
605 
606 /**
607  * lws_get_parent() - get parent wsi or NULL
608  * \param wsi: lws connection
609  *
610  * Specialized wsi like cgi stdin/out/err are associated to a parent wsi,
611  * this allows you to get their parent.
612  */
613 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
614 lws_get_parent(const struct lws *wsi);
615 
616 /**
617  * lws_get_child() - get child wsi or NULL
618  * \param wsi: lws connection
619  *
620  * Allows you to find a related wsi from the parent wsi.
621  */
622 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
623 lws_get_child(const struct lws *wsi);
624 
625 /**
626  * lws_get_effective_uid_gid() - find out eventual uid and gid while still root
627  *
628  * \param context: lws context
629  * \param uid: pointer to uid result
630  * \param gid: pointer to gid result
631  *
632  * This helper allows you to find out what the uid and gid for the process will
633  * be set to after the privileges are dropped, beforehand. So while still root,
634  * eg in LWS_CALLBACK_PROTOCOL_INIT, you can arrange things like cache dir
635  * and subdir creation / permissions down /var/cache dynamically.
636  */
637 LWS_VISIBLE LWS_EXTERN void
638 lws_get_effective_uid_gid(struct lws_context *context, uid_t *uid, gid_t *gid);
639 
640 /**
641  * lws_get_udp() - get wsi's udp struct
642  *
643  * \param wsi: lws connection
644  *
645  * Returns NULL or pointer to the wsi's UDP-specific information
646  */
647 LWS_VISIBLE LWS_EXTERN const struct lws_udp * LWS_WARN_UNUSED_RESULT
648 lws_get_udp(const struct lws *wsi);
649 
650 LWS_VISIBLE LWS_EXTERN void *
651 lws_get_opaque_parent_data(const struct lws *wsi);
652 
653 LWS_VISIBLE LWS_EXTERN void
654 lws_set_opaque_parent_data(struct lws *wsi, void *data);
655 
656 LWS_VISIBLE LWS_EXTERN void *
657 lws_get_opaque_user_data(const struct lws *wsi);
658 
659 LWS_VISIBLE LWS_EXTERN void
660 lws_set_opaque_user_data(struct lws *wsi, void *data);
661 
662 LWS_VISIBLE LWS_EXTERN int
663 lws_get_child_pending_on_writable(const struct lws *wsi);
664 
665 LWS_VISIBLE LWS_EXTERN void
667 
668 LWS_VISIBLE LWS_EXTERN int
669 lws_get_close_length(struct lws *wsi);
670 
671 LWS_VISIBLE LWS_EXTERN unsigned char *
672 lws_get_close_payload(struct lws *wsi);
673 
674 /**
675  * lws_get_network_wsi() - Returns wsi that has the tcp connection for this wsi
676  *
677  * \param wsi: wsi you have
678  *
679  * Returns wsi that has the tcp connection (which may be the incoming wsi)
680  *
681  * HTTP/1 connections will always return the incoming wsi
682  * HTTP/2 connections may return a different wsi that has the tcp connection
683  */
684 LWS_VISIBLE LWS_EXTERN
685 struct lws *lws_get_network_wsi(struct lws *wsi);
686 
687 /**
688  * lws_set_allocator() - custom allocator support
689  *
690  * \param realloc
691  *
692  * Allows you to replace the allocator (and deallocator) used by lws
693  */
694 LWS_VISIBLE LWS_EXTERN void
695 lws_set_allocator(void *(*realloc)(void *ptr, size_t size, const char *reason));
696 
697 enum {
698  /*
699  * Flags for enable and disable rxflow with reason bitmap and with
700  * backwards-compatible single bool
701  */
705 
712 
713 };
714 
715 /**
716  * lws_rx_flow_control() - Enable and disable socket servicing for
717  * received packets.
718  *
719  * If the output side of a server process becomes choked, this allows flow
720  * control for the input side.
721  *
722  * \param wsi: Websocket connection instance to get callback for
723  * \param enable: 0 = disable read servicing for this connection, 1 = enable
724  *
725  * If you need more than one additive reason for rxflow control, you can give
726  * iLWS_RXFLOW_REASON_APPLIES_ENABLE or _DISABLE together with one or more of
727  * b5..b0 set to idicate which bits to enable or disable. If any bits are
728  * enabled, rx on the connection is suppressed.
729  *
730  * LWS_RXFLOW_REASON_FLAG_PROCESS_NOW flag may also be given to force any change
731  * in rxflowbstatus to benapplied immediately, this should be used when you are
732  * changing a wsi flow control state from outside a callback on that wsi.
733  */
734 LWS_VISIBLE LWS_EXTERN int
735 lws_rx_flow_control(struct lws *wsi, int enable);
736 
737 /**
738  * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
739  *
740  * When the user server code realizes it can accept more input, it can
741  * call this to have the RX flow restriction removed from all connections using
742  * the given protocol.
743  * \param context: lws_context
744  * \param protocol: all connections using this protocol will be allowed to receive
745  */
746 LWS_VISIBLE LWS_EXTERN void
747 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
748  const struct lws_protocols *protocol);
749 
750 /**
751  * lws_remaining_packet_payload() - Bytes to come before "overall"
752  * rx fragment is complete
753  * \param wsi: Websocket instance (available from user callback)
754  *
755  * This tracks how many bytes are left in the current ws fragment, according
756  * to the ws length given in the fragment header.
757  *
758  * If the message was in a single fragment, and there is no compression, this
759  * is the same as "how much data is left to read for this message".
760  *
761  * However, if the message is being sent in multiple fragments, this will
762  * reflect the unread amount of the current **fragment**, not the message. With
763  * ws, it is legal to not know the length of the message before it completes.
764  *
765  * Additionally if the message is sent via the negotiated permessage-deflate
766  * extension, this number only tells the amount of **compressed** data left to
767  * be read, since that is the only information available at the ws layer.
768  */
769 LWS_VISIBLE LWS_EXTERN size_t
770 lws_remaining_packet_payload(struct lws *wsi);
771 
772 #if defined(LWS_WITH_DIR)
773 
774 typedef enum {
775  LDOT_UNKNOWN,
776  LDOT_FILE,
777  LDOT_DIR,
778  LDOT_LINK,
779  LDOT_FIFO,
780  LDOTT_SOCKET,
781  LDOT_CHAR,
782  LDOT_BLOCK
783 } lws_dir_obj_type_t;
784 
785 struct lws_dir_entry {
786  const char *name;
787  lws_dir_obj_type_t type;
788 };
789 
790 typedef int
791 lws_dir_callback_function(const char *dirpath, void *user,
792  struct lws_dir_entry *lde);
793 
794 /**
795  * lws_dir() - get a callback for everything in a directory
796  *
797  * \param dirpath: the directory to scan
798  * \param user: pointer to give to callback
799  * \param cb: callback to receive information on each file or dir
800  *
801  * Calls \p cb (with \p user) for every object in dirpath.
802  *
803  * This wraps whether it's using POSIX apis, or libuv (as needed for windows,
804  * since it refuses to support POSIX apis for this).
805  */
806 LWS_VISIBLE LWS_EXTERN int
807 lws_dir(const char *dirpath, void *user, lws_dir_callback_function cb);
808 
809 /**
810  * lws_dir_rm_rf_cb() - callback for lws_dir that performs recursive rm -rf
811  *
812  * \param dirpath: directory we are at in lws_dir
813  * \param user: ignored
814  * \param lde: lws_dir info on the file or directory we are at
815  *
816  * This is a readymade rm -rf callback for use with lws_dir. It recursively
817  * removes everything below the starting dir and then the starting dir itself.
818  * Works on linux, OSX and Windows at least.
819  */
820 LWS_VISIBLE LWS_EXTERN int
821 lws_dir_rm_rf_cb(const char *dirpath, void *user, struct lws_dir_entry *lde);
822 
823 /*
824  * We pass every file in the base dir through a filter, and call back on the
825  * ones that match. Directories are ignored.
826  *
827  * The original path filter string may look like, eg, "sai-*.deb" or "*.txt"
828  */
829 
830 typedef int (*lws_dir_glob_cb_t)(void *data, const char *path);
831 
832 typedef struct lws_dir_glob {
833  const char *filter;
834  lws_dir_glob_cb_t cb;
835  void *user;
836 } lws_dir_glob_t;
837 
838 /**
839  * lws_dir_glob_cb() - callback for lws_dir that performs filename globbing
840  *
841  * \param dirpath: directory we are at in lws_dir
842  * \param user: pointer to your prepared lws_dir_glob_cb_t
843  * \param lde: lws_dir info on the file or directory we are at
844  *
845  * \p user is prepared with an `lws_dir_glob_t` containing a callback for paths
846  * that pass the filtering, a user pointer to pass to that callback, and a
847  * glob string like "*.txt". It may not contain directories, the lws_dir musr
848  * be started at the correct dir.
849  *
850  * Only the base path passed to lws_dir is scanned, it does not look in subdirs.
851  */
852 LWS_VISIBLE LWS_EXTERN int
853 lws_dir_glob_cb(const char *dirpath, void *user, struct lws_dir_entry *lde);
854 
855 #endif
856 
857 /**
858  * lws_get_allocated_heap() - if the platform supports it, returns amount of
859  * heap allocated by lws itself
860  *
861  * On glibc currently, this reports the total amount of current logical heap
862  * allocation, found by tracking the amount allocated by lws_malloc() and
863  * friends and accounting for freed allocations via lws_free().
864  *
865  * This is useful for confirming where processwide heap allocations actually
866  * come from... this number represents all lws internal allocations, for
867  * fd tables, wsi allocations, ah, etc combined. It doesn't include allocations
868  * from user code, since lws_malloc() etc are not exported from the library.
869  *
870  * On other platforms, it always returns 0.
871  */
873 
874 /**
875  * lws_get_tsi() - Get thread service index wsi belong to
876  * \param wsi: websocket connection to check
877  *
878  * Returns more than zero (or zero if only one service thread as is the default).
879  */
880 LWS_VISIBLE LWS_EXTERN int
881 lws_get_tsi(struct lws *wsi);
882 
883 /**
884  * lws_is_ssl() - Find out if connection is using SSL
885  * \param wsi: websocket connection to check
886  *
887  * Returns nonzero if the wsi is inside a tls tunnel, else zero.
888  */
889 LWS_VISIBLE LWS_EXTERN int
890 lws_is_ssl(struct lws *wsi);
891 /**
892  * lws_is_cgi() - find out if this wsi is running a cgi process
893  *
894  * \param wsi: lws connection
895  */
896 LWS_VISIBLE LWS_EXTERN int
897 lws_is_cgi(struct lws *wsi);
898 
899 /**
900  * lws_tls_jit_trust_blob_queury_skid() - walk jit trust blob for skid
901  *
902  * \param _blob: the start of the blob in memory
903  * \param blen: the length of the blob in memory
904  * \param skid: the SKID we are looking for
905  * \param skid_len: the length of the SKID we are looking for
906  * \param prpder: result pointer to receive a pointer to the matching DER
907  * \param prder_len: result pointer to receive matching DER length
908  *
909  * Helper to scan a JIT Trust blob in memory for a trusted CA cert matching
910  * a given SKID. Returns 0 if found and *prpder and *prder_len are set, else
911  * nonzero.
912  */
913 LWS_VISIBLE LWS_EXTERN int
914 lws_tls_jit_trust_blob_queury_skid(const void *_blob, size_t blen,
915  const uint8_t *skid, size_t skid_len,
916  const uint8_t **prpder, size_t *prder_len);
917 
918 /**
919  * lws_open() - platform-specific wrapper for open that prepares the fd
920  *
921  * \param __file: the filepath to open
922  * \param __oflag: option flags
923  *
924  * This is a wrapper around platform open() that sets options on the fd
925  * according to lws policy. Currently that is FD_CLOEXEC to stop the opened
926  * fd being available to any child process forked by user code.
927  */
928 LWS_VISIBLE LWS_EXTERN int
929 lws_open(const char *__file, int __oflag, ...);
930 
931 struct lws_wifi_scan { /* generic wlan scan item */
933  char ssid[32];
934  int32_t rssi; /* divide by .count to get db */
939 };
940 
941 #if defined(LWS_WITH_TLS) && !defined(LWS_WITH_MBEDTLS)
942 /**
943  * lws_get_ssl() - Return wsi's SSL context structure
944  * \param wsi: websocket connection
945  *
946  * Returns pointer to the SSL library's context structure
947  */
948 LWS_VISIBLE LWS_EXTERN SSL*
949 lws_get_ssl(struct lws *wsi);
950 #endif
951 
952 LWS_VISIBLE LWS_EXTERN void
953 lws_explicit_bzero(void *p, size_t len);
954 
955 typedef struct lws_humanize_unit {
956  const char *name; /* array ends with NULL name */
958 } lws_humanize_unit_t;
959 
960 LWS_VISIBLE extern const lws_humanize_unit_t humanize_schema_si[7];
961 LWS_VISIBLE extern const lws_humanize_unit_t humanize_schema_si_bytes[7];
962 LWS_VISIBLE extern const lws_humanize_unit_t humanize_schema_us[8];
963 
964 #if defined(_DEBUG)
965 void
966 lws_assert_fourcc(uint32_t fourcc, uint32_t expected);
967 #else
968 #define lws_assert_fourcc(_a, _b) do { } while (0);
969 #endif
970 
971 /**
972  * lws_humanize() - Convert possibly large number to human-readable uints
973  *
974  * \param buf: result string buffer
975  * \param len: remaining length in \p buf
976  * \param value: the uint64_t value to represent
977  * \param schema: and array of scaling factors and units
978  *
979  * This produces a concise string representation of \p value, referencing the
980  * schema \p schema of scaling factors and units to find the smallest way to
981  * render it.
982  *
983  * Three schema are exported from lws for general use, humanize_schema_si, which
984  * represents as, eg, " 22.130Gi" or " 128 "; humanize_schema_si_bytes
985  * which is the same but shows, eg, " 22.130GiB", and humanize_schema_us,
986  * which represents a count of us as a human-readable time like " 14.350min",
987  * or " 1.500d".
988  *
989  * You can produce your own schema.
990  */
991 
992 LWS_VISIBLE LWS_EXTERN int
993 lws_humanize(char *buf, size_t len, uint64_t value,
994  const lws_humanize_unit_t *schema);
995 
996 LWS_VISIBLE LWS_EXTERN void
997 lws_ser_wu16be(uint8_t *b, uint16_t u);
998 
999 LWS_VISIBLE LWS_EXTERN void
1000 lws_ser_wu32be(uint8_t *b, uint32_t u32);
1001 
1002 LWS_VISIBLE LWS_EXTERN void
1003 lws_ser_wu64be(uint8_t *b, uint64_t u64);
1004 
1005 LWS_VISIBLE LWS_EXTERN uint16_t
1006 lws_ser_ru16be(const uint8_t *b);
1007 
1008 LWS_VISIBLE LWS_EXTERN uint32_t
1009 lws_ser_ru32be(const uint8_t *b);
1010 
1011 LWS_VISIBLE LWS_EXTERN uint64_t
1012 lws_ser_ru64be(const uint8_t *b);
1013 
1014 LWS_VISIBLE LWS_EXTERN int
1015 lws_vbi_encode(uint64_t value, void *buf);
1016 
1017 LWS_VISIBLE LWS_EXTERN int
1018 lws_vbi_decode(const void *buf, uint64_t *value, size_t len);
1019 
1020 ///@}
1021 
1022 #if defined(LWS_WITH_SPAWN)
1023 
1024 /* opaque internal struct */
1025 struct lws_spawn_piped;
1026 
1027 #if defined(WIN32)
1028 struct _lws_siginfo_t {
1029  int retcode;
1030 };
1031 typedef struct _lws_siginfo_t siginfo_t;
1032 #endif
1033 
1034 typedef void (*lsp_cb_t)(void *opaque, lws_usec_t *accounting, siginfo_t *si,
1035  int we_killed_him);
1036 
1037 
1038 /**
1039  * lws_spawn_piped_info - details given to create a spawned pipe
1040  *
1041  * \p owner: lws_dll2_owner_t that lists all active spawns, or NULL
1042  * \p vh: vhost to bind stdwsi to... from opt_parent if given
1043  * \p opt_parent: optional parent wsi for stdwsi
1044  * \p exec_array: argv for process to spawn
1045  * \p env_array: environment for spawned process, NULL ends env list
1046  * \p protocol_name: NULL, or vhost protocol name to bind stdwsi to
1047  * \p chroot_path: NULL, or chroot patch for child process
1048  * \p wd: working directory to cd to after fork, NULL defaults to /tmp
1049  * \p plsp: NULL, or pointer to the outer lsp pointer so it can be set NULL when destroyed
1050  * \p opaque: pointer passed to the reap callback, if any
1051  * \p timeout: optional us-resolution timeout, or zero
1052  * \p reap_cb: callback when child process has been reaped and the lsp destroyed
1053  * \p tsi: tsi to bind stdwsi to... from opt_parent if given
1054  */
1055 struct lws_spawn_piped_info {
1056  struct lws_dll2_owner *owner;
1057  struct lws_vhost *vh;
1058  struct lws *opt_parent;
1059 
1060  const char * const *exec_array;
1061  const char **env_array;
1062  const char *protocol_name;
1063  const char *chroot_path;
1064  const char *wd;
1065 
1066  struct lws_spawn_piped **plsp;
1067 
1068  void *opaque;
1069 
1070  lsp_cb_t reap_cb;
1071 
1072  lws_usec_t timeout_us;
1073  int max_log_lines;
1074  int tsi;
1075 
1076  const struct lws_role_ops *ops; /* NULL is raw file */
1077 
1078  uint8_t disable_ctrlc;
1079 };
1080 
1081 /**
1082  * lws_spawn_piped() - spawn a child process with stdxxx redirected
1083  *
1084  * \p lspi: info struct describing details of spawn to create
1085  *
1086  * This spawns a child process managed in the lsp object and with attributes
1087  * set in the arguments. The stdin/out/err streams are redirected to pipes
1088  * which are instantiated into wsi that become child wsi of \p parent if non-
1089  * NULL. .opaque_user_data on the stdwsi created is set to point to the
1090  * lsp object, so this can be recovered easily in the protocol handler.
1091  *
1092  * If \p owner is non-NULL, successful spawns join the given dll2 owner in the
1093  * original process.
1094  *
1095  * If \p timeout is non-zero, successful spawns register a sul with the us-
1096  * resolution timeout to callback \p timeout_cb, in the original process.
1097  *
1098  * Returns 0 if the spawn went OK or nonzero if it failed and was cleaned up.
1099  * The spawned process continues asynchronously and this will return after
1100  * starting it if all went well.
1101  */
1102 LWS_VISIBLE LWS_EXTERN struct lws_spawn_piped *
1103 lws_spawn_piped(const struct lws_spawn_piped_info *lspi);
1104 
1105 /*
1106  * lws_spawn_piped_kill_child_process() - attempt to kill child process
1107  *
1108  * \p lsp: child object to kill
1109  *
1110  * Attempts to signal the child process in \p lsp to terminate.
1111  */
1112 LWS_VISIBLE LWS_EXTERN int
1113 lws_spawn_piped_kill_child_process(struct lws_spawn_piped *lsp);
1114 
1115 /**
1116  * lws_spawn_stdwsi_closed() - inform the spawn one of its stdxxx pipes closed
1117  *
1118  * \p lsp: the spawn object
1119  * \p wsi: the wsi that is closing
1120  *
1121  * When you notice one of the spawn stdxxx pipes closed, inform the spawn
1122  * instance using this api. When it sees all three have closed, it will
1123  * automatically try to reap the child process.
1124  *
1125  * This is the mechanism whereby the spawn object can understand its child
1126  * has closed.
1127  */
1128 LWS_VISIBLE LWS_EXTERN void
1129 lws_spawn_stdwsi_closed(struct lws_spawn_piped *lsp, struct lws *wsi);
1130 
1131 /**
1132  * lws_spawn_get_stdfd() - return std channel index for stdwsi
1133  *
1134  * \p wsi: the wsi
1135  *
1136  * If you know wsi is a stdwsi from a spawn, you can determine its original
1137  * channel index / fd before the pipes replaced the default fds. It will return
1138  * one of 0 (STDIN), 1 (STDOUT) or 2 (STDERR). You can handle all three in the
1139  * same protocol handler and then disambiguate them using this api.
1140  */
1141 LWS_VISIBLE LWS_EXTERN int
1142 lws_spawn_get_stdfd(struct lws *wsi);
1143 
1144 #endif
1145 
1146 struct lws_fsmount {
1147  const char *layers_path; /* where layers live */
1148  const char *overlay_path; /* where overlay instantiations live */
1149 
1150  char mp[256]; /* mountpoint path */
1151  char ovname[64]; /* unique name for mount instance */
1152  char distro[64]; /* unique name for layer source */
1153 
1154 #if defined(__linux__)
1155  const char *layers[4]; /* distro layers, like "base", "env" */
1156 #endif
1157 };
1158 
1159 /**
1160  * lws_fsmount_mount() - Mounts an overlayfs stack of layers
1161  *
1162  * \p fsm: struct lws_fsmount specifying the mount layout
1163  *
1164  * This api is able to assemble up to 4 layer directories on to a mountpoint
1165  * using overlayfs mount (Linux only).
1166  *
1167  * Set fsm.layers_path to the base dir where the layers themselves live, the
1168  * entries in fsm.layers[] specifies the relative path to the layer, comprising
1169  * fsm.layers_path/fsm.distro/fsm.layers[], with [0] being the deepest, earliest
1170  * layer and the rest being progressively on top of [0]; NULL indicates the
1171  * layer is unused.
1172  *
1173  * fsm.overlay_path is the base path of the overlayfs instantiations... empty
1174  * dirs must exist at
1175  *
1176  * fsm.overlay_path/overlays/fsm.ovname/work
1177  * fsm.overlay_path/overlays/fsm.ovname/session
1178  *
1179  * Set fsm.mp to the path of an already-existing empty dir that will be the
1180  * mountpoint, this can be whereever you like.
1181  *
1182  * Overlayfs merges the union of all the contributing layers at the mountpoint,
1183  * the mount is writeable but the layer themselves are immutable, all additions
1184  * and changes are stored in
1185  *
1186  * fsm.overlay_path/overlays/fsm.ovname/session
1187  *
1188  * Returns 0 if mounted OK, nonzero if errors.
1189  *
1190  * Retain fsm for use with unmounting.
1191  */
1192 LWS_VISIBLE LWS_EXTERN int
1194 
1195 /**
1196  * lws_fsmount_unmount() - Unmounts an overlayfs dir
1197  *
1198  * \p fsm: struct lws_fsmount specifying the mount layout
1199  *
1200  * Unmounts the mountpoint in fsm.mp.
1201  *
1202  * Delete fsm.overlay_path/overlays/fsm.ovname/session to permanently eradicate
1203  * all changes from the time the mountpoint was in use.
1204  *
1205  * Returns 0 if unmounted OK.
1206  */
1207 LWS_VISIBLE LWS_EXTERN int
1209 
1210 #define LWS_MINILEX_FAIL -1
1211 #define LWS_MINILEX_CONTINUE 0
1212 #define LWS_MINILEX_MATCH 1
1213 
1214 /**
1215  * lws_minilex_parse() - stateful matching vs lws minilex tables
1216  *
1217  * \p lex: the start of the precomputed minilex table
1218  * \p ps: pointer to the int16_t that holds the parsing state (init to 0)
1219  * \p c: the next incoming character to parse
1220  * \p match: pointer to take the match
1221  *
1222  * Returns either
1223  *
1224  * - LWS_MINILEX_FAIL if there is no way to match the characters seen,
1225  * this is sticky for additional characters until the *ps is reset to 0.
1226  *
1227  * - LWS_MINILEX_CONTINUE if the character could be part of a match but more
1228  * are required to see if it can match
1229  *
1230  * - LWS_MINILEX_MATCH and *match is set to the match index if there is a
1231  * valid match.
1232  *
1233  * In cases where the match is ambiguous, eg, we saw "right" and the possible
1234  * matches are "right" or "right-on", LWS_MINILEX_CONTINUE is returned. To
1235  * allow it to match on the complete-but-ambiguous token, if the caller sees
1236  * a delimiter it can call lws_minilex_parse() again with c == 0. This will
1237  * either return LWS_MINILEX_MATCH and set *match to the smaller ambiguous
1238  * match, or return LWS_MINILEX_FAIL.
1239  */
1240 LWS_VISIBLE LWS_EXTERN int
1241 lws_minilex_parse(const uint8_t *lex, int16_t *ps, const uint8_t c,
1242  int *match);
1243 
1244 /*
1245  * Reports the number of significant bits (from the left) that is needed to
1246  * represent u. So if u is 0x80, result is 8.
1247  */
1248 
1249 LWS_VISIBLE LWS_EXTERN unsigned int
1250 lws_sigbits(uintptr_t u);