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
45struct 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 */
57LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
58lws_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 */
70LWS_VISIBLE LWS_EXTERN size_t
71lws_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 */
88LWS_VISIBLE LWS_EXTERN size_t
89lws_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 */
98LWS_VISIBLE LWS_EXTERN size_t
99lws_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 */
112LWS_VISIBLE LWS_EXTERN int
113lws_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 */
132LWS_VISIBLE LWS_EXTERN int
133lws_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: NULL, 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 * It's legal for buf to be NULL and / or len = 0. In this case nothing is
152 * "used" and the effect is to set `frag_first` according to if we are at the
153 * start of the fragment and 0 is returned.
154 *
155 * Returns the number of bytes written into \p buf.
156 */
157LWS_VISIBLE LWS_EXTERN int
158lws_buflist_fragment_use(struct lws_buflist **head, uint8_t *buf,
159 size_t len, char *frag_first, char *frag_fin);
160
161/**
162 * lws_buflist_destroy_all_segments(): free all segments on the list
163 *
164 * \param head: list head
165 *
166 * This frees everything on the list unconditionally. *head is always
167 * NULL after this.
168 */
169LWS_VISIBLE LWS_EXTERN void
170lws_buflist_destroy_all_segments(struct lws_buflist **head);
171
172/**
173 * lws_buflist_describe(): debug helper logging buflist status
174 *
175 * \param head: list head
176 * \param id: pointer shown in debug list
177 * \param reason: reason string show in debug list
178 *
179 * Iterates through the buflist segments showing position and size.
180 * This only exists when lws was built in debug mode
181 */
182LWS_VISIBLE LWS_EXTERN void
183lws_buflist_describe(struct lws_buflist **head, void *id, const char *reason);
184
185/**
186 * lws_buflist_get_frag_start_or_NULL(): get pointer to start of fragment
187 *
188 * \param head: list head
189 *
190 * This gets you a pointer to the start of the fragment payload, no matter
191 * how much of it you may have 'used' already. This is useful for schemes
192 * where you prepend something to the payload and need to reference it no
193 * matter how much of it you have consumed or the fragmentation details.
194 *
195 * If the buflist is empty, it will return NULL.
196 */
197LWS_VISIBLE LWS_EXTERN void *
198lws_buflist_get_frag_start_or_NULL(struct lws_buflist **head);
199
200
201struct lws_wsmsg_info;
202
203typedef void (*lws_wsmsg_transfer_cb)(struct lws_wsmsg_info *info);
204
205typedef struct lws_wsmsg_info {
206 struct lws_buflist **head_upstream; /* the upstream buflist */
207 struct lws_buflist **private_heads; /* the private reassembly heads */
208 int private_source_idx; /* which index to use in private_heads */
209 lws_wsmsg_transfer_cb optional_cb; /* optional transfer callback */
210 void *opaque; /* optional opaque pointer */
211 const uint8_t *buf; /* array to add */
212 size_t len; /* length of bytes in array */
213 unsigned int ss_flags; /* SS flags for SOM / EOM */
214} lws_wsmsg_info_t;
215
216/**
217 * lws_wsmsg_append() - append to buflist via private buflists
218 *
219 * \param info: the info struct, filled in before calling
220 *
221 * This api allows you to pass incoming fragments through a private buflist
222 * until the message it contains is reassembled and complete. At that point, if
223 * the upstream buflist is not blocked by being in the middle of a message itself,
224 * the fragments are added to the end of an upstream buflist and the private
225 * buflist left empty.
226 *
227 * As an optimization, if the upstream buflist is not blocked waiting for an EOM,
228 * the private buflist is empty, and the incoming data represents a complete
229 * message, then the incoming message is added directly to the upstream buflist.
230 *
231 * This method allows potentially many async connections with fragmented messages
232 * to contribute to a single buflist containing only complete messages. It's
233 * not possible to add a partial message (without the EOM flag) to the upstream
234 * buflist; when all parts of it have arrived it will be added.
235 *
236 * An array of private buflists is supported so that messages from many different
237 * connections can be reassembled before moving to the upstream buflist.
238 *
239 * Optionally, instead of transfer to another buflist when the message is complete,
240 * if the optional_cb is provided, this is called instead with the info struct, so
241 * arbitrary operations can be performed by the user.
242 *
243 * The info->opaque pointer is not used by lws, it's there to facilitate passing
244 * related user parameters in the callback case.
245 */
246LWS_VISIBLE LWS_EXTERN int
247lws_wsmsg_append(lws_wsmsg_info_t *info);
248
249/*
250 * lws_wsmsg_destroy() - free all allocations in private buflists
251 *
252 * \param private_heads: the private buflists
253 * \param count_private_heads: the number of private buflists
254 */
255LWS_VISIBLE LWS_EXTERN void
256lws_wsmsg_destroy(struct lws_buflist *private_heads[], size_t count_private_heads);
257
258
259
260/*
261 * Optional helpers for closely-managed stream flow control. These are useful
262 * when there is no memory for large rx buffers and instead tx credit is being
263 * used to regulate the server sending data.
264 *
265 * When combined with stateful consumption-on-demand, this can be very effective
266 * at managing data flows through restricted circumstances. These helpers
267 * implement a golden implementation that can be bound to a stream in its priv
268 * data.
269 *
270 * The helper is sophisticated enough to contain a buflist to manage overflows
271 * on heap and preferentially drain it. RX goes through heap to guarantee the
272 * consumer can exit cleanly at any time.
273 */
274
275enum {
276 LWSDLOFLOW_STATE_READ, /* default, we want input */
277 LWSDLOFLOW_STATE_READ_COMPLETED, /* we do not need further rx, every-
278 * thing is locally buffered or used */
279 LWSDLOFLOW_STATE_READ_FAILED, /* operation has fatal error */
280};
281
282struct lws_ss_handle;
283
284typedef struct lws_flow {
285 lws_dll2_t list;
286
287 struct lws_ss_handle *h;
288 struct lws_buflist *bl;
289
290 const uint8_t *data;
291 size_t len; /* bytes left in data */
292 uint32_t blseglen; /* bytes issued */
293 int32_t window;
294
295 uint8_t state;
296} lws_flow_t;
297
298/**
299 * lws_flow_feed() - consume waiting data if ready for it
300 *
301 * \param flow: pointer to the flow struct managing waiting data
302 *
303 * This will bring out waiting data from the flow buflist when it is needed.
304 */
305LWS_VISIBLE LWS_EXTERN lws_stateful_ret_t
306lws_flow_feed(lws_flow_t *flow);
307
308/**
309 * lws_flow_req() - request remote data if we have run low
310 *
311 * \param flow: pointer to the flow struct managing waiting data
312 *
313 * When the estimated remote tx credit is below flow->window, accounting for
314 * what is in the buflist, add to the peer tx credit so it can send us more.
315 */
316LWS_VISIBLE LWS_EXTERN lws_stateful_ret_t
317lws_flow_req(lws_flow_t *flow);
318
319/**
320 * lws_ptr_diff(): helper to report distance between pointers as an int
321 *
322 * \param head: the pointer with the larger address
323 * \param tail: the pointer with the smaller address
324 *
325 * This helper gives you an int representing the number of bytes further
326 * forward the first pointer is compared to the second pointer.
327 */
328#define lws_ptr_diff(head, tail) \
329 ((int)((char *)(head) - (char *)(tail)))
330
331#define lws_ptr_diff_size_t(head, tail) \
332 ((size_t)(ssize_t)((char *)(head) - (char *)(tail)))
333
334/**
335 * lws_snprintf(): snprintf that truncates the returned length too
336 *
337 * \param str: destination buffer
338 * \param size: bytes left in destination buffer
339 * \param format: format string
340 * \param ...: args for format
341 *
342 * This lets you correctly truncate buffers by concatenating lengths, if you
343 * reach the limit the reported length doesn't exceed the limit.
344 */
345LWS_VISIBLE LWS_EXTERN int
346lws_snprintf(char *str, size_t size, const char *format, ...) LWS_FORMAT(3);
347
348/**
349 * lws_strncpy(): strncpy that guarantees NUL on truncated copy
350 *
351 * \param dest: destination buffer
352 * \param src: source buffer
353 * \param size: bytes left in destination buffer
354 *
355 * This lets you correctly truncate buffers by concatenating lengths, if you
356 * reach the limit the reported length doesn't exceed the limit.
357 */
358LWS_VISIBLE LWS_EXTERN char *
359lws_strncpy(char *dest, const char *src, size_t size);
360
361/*
362 * Variation where we want to use the smaller of two lengths, useful when the
363 * source string is not NUL terminated
364 */
365#define lws_strnncpy(dest, src, size1, destsize) \
366 lws_strncpy(dest, src, (size_t)(size1 + 1) < (size_t)(destsize) ? \
367 (size_t)(size1 + 1) : (size_t)(destsize))
368
369/**
370 * lws_nstrstr(): like strstr for length-based strings without terminating NUL
371 *
372 * \param buf: the string to search
373 * \param len: the length of the string to search
374 * \param name: the substring to search for
375 * \param nl: the length of name
376 *
377 * Returns NULL if \p name is not present in \p buf. Otherwise returns the
378 * address of the first instance of \p name in \p buf.
379 *
380 * Neither buf nor name need to be NUL-terminated.
381 */
382LWS_VISIBLE LWS_EXTERN const char *
383lws_nstrstr(const char *buf, size_t len, const char *name, size_t nl);
384
385/**
386 * lws_json_simple_find(): dumb JSON string parser
387 *
388 * \param buf: the JSON to search
389 * \param len: the length of the JSON to search
390 * \param name: the name field to search the JSON for, eg, "\"myname\":"
391 * \param alen: set to the length of the argument part if non-NULL return
392 *
393 * Either returns NULL if \p name is not present in buf, or returns a pointer
394 * to the argument body of the first instance of \p name, and sets *alen to the
395 * length of the argument body.
396 *
397 * This can cheaply handle fishing out, eg, myarg from {"myname": "myarg"} by
398 * searching for "\"myname\":". It will return a pointer to myarg and set *alen
399 * to 5. It equally handles args like "myname": true, or "myname":false, and
400 * null or numbers are all returned as delimited strings.
401 *
402 * Anything more complicated like the value is a subobject or array, you should
403 * parse it using a full parser like lejp. This is suitable is the JSON is
404 * and will remain short and simple, and contains well-known names amongst other
405 * extensible JSON members.
406 */
407LWS_VISIBLE LWS_EXTERN const char *
408lws_json_simple_find(const char *buf, size_t len, const char *name, size_t *alen);
409
410/**
411 * lws_json_simple_strcmp(): dumb JSON string comparison
412 *
413 * \param buf: the JSON to search
414 * \param len: the length of the JSON to search
415 * \param name: the name field to search the JSON for, eg, "\"myname\":"
416 * \param comp: return a strcmp of this and the discovered argument
417 *
418 * Helper that combines lws_json_simple_find() with strcmp() if it was found.
419 * If the \p name was not found, returns -1. Otherwise returns a strcmp()
420 * between what was found and \p comp, ie, return 0 if they match or something
421 * else if they don't.
422 *
423 * If the JSON is relatively simple and you want to target constrained
424 * devices, this can be a good choice. If the JSON may be complex, you
425 * should use a full JSON parser.
426 */
427LWS_VISIBLE LWS_EXTERN int
428lws_json_simple_strcmp(const char *buf, size_t len, const char *name, const char *comp);
429
430/**
431 * lws_hex_len_to_byte_array(): convert hex string like 0123456789ab into byte data
432 *
433 * \param h: incoming hex string
434 * \param hlen: number of chars to process at \p h
435 * \param dest: array to fill with binary decodes of hex pairs from h
436 * \param max: maximum number of bytes dest can hold, must be at least half
437 * the size of strlen(h)
438 *
439 * This converts hex strings into an array of 8-bit representations, ie the
440 * input "abcd" produces two bytes of value 0xab and 0xcd.
441 *
442 * Returns number of bytes produced into \p dest, or -1 on error.
443 *
444 * Errors include non-hex chars and an odd count of hex chars in the input
445 * string.
446 */
447LWS_VISIBLE LWS_EXTERN int
448lws_hex_len_to_byte_array(const char *h, size_t hlen, uint8_t *dest, int max);
449
450/**
451 * lws_hex_to_byte_array(): convert hex string like 0123456789ab into byte data
452 *
453 * \param h: incoming NUL-terminated hex string
454 * \param dest: array to fill with binary decodes of hex pairs from h
455 * \param max: maximum number of bytes dest can hold, must be at least half
456 * the size of strlen(h)
457 *
458 * This converts hex strings into an array of 8-bit representations, ie the
459 * input "abcd" produces two bytes of value 0xab and 0xcd.
460 *
461 * Returns number of bytes produced into \p dest, or -1 on error.
462 *
463 * Errors include non-hex chars and an odd count of hex chars in the input
464 * string.
465 */
466LWS_VISIBLE LWS_EXTERN int
467lws_hex_to_byte_array(const char *h, uint8_t *dest, int max);
468
469/**
470 * lws_hex_from_byte_array(): render byte array as hex char string
471 *
472 * \param src: incoming binary source array
473 * \param slen: length of src in bytes
474 * \param dest: array to fill with hex chars representing src
475 * \param len: max extent of dest
476 *
477 * This converts binary data of length slen at src, into a hex string at dest
478 * of maximum length len. Even if truncated, the result will be NUL-terminated.
479 */
480LWS_VISIBLE LWS_EXTERN void
481lws_hex_from_byte_array(const uint8_t *src, size_t slen, char *dest, size_t len);
482
483/**
484 * lws_hex_random(): generate len - 1 or - 2 characters of random ascii hex
485 *
486 * \param context: the lws_context used to get the random
487 * \param dest: destination for hex ascii chars
488 * \param len: the number of bytes the buffer dest points to can hold
489 *
490 * This creates random ascii-hex strings up to a given length, with a
491 * terminating NUL.
492 *
493 * There will not be any characters produced that are not 0-9, a-f, so it's
494 * safe to go straight into, eg, JSON.
495 */
496LWS_VISIBLE LWS_EXTERN int
497lws_hex_random(struct lws_context *context, char *dest, size_t len);
498
499/*
500 * lws_timingsafe_bcmp(): constant time memcmp
501 *
502 * \param a: first buffer
503 * \param b: second buffer
504 * \param len: count of bytes to compare
505 *
506 * Return 0 if the two buffers are the same, else nonzero.
507 *
508 * Always compares all of the buffer before returning, so it can't be used as
509 * a timing oracle.
510 */
511
512LWS_VISIBLE LWS_EXTERN int
513lws_timingsafe_bcmp(const void *a, const void *b, uint32_t len);
514
515/**
516 * lws_get_random(): fill a buffer with platform random data
517 *
518 * \param context: the lws context
519 * \param buf: buffer to fill
520 * \param len: how much to fill
521 *
522 * Fills buf with len bytes of random. Returns the number of bytes set, if
523 * not equal to len, then getting the random failed.
524 */
525LWS_VISIBLE LWS_EXTERN size_t
526lws_get_random(struct lws_context *context, void *buf, size_t len);
527/**
528 * lws_daemonize(): make current process run in the background
529 *
530 * \param _lock_path: the filepath to write the lock file
531 *
532 * Spawn lws as a background process, taking care of various things
533 */
534LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
535lws_daemonize(const char *_lock_path);
536/**
537 * lws_get_library_version(): return string describing the version of lws
538 *
539 * On unix, also includes the git describe
540 */
541LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
542lws_get_library_version(void);
543
544/**
545 * lws_wsi_user() - get the user data associated with the connection
546 * \param wsi: lws connection
547 *
548 * Not normally needed since it's passed into the callback
549 */
550LWS_VISIBLE LWS_EXTERN void *
551lws_wsi_user(struct lws *wsi);
552
553/**
554 * lws_wsi_tsi() - get the service thread index the wsi is bound to
555 * \param wsi: lws connection
556 *
557 * Only useful is LWS_MAX_SMP > 1
558 */
559LWS_VISIBLE LWS_EXTERN int
560lws_wsi_tsi(struct lws *wsi);
561
562/**
563 * lws_set_wsi_user() - set the user data associated with the client connection
564 * \param wsi: lws connection
565 * \param user: user data
566 *
567 * By default lws allocates this and it's not legal to externally set it
568 * yourself. However client connections may have it set externally when the
569 * connection is created... if so, this api can be used to modify it at
570 * runtime additionally.
571 */
572LWS_VISIBLE LWS_EXTERN void
573lws_set_wsi_user(struct lws *wsi, void *user);
574
575/**
576 * lws_parse_uri: cut up prot:/ads:port/path into pieces
577 * Notice it does so by dropping '\0' into input string
578 * and the leading / on the path is consequently lost
579 *
580 * \param p: incoming uri string.. will get written to
581 * \param prot: result pointer for protocol part (https://)
582 * \param ads: result pointer for address part
583 * \param port: result pointer for port part
584 * \param path: result pointer for path part
585 *
586 * You may also refer to unix socket addresses, using a '+' at the start of
587 * the address. In this case, the address should end with ':', which is
588 * treated as the separator between the address and path (the normal separator
589 * '/' is a valid part of the socket path). Eg,
590 *
591 * http://+/var/run/mysocket:/my/path
592 *
593 * If the first character after the + is '@', it's interpreted by lws client
594 * processing as meaning to use linux abstract namespace sockets, the @ is
595 * replaced with a '\0' before use.
596 */
597LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
598lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
599 const char **path);
600/**
601 * lws_cmdline_option(): simple commandline parser
602 *
603 * \param argc: count of argument strings
604 * \param argv: argument strings
605 * \param val: string to find
606 *
607 * Returns NULL if the string \p val is not found in the arguments.
608 *
609 * This only returns the first hit for \p val.
610 *
611 * If it is found, then it returns a pointer to the next character after \p val.
612 * So if \p val is "-d", then for the commandlines "myapp -d15" and
613 * "myapp -d 15", in both cases the return will point to the "15".
614 *
615 * In the case there is no argument, like "myapp -d", the return will
616 * either point to the '\\0' at the end of -d, or to the start of the
617 * next argument, ie, will be non-NULL.
618 *
619 * This original api variant does not handle stdin-passed commandline content,
620 * only that present in the passed argc / argv.
621 */
622LWS_VISIBLE LWS_EXTERN const char *
623lws_cmdline_option(int argc, const char **argv, const char *val);
624
625/**
626 * lws_cmdline_options(): simple commandline parser
627 *
628 * \param argc: count of argument strings
629 * \param argv: argument strings
630 * \param val: string to find
631 * \param last: last successful return from previous call
632 *
633 * Returns NULL if the string \p val is not found in the arguments.
634 *
635 * Before checking, the api aligns itself to the place of the \p last
636 * hit (or the beginning of the commandline if NULL), and starts checking
637 * from just beyond that. In this way you can get the first, or
638 * incrementally get multiple results, for every hit.
639 *
640 * If a match is found, then it returns a pointer to the next character after \p val.
641 * So if \p val is "-d", then for the commandlines "myapp -d15" and
642 * "myapp -d 15", in both cases the return will point to the "15".
643 *
644 * In the case there is no argument, like "myapp -d", the return will
645 * either point to the '\\0' at the end of -d, or to the start of the
646 * next argument, ie, will be non-NULL indicating success.
647 *
648 * This original api variant does not handle stdin-passed commandline content,
649 * only that present in the passed argc / argv.
650 */
651LWS_VISIBLE LWS_EXTERN const char *
652lws_cmdline_options(int argc, const char * const *argv, const char *val, const char *last);
653
654/**
655 * lws_cmdline_options_cx(): simple commandline parser
656 *
657 * \param cx: the lws_context
658 * \param val: string to find
659 * \param last: last successful return from previous call
660 *
661 * Returns NULL if the string \p val is not found in the arguments.
662 *
663 * Before checking, the api aligns itself to the place of the \p last
664 * hit (or the beginning of the commandline if NULL), and starts checking
665 * from just beyond that. In this way you can get the first, or
666 * incrementally get multiple results, for every hit.
667 *
668 * If a match is found, then it returns a pointer to the next character after \p val.
669 * So if \p val is "-d", then for the commandlines "myapp -d15" and
670 * "myapp -d 15", in both cases the return will point to the "15".
671 *
672 * In the case there is no argument, like "myapp -d", the return will
673 * either point to the '\\0' at the end of -d, or to the start of the
674 * next argument, ie, will be non-NULL indicating success.
675 *
676 * This api variant handles stdin-passed commandline content, placing it
677 * after the argc / argv content. You must ensure the context creation
678 * info .argc and .argv were set to the application's main argc and argv,
679 * either manually or it is handled for you as a side-effect of calling
680 * lws_cmdline_option_handle_builtin().
681 */
682
683LWS_VISIBLE LWS_EXTERN const char *
684lws_cmdline_options_cx(const struct lws_context *cx, const char *val, const char *last);
685
686/**
687 * lws_cmdline_option_cx(): simple commandline parser
688 *
689 * \param cx: the lws_context
690 * \param val: string to find
691 *
692 * Returns NULL if the string \p val is not found in the arguments.
693 *
694 * This only returns the first hit for \p val.
695 *
696 * If a match is found, then it returns a pointer to the next character after \p val.
697 * So if \p val is "-d", then for the commandlines "myapp -d15" and
698 * "myapp -d 15", in both cases the return will point to the "15".
699 *
700 * In the case there is no argument, like "myapp -d", the return will
701 * either point to the '\\0' at the end of -d, or to the start of the
702 * next argument, ie, will be non-NULL indicating success.
703 *
704 * This api variant handles stdin-passed commandline content, placing it
705 * after the argc / argv content. You must ensure the context creation
706 * info .argc and .argv were set to the application's main argc and argv,
707 * either manually or it is handled for you as a side-effect of calling
708 * lws_cmdline_option_handle_builtin().
709 */
710LWS_VISIBLE LWS_EXTERN const char *
711lws_cmdline_option_cx(const struct lws_context *cx, const char *val);
712
713/**
714 * lws_cmdline_option_handle_builtin(): apply standard cmdline options
715 *
716 * \param argc: count of argument strings
717 * \param argv: argument strings
718 * \param info: context creation info
719 *
720 * Applies standard options to the context creation info to save them having
721 * to be (unevenly) copied into the minimal examples.
722 *
723 * Applies default log levels that can be overriden by -d
724 */
725LWS_VISIBLE LWS_EXTERN void
726lws_cmdline_option_handle_builtin(int argc, const char **argv,
727 struct lws_context_creation_info *info);
728
729/**
730 * lws_now_secs(): return seconds since 1970-1-1
731 */
732LWS_VISIBLE LWS_EXTERN unsigned long
733lws_now_secs(void);
734
735/**
736 * lws_now_usecs(): return useconds since 1970-1-1
737 */
738LWS_VISIBLE LWS_EXTERN lws_usec_t
739lws_now_usecs(void);
740
741/**
742 * lws_get_context - Allow getting lws_context from a Websocket connection
743 * instance
744 *
745 * With this function, users can access context in the callback function.
746 * Otherwise users may have to declare context as a global variable.
747 *
748 * \param wsi: Websocket connection instance
749 */
750LWS_VISIBLE LWS_EXTERN struct lws_context * LWS_WARN_UNUSED_RESULT
751lws_get_context(const struct lws *wsi);
752
753/**
754 * lws_get_vhost_listen_port - Find out the port number a vhost is listening on
755 *
756 * In the case you passed 0 for the port number at context creation time, you
757 * can discover the port number that was actually chosen for the vhost using
758 * this api.
759 *
760 * \param vhost: Vhost to get listen port from
761 */
762LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
763lws_get_vhost_listen_port(struct lws_vhost *vhost);
764
765/**
766 * lws_get_count_threads(): how many service threads the context uses
767 *
768 * \param context: the lws context
769 *
770 * By default this is always 1, if you asked for more than lws can handle it
771 * will clip the number of threads. So you can use this to find out how many
772 * threads are actually in use.
773 */
774LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
775lws_get_count_threads(struct lws_context *context);
776
777/**
778 * lws_get_parent() - get parent wsi or NULL
779 * \param wsi: lws connection
780 *
781 * Specialized wsi like cgi stdin/out/err are associated to a parent wsi,
782 * this allows you to get their parent.
783 */
784LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
785lws_get_parent(const struct lws *wsi);
786
787/**
788 * lws_get_child() - get child wsi or NULL
789 * \param wsi: lws connection
790 *
791 * Allows you to find a related wsi from the parent wsi.
792 */
793LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
794lws_get_child(const struct lws *wsi);
795
796/**
797 * lws_get_effective_uid_gid() - find out eventual uid and gid while still root
798 *
799 * \param context: lws context
800 * \param uid: pointer to uid result
801 * \param gid: pointer to gid result
802 *
803 * This helper allows you to find out what the uid and gid for the process will
804 * be set to after the privileges are dropped, beforehand. So while still root,
805 * eg in LWS_CALLBACK_PROTOCOL_INIT, you can arrange things like cache dir
806 * and subdir creation / permissions down /var/cache dynamically.
807 */
808LWS_VISIBLE LWS_EXTERN void
809lws_get_effective_uid_gid(struct lws_context *context, uid_t *uid, gid_t *gid);
810
811/**
812 * lws_get_udp() - get wsi's udp struct
813 *
814 * \param wsi: lws connection
815 *
816 * Returns NULL or pointer to the wsi's UDP-specific information
817 */
818LWS_VISIBLE LWS_EXTERN const struct lws_udp * LWS_WARN_UNUSED_RESULT
819lws_get_udp(const struct lws *wsi);
820
821LWS_VISIBLE LWS_EXTERN void *
822lws_get_opaque_parent_data(const struct lws *wsi);
823
824LWS_VISIBLE LWS_EXTERN void
825lws_set_opaque_parent_data(struct lws *wsi, void *data);
826
827LWS_VISIBLE LWS_EXTERN void *
828lws_get_opaque_user_data(const struct lws *wsi);
829
830LWS_VISIBLE LWS_EXTERN void
831lws_set_opaque_user_data(struct lws *wsi, void *data);
832
833LWS_VISIBLE LWS_EXTERN int
834lws_get_child_pending_on_writable(const struct lws *wsi);
835
836LWS_VISIBLE LWS_EXTERN void
837lws_clear_child_pending_on_writable(struct lws *wsi);
838
839LWS_VISIBLE LWS_EXTERN int
840lws_get_close_length(struct lws *wsi);
841
842LWS_VISIBLE LWS_EXTERN unsigned char *
843lws_get_close_payload(struct lws *wsi);
844
845/**
846 * lws_get_network_wsi() - Returns wsi that has the tcp connection for this wsi
847 *
848 * \param wsi: wsi you have
849 *
850 * Returns wsi that has the tcp connection (which may be the incoming wsi)
851 *
852 * HTTP/1 connections will always return the incoming wsi
853 * HTTP/2 connections may return a different wsi that has the tcp connection
854 */
855LWS_VISIBLE LWS_EXTERN
856struct lws *lws_get_network_wsi(struct lws *wsi);
857
858/**
859 * lws_set_allocator() - custom allocator support
860 *
861 * \param realloc
862 *
863 * Allows you to replace the allocator (and deallocator) used by lws
864 */
865LWS_VISIBLE LWS_EXTERN void
866lws_set_allocator(void *(*realloc)(void *ptr, size_t size, const char *reason));
867
868enum {
869 /*
870 * Flags for enable and disable rxflow with reason bitmap and with
871 * backwards-compatible single bool
872 */
873 LWS_RXFLOW_REASON_USER_BOOL = (1 << 0),
874 LWS_RXFLOW_REASON_HTTP_RXBUFFER = (1 << 6),
875 LWS_RXFLOW_REASON_H2_PPS_PENDING = (1 << 7),
876
877 LWS_RXFLOW_REASON_APPLIES = (1 << 14),
878 LWS_RXFLOW_REASON_APPLIES_ENABLE_BIT = (1 << 13),
879 LWS_RXFLOW_REASON_APPLIES_ENABLE = LWS_RXFLOW_REASON_APPLIES |
880 LWS_RXFLOW_REASON_APPLIES_ENABLE_BIT,
881 LWS_RXFLOW_REASON_APPLIES_DISABLE = LWS_RXFLOW_REASON_APPLIES,
882 LWS_RXFLOW_REASON_FLAG_PROCESS_NOW = (1 << 12),
883
884};
885
886/**
887 * lws_rx_flow_control() - Enable and disable socket servicing for
888 * received packets.
889 *
890 * If the output side of a server process becomes choked, this allows flow
891 * control for the input side.
892 *
893 * \param wsi: Websocket connection instance to get callback for
894 * \param enable: 0 = disable read servicing for this connection, 1 = enable
895 *
896 * If you need more than one additive reason for rxflow control, you can give
897 * iLWS_RXFLOW_REASON_APPLIES_ENABLE or _DISABLE together with one or more of
898 * b5..b0 set to idicate which bits to enable or disable. If any bits are
899 * enabled, rx on the connection is suppressed.
900 *
901 * LWS_RXFLOW_REASON_FLAG_PROCESS_NOW flag may also be given to force any change
902 * in rxflowbstatus to benapplied immediately, this should be used when you are
903 * changing a wsi flow control state from outside a callback on that wsi.
904 */
905LWS_VISIBLE LWS_EXTERN int
906lws_rx_flow_control(struct lws *wsi, int enable);
907
908/**
909 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
910 *
911 * When the user server code realizes it can accept more input, it can
912 * call this to have the RX flow restriction removed from all connections using
913 * the given protocol.
914 * \param context: lws_context
915 * \param protocol: all connections using this protocol will be allowed to receive
916 */
917LWS_VISIBLE LWS_EXTERN void
918lws_rx_flow_allow_all_protocol(const struct lws_context *context,
919 const struct lws_protocols *protocol);
920
921/**
922 * lws_remaining_packet_payload() - Bytes to come before "overall"
923 * rx fragment is complete
924 * \param wsi: Websocket instance (available from user callback)
925 *
926 * This tracks how many bytes are left in the current ws fragment, according
927 * to the ws length given in the fragment header.
928 *
929 * If the message was in a single fragment, and there is no compression, this
930 * is the same as "how much data is left to read for this message".
931 *
932 * However, if the message is being sent in multiple fragments, this will
933 * reflect the unread amount of the current **fragment**, not the message. With
934 * ws, it is legal to not know the length of the message before it completes.
935 *
936 * Additionally if the message is sent via the negotiated permessage-deflate
937 * extension, zero is always reported. You should use lws_is_final_fragment()
938 * to find out if you have completed the message... in compressed case, it holds
939 * back reporting the final fragment until it's also the final decompressed
940 * block issued.
941 */
942LWS_VISIBLE LWS_EXTERN size_t
943lws_remaining_packet_payload(struct lws *wsi);
944
945#if defined(LWS_WITH_DIR)
946
947typedef enum {
948 LDOT_UNKNOWN,
949 LDOT_FILE,
950 LDOT_DIR,
951 LDOT_LINK,
952 LDOT_FIFO,
953 LDOTT_SOCKET,
954 LDOT_CHAR,
955 LDOT_BLOCK
956} lws_dir_obj_type_t;
957
958struct lws_dir_entry {
959 const char *name;
960 lws_dir_obj_type_t type;
961};
962
963typedef int
964lws_dir_callback_function(const char *dirpath, void *user,
965 struct lws_dir_entry *lde);
966
967struct lws_dir_info {
968 const char *dirpath;
969 void *user;
970 lws_dir_callback_function *cb;
971 unsigned char do_toplevel_cb:1;
972};
973
974/**
975 * lws_dir() - get a callback for everything in a directory
976 *
977 * \param dirpath: the directory to scan
978 * \param user: pointer to give to callback
979 * \param cb: callback to receive information on each file or dir
980 *
981 * Calls \p cb (with \p user) for every object in dirpath.
982 *
983 * This form does not call the callback for the toplevel, dirpath dir
984 * itself. If you want to do that, use lws_dir_via_info(), with
985 * .do_toplevel_cb nonzero.
986 *
987 * This wraps whether it's using POSIX apis, or libuv (as needed for windows,
988 * since it refuses to support POSIX apis for this).
989 *
990 * Returns 1 if completed normally or 0 if the recursion ended early.
991 *
992 * This is here for historical reasons, use the below lws_dir_via_info() for
993 * new code, it's the same function but using an info struct type args.
994 */
995LWS_VISIBLE LWS_EXTERN int
996lws_dir(const char *dirpath, void *user, lws_dir_callback_function cb);
997
998/**
999 * lws_dir_via_info() - get a callback for everything in a directory
1000 *
1001 * \param info: details of what to scan and how
1002 *
1003 * All of the members of \p info should be set on entry.
1004 *
1005 * Calls \p info.cb (with \p info.user) for every object in info.dirpath.
1006 *
1007 * Set \p info.do_toplevel_cb to nonzero if you also want the callback to
1008 * be called for the toplevel dir, ie, dirpath itself.
1009 *
1010 * This wraps whether it's using POSIX apis, or libuv (as needed for windows,
1011 * since it refuses to support POSIX apis for this).
1012 *
1013 * Returns 1 if completed normally or 0 if the recursion ended early.
1014 */
1015LWS_VISIBLE LWS_EXTERN int
1016lws_dir_via_info(struct lws_dir_info *info);
1017
1018
1019/**
1020 * lws_dir_rm_rf_cb() - callback for lws_dir that performs recursive rm -rf
1021 *
1022 * \param dirpath: directory we are at in lws_dir
1023 * \param user: ignored
1024 * \param lde: lws_dir info on the file or directory we are at
1025 *
1026 * This is a readymade rm -rf callback for use with lws_dir. It recursively
1027 * removes everything below the starting dir and then the starting dir itself.
1028 * Works on linux, OSX and Windows at least.
1029 */
1030LWS_VISIBLE LWS_EXTERN int
1031lws_dir_rm_rf_cb(const char *dirpath, void *user, struct lws_dir_entry *lde);
1032
1033
1034/**
1035 * lws_dir_du_t: context for lws_dir_du_cb()
1036 *
1037 * It's zeroed before starting the lws_dir() walk.
1038 */
1039
1040typedef struct lws_dir_du {
1041 uint64_t size_in_bytes;
1042 uint32_t count_files;
1043} lws_dir_du_t;
1044
1045/**
1046 * lws_dir_du_cb() - callback for lws_dir that performs recursive du
1047 *
1048 * \param dirpath: directory we are at in lws_dir
1049 * \param user: pointer to a lws_dir_du_t to collate the results in
1050 * \param lde: lws_dir info on the file or directory we are at
1051 *
1052 * This is a readymade du -b callback for use with lws_dir. It recursively
1053 * sums the sizes of all files it finds and the count of files. The user
1054 an
1055 * lws_dir_du_t struct should be zeroed before starting the walk.
1056 */
1057LWS_VISIBLE LWS_EXTERN int
1058lws_dir_du_cb(const char *dirpath, void *user, struct lws_dir_entry *lde);
1059
1060
1061/*
1062 * We pass every file in the base dir through a filter, and call back on the
1063 * ones that match. Directories are ignored.
1064 *
1065 * The original path filter string may look like, eg, "sai-*.deb" or "*.txt"
1066 */
1067
1068typedef int (*lws_dir_glob_cb_t)(void *data, const char *path);
1069
1070typedef struct lws_dir_glob {
1071 const char *filter;
1072 lws_dir_glob_cb_t cb;
1073 void *user;
1074} lws_dir_glob_t;
1075
1076/**
1077 * lws_dir_glob_cb() - callback for lws_dir that performs filename globbing
1078 *
1079 * \param dirpath: directory we are at in lws_dir
1080 * \param user: pointer to your prepared lws_dir_glob_cb_t
1081 * \param lde: lws_dir info on the file or directory we are at
1082 *
1083 * \p user is prepared with an `lws_dir_glob_t` containing a callback for paths
1084 * that pass the filtering, a user pointer to pass to that callback, and a
1085 * glob string like "*.txt". It may not contain directories, the lws_dir musr
1086 * be started at the correct dir.
1087 *
1088 * Only the base path passed to lws_dir is scanned, it does not look in subdirs.
1089 */
1090LWS_VISIBLE LWS_EXTERN int
1091lws_dir_glob_cb(const char *dirpath, void *user, struct lws_dir_entry *lde);
1092
1093#endif
1094
1095/**
1096 * lws_get_allocated_heap() - if the platform supports it, returns amount of
1097 * heap allocated by lws itself
1098 *
1099 * On glibc currently, this reports the total amount of current logical heap
1100 * allocation, found by tracking the amount allocated by lws_malloc() and
1101 * friends and accounting for freed allocations via lws_free().
1102 *
1103 * This is useful for confirming where processwide heap allocations actually
1104 * come from... this number represents all lws internal allocations, for
1105 * fd tables, wsi allocations, ah, etc combined. It doesn't include allocations
1106 * from user code, since lws_malloc() etc are not exported from the library.
1107 *
1108 * On other platforms, it always returns 0.
1109 */
1110size_t lws_get_allocated_heap(void);
1111
1112/**
1113 * lws_get_tsi() - Get thread service index wsi belong to
1114 * \param wsi: websocket connection to check
1115 *
1116 * Returns more than zero (or zero if only one service thread as is the default).
1117 */
1118LWS_VISIBLE LWS_EXTERN int
1119lws_get_tsi(struct lws *wsi);
1120
1121/**
1122 * lws_is_ssl() - Find out if connection is using SSL
1123 * \param wsi: websocket connection to check
1124 *
1125 * Returns nonzero if the wsi is inside a tls tunnel, else zero.
1126 */
1127LWS_VISIBLE LWS_EXTERN int
1128lws_is_ssl(struct lws *wsi);
1129/**
1130 * lws_is_cgi() - find out if this wsi is running a cgi process
1131 *
1132 * \param wsi: lws connection
1133 */
1134LWS_VISIBLE LWS_EXTERN int
1135lws_is_cgi(struct lws *wsi);
1136
1137/**
1138 * lws_tls_jit_trust_blob_queury_skid() - walk jit trust blob for skid
1139 *
1140 * \param _blob: the start of the blob in memory
1141 * \param blen: the length of the blob in memory
1142 * \param skid: the SKID we are looking for
1143 * \param skid_len: the length of the SKID we are looking for
1144 * \param prpder: result pointer to receive a pointer to the matching DER
1145 * \param prder_len: result pointer to receive matching DER length
1146 *
1147 * Helper to scan a JIT Trust blob in memory for a trusted CA cert matching
1148 * a given SKID. Returns 0 if found and *prpder and *prder_len are set, else
1149 * nonzero.
1150 */
1151LWS_VISIBLE LWS_EXTERN int
1152lws_tls_jit_trust_blob_queury_skid(const void *_blob, size_t blen,
1153 const uint8_t *skid, size_t skid_len,
1154 const uint8_t **prpder, size_t *prder_len);
1155
1156/**
1157 * lws_open() - platform-specific wrapper for open that prepares the fd
1158 *
1159 * \param __file: the filepath to open
1160 * \param __oflag: option flags
1161 *
1162 * This is a wrapper around platform open() that sets options on the fd
1163 * according to lws policy. Currently that is FD_CLOEXEC to stop the opened
1164 * fd being available to any child process forked by user code.
1165 */
1166LWS_VISIBLE LWS_EXTERN int
1167lws_open(const char *__file, int __oflag, ...);
1168
1169struct lws_wifi_scan { /* generic wlan scan item */
1170 struct lws_wifi_scan *next;
1171 char ssid[32];
1172 int32_t rssi; /* divide by .count to get db */
1173 uint8_t bssid[6];
1174 uint8_t count;
1175 uint8_t channel;
1176 uint8_t authmode;
1177};
1178
1179#if defined(LWS_WITH_TLS) && !defined(LWS_WITH_MBEDTLS)
1180/**
1181 * lws_get_ssl() - Return wsi's SSL context structure
1182 * \param wsi: websocket connection
1183 *
1184 * Returns pointer to the SSL library's context structure
1185 */
1186LWS_VISIBLE LWS_EXTERN SSL*
1187lws_get_ssl(struct lws *wsi);
1188#endif
1189
1190LWS_VISIBLE LWS_EXTERN void
1191lws_explicit_bzero(void *p, size_t len);
1192
1193typedef struct lws_humanize_unit {
1194 const char *name; /* array ends with NULL name */
1195 uint64_t factor;
1196} lws_humanize_unit_t;
1197
1198LWS_VISIBLE extern const lws_humanize_unit_t humanize_schema_si[7];
1199LWS_VISIBLE extern const lws_humanize_unit_t humanize_schema_si_bytes[7];
1200LWS_VISIBLE extern const lws_humanize_unit_t humanize_schema_us[8];
1201
1202#if defined(_DEBUG)
1203void
1204lws_assert_fourcc(uint32_t fourcc, uint32_t expected);
1205#else
1206#define lws_assert_fourcc(_a, _b) do { } while (0);
1207#endif
1208
1209/**
1210 * lws_humanize() - Convert possibly large number to human-readable uints
1211 *
1212 * \param buf: result string buffer
1213 * \param len: remaining length in \p buf
1214 * \param value: the uint64_t value to represent
1215 * \param schema: and array of scaling factors and units
1216 *
1217 * This produces a concise string representation of \p value, referencing the
1218 * schema \p schema of scaling factors and units to find the smallest way to
1219 * render it.
1220 *
1221 * Three schema are exported from lws for general use, humanize_schema_si, which
1222 * represents as, eg, " 22.130Gi" or " 128 "; humanize_schema_si_bytes
1223 * which is the same but shows, eg, " 22.130GiB", and humanize_schema_us,
1224 * which represents a count of us as a human-readable time like " 14.350min",
1225 * or " 1.500d".
1226 *
1227 * You can produce your own schema tables.
1228 *
1229 * lws_humanize_pad() is the same but pads the lhs so that it
1230 * always produces the same length.
1231 */
1232
1233LWS_VISIBLE LWS_EXTERN int
1234lws_humanize(char *buf, size_t len, uint64_t value,
1235 const lws_humanize_unit_t *schema);
1236
1237LWS_VISIBLE LWS_EXTERN int
1238lws_humanize_pad(char *p, size_t len, uint64_t v,
1239 const lws_humanize_unit_t *schema);
1240
1241LWS_VISIBLE LWS_EXTERN void
1242lws_ser_wu16be(uint8_t *b, uint16_t u);
1243
1244LWS_VISIBLE LWS_EXTERN void
1245lws_ser_wu32be(uint8_t *b, uint32_t u32);
1246
1247LWS_VISIBLE LWS_EXTERN void
1248lws_ser_wu64be(uint8_t *b, uint64_t u64);
1249
1250LWS_VISIBLE LWS_EXTERN uint16_t
1251lws_ser_ru16be(const uint8_t *b);
1252
1253LWS_VISIBLE LWS_EXTERN uint32_t
1254lws_ser_ru32be(const uint8_t *b);
1255
1256LWS_VISIBLE LWS_EXTERN uint64_t
1257lws_ser_ru64be(const uint8_t *b);
1258
1259LWS_VISIBLE LWS_EXTERN int
1260lws_vbi_encode(uint64_t value, void *buf);
1261
1262LWS_VISIBLE LWS_EXTERN int
1263lws_vbi_decode(const void *buf, uint64_t *value, size_t len);
1264
1265///@}
1266
1267#if defined(LWS_WITH_SPAWN)
1268
1269/* opaque internal struct */
1270struct lws_spawn_piped;
1271
1272#if defined(WIN32)
1273struct _lws_siginfo_t {
1274 int retcode;
1275};
1276typedef struct _lws_siginfo_t siginfo_t;
1277#endif
1278
1279/**
1280 * lws_spawn_resource_us_t - resource usage results from spawned process
1281 *
1282 * All time values are in uS.
1283 * All size values are in bytes.
1284 */
1285typedef struct lws_spawn_resource_us {
1286 uint64_t us_cpu_user; /**< user space cpu time */
1287 uint64_t us_cpu_sys; /**< kernel space cpu time */
1288
1289 uint64_t peak_mem_rss; /**< peak resident memory */
1290 uint64_t peak_mem_virt; /**< peak virtual memory */
1291} lws_spawn_resource_us_t;
1292
1293typedef void (*lsp_cb_t)(void *opaque, const lws_spawn_resource_us_t *res,
1294 siginfo_t *si, int we_killed_him);
1295
1296
1297/**
1298 * lws_spawn_piped_info - details given to create a spawned pipe
1299 *
1300 * \p owner: lws_dll2_owner_t that lists all active spawns, or NULL
1301 * \p vh: vhost to bind stdwsi to... from opt_parent if given
1302 * \p opt_parent: optional parent wsi for stdwsi
1303 * \p exec_array: argv for process to spawn
1304 * \p env_array: environment for spawned process, NULL ends env list
1305 * \p protocol_name: NULL, or vhost protocol name to bind stdwsi to
1306 * \p chroot_path: NULL, or chroot patch for child process
1307 * \p wd: working directory to cd to after fork, NULL defaults to /tmp
1308 * \p plsp: NULL, or pointer to the outer lsp pointer so it can be set NULL when destroyed
1309 * \p opaque: pointer passed to the reap callback, if any
1310 * \p reap_cb: callback when child process has been reaped and the lsp destroyed
1311 * \p tsi: tsi to bind stdwsi to... from opt_parent if given
1312 * \p cgroup_name_suffix: for Linux, encapsulate spawn into this new cgroup
1313 * \p p_cgroup_ret: NULL, or pointer to int to show if cgroups applied OK (0 = OK)
1314 * \p pres: NULL, or pointer to a lws_spawn_resource_us_t to take the results
1315 */
1316struct lws_spawn_piped_info {
1317 struct lws_dll2_owner *owner;
1318 struct lws_vhost *vh;
1319 struct lws *opt_parent;
1320
1321 const char * const *exec_array;
1322 const char **env_array;
1323 const char *protocol_name;
1324 const char *chroot_path;
1325 const char *wd;
1326
1327 struct lws_spawn_piped **plsp;
1328
1329 void *opaque;
1330
1331 lsp_cb_t reap_cb;
1332
1333 lws_spawn_resource_us_t *res;
1334
1335 lws_usec_t timeout_us;
1336 int max_log_lines;
1337 int tsi;
1338
1339 const struct lws_role_ops *ops; /* NULL is raw file */
1340
1341 uint8_t disable_ctrlc;
1342
1343 const char *cgroup_name_suffix;
1344 int *p_cgroup_ret;
1345};
1346
1347/**
1348 * lws_spawn_piped() - spawn a child process with stdxxx redirected
1349 *
1350 * \p lspi: info struct describing details of spawn to create
1351 *
1352 * This spawns a child process managed in the lsp object and with attributes
1353 * set in the arguments. The stdin/out/err streams are redirected to pipes
1354 * which are instantiated into wsi that become child wsi of \p parent if non-
1355 * NULL. .opaque_user_data on the stdwsi created is set to point to the
1356 * lsp object, so this can be recovered easily in the protocol handler.
1357 *
1358 * If \p owner is non-NULL, successful spawns join the given dll2 owner in the
1359 * original process.
1360 *
1361 * If \p timeout is non-zero, successful spawns register a sul with the us-
1362 * resolution timeout to callback \p timeout_cb, in the original process.
1363 *
1364 * Returns 0 if the spawn went OK or nonzero if it failed and was cleaned up.
1365 * The spawned process continues asynchronously and this will return after
1366 * starting it if all went well.
1367 */
1368LWS_VISIBLE LWS_EXTERN struct lws_spawn_piped *
1369lws_spawn_piped(const struct lws_spawn_piped_info *lspi);
1370
1371/*
1372 * lws_spawn_piped_kill_child_process() - attempt to kill child process
1373 *
1374 * \p lsp: child object to kill
1375 *
1376 * Attempts to signal the child process in \p lsp to terminate.
1377 */
1378LWS_VISIBLE LWS_EXTERN int
1379lws_spawn_piped_kill_child_process(struct lws_spawn_piped *lsp);
1380
1381/**
1382 * lws_spawn_get_stdwsi_open_count() - return stdwsi unclosed count
1383 *
1384 * \p lsp: the spawn object
1385 *
1386 * Returns number of stdwsi left unclosed on the lsp.
1387 */
1388LWS_VISIBLE LWS_EXTERN int
1389lws_spawn_get_stdwsi_open_count(struct lws_spawn_piped *lsp);
1390
1391/**
1392 * lws_spawn_stdwsi_closed() - inform the spawn one of its stdxxx pipes closed
1393 *
1394 * \p lsp: the spawn object
1395 * \p wsi: the wsi that is closing
1396 *
1397 * When you notice one of the spawn stdxxx pipes closed, inform the spawn
1398 * instance using this api. When it sees all three have closed, it will
1399 * automatically try to reap the child process.
1400 *
1401 * This is the mechanism whereby the spawn object can understand its child
1402 * has closed.
1403 *
1404 * Returns non-zero if there are no more stdwsi to wait for.
1405 */
1406LWS_VISIBLE LWS_EXTERN int
1407lws_spawn_stdwsi_closed(struct lws_spawn_piped *lsp, struct lws *wsi);
1408
1409/*
1410 * lws_spawn_closedown_stdwsis() - forcibly close the spawner side of stdwsi pipes
1411 *
1412 * \p lsp: the spawn object
1413 *
1414 * Closes the spawner side of all the stdwsi for an lsp that are still open.
1415 */
1416LWS_VISIBLE LWS_EXTERN void
1417lws_spawn_closedown_stdwsis(struct lws_spawn_piped *lsp);
1418
1419/**
1420 * lws_spawn_get_stdfd() - return std channel index for stdwsi
1421 *
1422 * \p wsi: the wsi
1423 *
1424 * If you know wsi is a stdwsi from a spawn, you can determine its original
1425 * channel index / fd before the pipes replaced the default fds. It will return
1426 * one of 0 (STDIN), 1 (STDOUT) or 2 (STDERR). You can handle all three in the
1427 * same protocol handler and then disambiguate them using this api.
1428 */
1429LWS_VISIBLE LWS_EXTERN int
1430lws_spawn_get_stdfd(struct lws *wsi);
1431
1432/**
1433 * lws_spawn_get_fd_stdxxx() - return fd belonging to lws side of spawn stdxxx
1434 *
1435 * \p lsp: the opaque pointer returned from lws_spawn()
1436 * \p std_idx: 0 (stdin write side), 1 (stdout read side), 2 (stderr read side)
1437 *
1438 * Lets you get the fd for writing to the spawned process stdin, or reading from
1439 * the spawned process stdout and stderr.
1440 */
1441LWS_VISIBLE LWS_EXTERN int
1442lws_spawn_get_fd_stdxxx(struct lws_spawn_piped *lsp, int std_idx);
1443
1444/**
1445 * lws_spawn_prepare_self_cgroup() - Create lws parent cgroup
1446 *
1447 * \p user: NULL, or the user name that will use the toplevel cgroup
1448 * \p group: NULL, or the group name that will use the toplevel cgroup
1449 *
1450 * This helper should be called once at startup by a process that has root
1451 * privileges. It will configure the current process cgroup to be able to
1452 * bring children into it when running under different uid / gid.
1453 *
1454 * After this has been called successfully, the process can drop privileges
1455 * to a non-root user, and subsequent calls to lws_spawn_piped() with a
1456 * cgroup_name_suffix will succeed as long as that user has write permission
1457 * in the master cgroup directory (which can be arranged via chown).
1458 *
1459 * Returns 0 on success. On non-Linux platforms, it's a no-op that returns 1.
1460 */
1461LWS_VISIBLE LWS_EXTERN int
1462lws_spawn_prepare_self_cgroup(const char *user, const char *group);
1463
1464/**
1465 * lws_spawn_get_self_cgroup() - Return current process cgroup name
1466 *
1467 * \p cgroup: buffer to take cgroup name
1468 * \p max: max size of cgroup buffer
1469 *
1470 * Helper stores cgroup name of current process into the buffer.
1471 * Returns 0 on success or 1 if failed.
1472 *
1473 * Returned name is a fragment like "system.slice/sai-builder.service"
1474 */
1475LWS_VISIBLE LWS_EXTERN int
1476lws_spawn_get_self_cgroup(char *cgroup, size_t max);
1477
1478#endif
1479
1480struct lws_fsmount {
1481 const char *layers_path; /* where layers live */
1482 const char *overlay_path; /* where overlay instantiations live */
1483
1484 char mp[256]; /* mountpoint path */
1485 char ovname[64]; /* unique name for mount instance */
1486 char distro[64]; /* unique name for layer source */
1487
1488#if defined(__linux__)
1489 const char *layers[4]; /* distro layers, like "base", "env" */
1490#endif
1491};
1492
1493/**
1494 * lws_fsmount_mount() - Mounts an overlayfs stack of layers
1495 *
1496 * \p fsm: struct lws_fsmount specifying the mount layout
1497 *
1498 * This api is able to assemble up to 4 layer directories on to a mountpoint
1499 * using overlayfs mount (Linux only).
1500 *
1501 * Set fsm.layers_path to the base dir where the layers themselves live, the
1502 * entries in fsm.layers[] specifies the relative path to the layer, comprising
1503 * fsm.layers_path/fsm.distro/fsm.layers[], with [0] being the deepest, earliest
1504 * layer and the rest being progressively on top of [0]; NULL indicates the
1505 * layer is unused.
1506 *
1507 * fsm.overlay_path is the base path of the overlayfs instantiations... empty
1508 * dirs must exist at
1509 *
1510 * fsm.overlay_path/overlays/fsm.ovname/work
1511 * fsm.overlay_path/overlays/fsm.ovname/session
1512 *
1513 * Set fsm.mp to the path of an already-existing empty dir that will be the
1514 * mountpoint, this can be whereever you like.
1515 *
1516 * Overlayfs merges the union of all the contributing layers at the mountpoint,
1517 * the mount is writeable but the layer themselves are immutable, all additions
1518 * and changes are stored in
1519 *
1520 * fsm.overlay_path/overlays/fsm.ovname/session
1521 *
1522 * Returns 0 if mounted OK, nonzero if errors.
1523 *
1524 * Retain fsm for use with unmounting.
1525 */
1526LWS_VISIBLE LWS_EXTERN int
1527lws_fsmount_mount(struct lws_fsmount *fsm);
1528
1529/**
1530 * lws_fsmount_unmount() - Unmounts an overlayfs dir
1531 *
1532 * \p fsm: struct lws_fsmount specifying the mount layout
1533 *
1534 * Unmounts the mountpoint in fsm.mp.
1535 *
1536 * Delete fsm.overlay_path/overlays/fsm.ovname/session to permanently eradicate
1537 * all changes from the time the mountpoint was in use.
1538 *
1539 * Returns 0 if unmounted OK.
1540 */
1541LWS_VISIBLE LWS_EXTERN int
1542lws_fsmount_unmount(struct lws_fsmount *fsm);
1543
1544#define LWS_MINILEX_FAIL -1
1545#define LWS_MINILEX_CONTINUE 0
1546#define LWS_MINILEX_MATCH 1
1547
1548/**
1549 * lws_minilex_parse() - stateful matching vs lws minilex tables
1550 *
1551 * \p lex: the start of the precomputed minilex table
1552 * \p ps: pointer to the int16_t that holds the parsing state (init to 0)
1553 * \p c: the next incoming character to parse
1554 * \p match: pointer to take the match
1555 *
1556 * Returns either
1557 *
1558 * - LWS_MINILEX_FAIL if there is no way to match the characters seen,
1559 * this is sticky for additional characters until the *ps is reset to 0.
1560 *
1561 * - LWS_MINILEX_CONTINUE if the character could be part of a match but more
1562 * are required to see if it can match
1563 *
1564 * - LWS_MINILEX_MATCH and *match is set to the match index if there is a
1565 * valid match.
1566 *
1567 * In cases where the match is ambiguous, eg, we saw "right" and the possible
1568 * matches are "right" or "right-on", LWS_MINILEX_CONTINUE is returned. To
1569 * allow it to match on the complete-but-ambiguous token, if the caller sees
1570 * a delimiter it can call lws_minilex_parse() again with c == 0. This will
1571 * either return LWS_MINILEX_MATCH and set *match to the smaller ambiguous
1572 * match, or return LWS_MINILEX_FAIL.
1573 */
1574LWS_VISIBLE LWS_EXTERN int
1575lws_minilex_parse(const uint8_t *lex, int16_t *ps, const uint8_t c,
1576 int *match);
1577
1578/*
1579 * Reports the number of significant bits (from the left) that is needed to
1580 * represent u. So if u is 0x80, result is 8.
1581 */
1582
1583LWS_VISIBLE LWS_EXTERN unsigned int
1584lws_sigbits(uintptr_t u);
1585
1586/**
1587 * lws_wol() - broadcast a magic WOL packet to MAC, optionally binding to if IP
1588 *
1589 * \p ctx: The lws context
1590 * \p ip_or_NULL: The IP address to bind to at the client side, to send the
1591 * magic packet on. If NULL, the system chooses, probably the
1592 * interface with the default route.
1593 * \p mac_6_bytes: Points to a 6-byte MAC address to direct the magic packet to
1594 */
1595LWS_VISIBLE LWS_EXTERN int
1596lws_wol(struct lws_context *ctx, const char *ip_or_NULL, uint8_t *mac_6_bytes);
1597