docs: swap _all_protocol_vhost cut and paste
[platform/upstream/libwebsockets.git] / lib / libwebsockets.h
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2016 Andy Green <andy@warmcat.com>
5  *
6  *  This library is free software; you can redistribute it and/or
7  *  modify it under the terms of the GNU Lesser General Public
8  *  License as published by the Free Software Foundation:
9  *  version 2.1 of the License.
10  *
11  *  This library is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  *  Lesser General Public License for more details.
15  *
16  *  You should have received a copy of the GNU Lesser General Public
17  *  License along with this library; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19  *  MA  02110-1301  USA
20  */
21
22 /** @file */
23
24 #ifndef LIBWEBSOCKET_H_3060898B846849FF9F88F5DB59B5950C
25 #define LIBWEBSOCKET_H_3060898B846849FF9F88F5DB59B5950C
26
27 #ifdef __cplusplus
28 #include <cstddef>
29 #include <cstdarg>
30 #
31 extern "C" {
32 #else
33 #include <stdarg.h>
34 #endif
35
36 #include "lws_config.h"
37
38 /*
39  * CARE: everything using cmake defines needs to be below here
40  */
41
42 #if defined(LWS_WITH_ESP8266)
43 struct sockaddr_in;
44 #define LWS_POSIX 0
45 #else
46 #define LWS_POSIX 1
47 #endif
48
49 #if defined(LWS_HAS_INTPTR_T)
50 #include <stdint.h>
51 #define lws_intptr_t intptr_t
52 #else
53 typedef unsigned long long lws_intptr_t;
54 #endif
55
56 #if defined(WIN32) || defined(_WIN32)
57 #ifndef WIN32_LEAN_AND_MEAN
58 #define WIN32_LEAN_AND_MEAN
59 #endif
60
61 #include <winsock2.h>
62 #include <ws2tcpip.h>
63 #include <stddef.h>
64 #include <basetsd.h>
65 #ifndef _WIN32_WCE
66 #include <fcntl.h>
67 #else
68 #define _O_RDONLY       0x0000
69 #define O_RDONLY        _O_RDONLY
70 #endif
71
72 // Visual studio older than 2015 and WIN_CE has only _stricmp
73 #if (defined(_MSC_VER) && _MSC_VER < 1900) || defined(_WIN32_WCE)
74 #define strcasecmp _stricmp
75 #elif !defined(__MINGW32__)
76 #define strcasecmp stricmp
77 #endif
78 #define getdtablesize() 30000
79
80 #define LWS_INLINE __inline
81 #define LWS_VISIBLE
82 #define LWS_WARN_UNUSED_RESULT
83 #define LWS_WARN_DEPRECATED
84 #define LWS_FORMAT(string_index)
85
86 #ifdef LWS_DLL
87 #ifdef LWS_INTERNAL
88 #define LWS_EXTERN extern __declspec(dllexport)
89 #else
90 #define LWS_EXTERN extern __declspec(dllimport)
91 #endif
92 #else
93 #define LWS_EXTERN
94 #endif
95
96 #define LWS_INVALID_FILE INVALID_HANDLE_VALUE
97 #define LWS_O_RDONLY _O_RDONLY
98 #define LWS_O_WRONLY _O_WRONLY
99 #define LWS_O_CREAT _O_CREAT
100 #define LWS_O_TRUNC _O_TRUNC
101
102 #if !defined(__MINGW32__) && (!defined(_MSC_VER) || _MSC_VER < 1900) /* Visual Studio 2015 already defines this in <stdio.h> */
103 #define lws_snprintf _snprintf
104 #endif
105
106 #ifndef __func__
107 #define __func__ __FUNCTION__
108 #endif
109
110 #if !defined(__MINGW32__) &&(!defined(_MSC_VER) || _MSC_VER < 1900) && !defined(snprintf)
111 #define snprintf(buf,len, format,...) _snprintf_s(buf, len,len, format, __VA_ARGS__)
112 #endif
113
114 #else /* NOT WIN32 */
115 #include <unistd.h>
116 #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
117 #include <sys/capability.h>
118 #endif
119
120 #if defined(__NetBSD__) || defined(__FreeBSD__)
121 #include <netinet/in.h>
122 #endif
123
124 #define LWS_INLINE inline
125 #define LWS_O_RDONLY O_RDONLY
126 #define LWS_O_WRONLY O_WRONLY
127 #define LWS_O_CREAT O_CREAT
128 #define LWS_O_TRUNC O_TRUNC
129
130 #if !defined(LWS_WITH_ESP8266) && !defined(OPTEE_TA) && !defined(LWS_WITH_ESP32)
131 #include <poll.h>
132 #include <netdb.h>
133 #define LWS_INVALID_FILE -1
134 #else
135 #define getdtablesize() (30)
136 #if defined(LWS_WITH_ESP32)
137 #define LWS_INVALID_FILE NULL
138 #else
139 #define LWS_INVALID_FILE NULL
140 #endif
141 #endif
142
143 #if defined(__GNUC__)
144
145 /* warn_unused_result attribute only supported by GCC 3.4 or later */
146 #if __GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
147 #define LWS_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
148 #else
149 #define LWS_WARN_UNUSED_RESULT
150 #endif
151
152 #define LWS_VISIBLE __attribute__((visibility("default")))
153 #define LWS_WARN_DEPRECATED __attribute__ ((deprecated))
154 #define LWS_FORMAT(string_index) __attribute__ ((format(printf, string_index, string_index+1)))
155 #else
156 #define LWS_VISIBLE
157 #define LWS_WARN_UNUSED_RESULT
158 #define LWS_WARN_DEPRECATED
159 #define LWS_FORMAT(string_index)
160 #endif
161
162 #if defined(__ANDROID__)
163 #include <unistd.h>
164 #define getdtablesize() sysconf(_SC_OPEN_MAX)
165 #endif
166
167 #endif
168
169 #ifdef LWS_USE_LIBEV
170 #include <ev.h>
171 #endif /* LWS_USE_LIBEV */
172 #ifdef LWS_USE_LIBUV
173 #include <uv.h>
174 #ifdef LWS_HAVE_UV_VERSION_H
175 #include <uv-version.h>
176 #endif
177 #endif /* LWS_USE_LIBUV */
178 #ifdef LWS_USE_LIBEVENT
179 #include <event2/event.h>
180 #endif /* LWS_USE_LIBEVENT */
181
182 #ifndef LWS_EXTERN
183 #define LWS_EXTERN extern
184 #endif
185
186 #ifdef _WIN32
187 #define random rand
188 #else
189 #if !defined(OPTEE_TA)
190 #include <sys/time.h>
191 #include <unistd.h>
192 #endif
193 #endif
194
195 #ifdef LWS_OPENSSL_SUPPORT
196
197 #ifdef USE_WOLFSSL
198 #ifdef USE_OLD_CYASSL
199 #include <cyassl/openssl/ssl.h>
200 #include <cyassl/error-ssl.h>
201 #else
202 #include <wolfssl/openssl/ssl.h>
203 #include <wolfssl/error-ssl.h>
204 #endif /* not USE_OLD_CYASSL */
205 #else
206 #include <openssl/ssl.h>
207 #if !defined(LWS_WITH_ESP32)
208 #include <openssl/err.h>
209 #endif
210 #endif /* not USE_WOLFSSL */
211 #endif
212
213
214 #define CONTEXT_PORT_NO_LISTEN -1
215 #define CONTEXT_PORT_NO_LISTEN_SERVER -2
216
217 /** \defgroup log Logging
218  *
219  * ##Logging
220  *
221  * Lws provides flexible and filterable logging facilities, which can be
222  * used inside lws and in user code.
223  *
224  * Log categories may be individually filtered bitwise, and directed to built-in
225  * sinks for syslog-compatible logging, or a user-defined function.
226  */
227 ///@{
228
229 enum lws_log_levels {
230         LLL_ERR = 1 << 0,
231         LLL_WARN = 1 << 1,
232         LLL_NOTICE = 1 << 2,
233         LLL_INFO = 1 << 3,
234         LLL_DEBUG = 1 << 4,
235         LLL_PARSER = 1 << 5,
236         LLL_HEADER = 1 << 6,
237         LLL_EXT = 1 << 7,
238         LLL_CLIENT = 1 << 8,
239         LLL_LATENCY = 1 << 9,
240         LLL_USER = 1 << 10,
241
242         LLL_COUNT = 11 /* set to count of valid flags */
243 };
244
245 LWS_VISIBLE LWS_EXTERN void _lws_log(int filter, const char *format, ...) LWS_FORMAT(2);
246 LWS_VISIBLE LWS_EXTERN void _lws_logv(int filter, const char *format, va_list vl);
247 /**
248  * lwsl_timestamp: generate logging timestamp string
249  *
250  * \param level:        logging level
251  * \param p:            char * buffer to take timestamp
252  * \param len:  length of p
253  *
254  * returns length written in p
255  */
256 LWS_VISIBLE LWS_EXTERN int
257 lwsl_timestamp(int level, char *p, int len);
258
259 /* these guys are unconditionally included */
260
261 #define lwsl_err(...) _lws_log(LLL_ERR, __VA_ARGS__)
262 #define lwsl_user(...) _lws_log(LLL_USER, __VA_ARGS__)
263
264 #if !defined(LWS_WITH_NO_LOGS)
265 /* notice and warn are usually included by being compiled in */
266 #define lwsl_warn(...) _lws_log(LLL_WARN, __VA_ARGS__)
267 #define lwsl_notice(...) _lws_log(LLL_NOTICE, __VA_ARGS__)
268 #endif
269 /*
270  *  weaker logging can be deselected by telling CMake to build in RELEASE mode
271  *  that gets rid of the overhead of checking while keeping _warn and _err
272  *  active
273  */
274
275 #if defined(LWS_WITH_ESP8266)
276 #undef _DEBUG
277 #endif
278
279 #ifdef _DEBUG
280 #if defined(LWS_WITH_NO_LOGS)
281 /* notice, warn and log are always compiled in */
282 #define lwsl_warn(...) _lws_log(LLL_WARN, __VA_ARGS__)
283 #define lwsl_notice(...) _lws_log(LLL_NOTICE, __VA_ARGS__)
284 #endif
285 #define lwsl_info(...) _lws_log(LLL_INFO, __VA_ARGS__)
286 #define lwsl_debug(...) _lws_log(LLL_DEBUG, __VA_ARGS__)
287 #define lwsl_parser(...) _lws_log(LLL_PARSER, __VA_ARGS__)
288 #define lwsl_header(...)  _lws_log(LLL_HEADER, __VA_ARGS__)
289 #define lwsl_ext(...)  _lws_log(LLL_EXT, __VA_ARGS__)
290 #define lwsl_client(...) _lws_log(LLL_CLIENT, __VA_ARGS__)
291 #define lwsl_latency(...) _lws_log(LLL_LATENCY, __VA_ARGS__)
292 /**
293  * lwsl_hexdump() - helper to hexdump a buffer (DEBUG builds only)
294  *
295  * \param buf: buffer start to dump
296  * \param len: length of buffer to dump
297  */
298 LWS_VISIBLE LWS_EXTERN void lwsl_hexdump(void *buf, size_t len);
299
300 #else /* no debug */
301 #if defined(LWS_WITH_NO_LOGS)
302 #define lwsl_warn(...) do {} while(0)
303 #define lwsl_notice(...) do {} while(0)
304 #endif
305 #define lwsl_info(...) do {} while(0)
306 #define lwsl_debug(...) do {} while(0)
307 #define lwsl_parser(...) do {} while(0)
308 #define lwsl_header(...) do {} while(0)
309 #define lwsl_ext(...) do {} while(0)
310 #define lwsl_client(...) do {} while(0)
311 #define lwsl_latency(...) do {} while(0)
312 #define lwsl_hexdump(a, b)
313
314 #endif
315
316 static LWS_INLINE int lws_is_be(void) {
317         const int probe = ~0xff;
318
319         return *(const char *)&probe;
320 }
321
322 /**
323  * lws_set_log_level() - Set the logging bitfield
324  * \param level:        OR together the LLL_ debug contexts you want output from
325  * \param log_emit_function:    NULL to leave it as it is, or a user-supplied
326  *                      function to perform log string emission instead of
327  *                      the default stderr one.
328  *
329  *      log level defaults to "err", "warn" and "notice" contexts enabled and
330  *      emission on stderr.
331  */
332 LWS_VISIBLE LWS_EXTERN void
333 lws_set_log_level(int level,
334                   void (*log_emit_function)(int level, const char *line));
335
336 /**
337  * lwsl_emit_syslog() - helper log emit function writes to system log
338  *
339  * \param level: one of LLL_ log level indexes
340  * \param line: log string
341  *
342  * You use this by passing the function pointer to lws_set_log_level(), to set
343  * it as the log emit function, it is not called directly.
344  */
345 LWS_VISIBLE LWS_EXTERN void
346 lwsl_emit_syslog(int level, const char *line);
347
348 /**
349  * lwsl_visible() - returns true if the log level should be printed
350  *
351  * \param level: one of LLL_ log level indexes
352  *
353  * This is useful if you have to do work to generate the log content, you
354  * can skip the work if the log level used to print it is not actually
355  * enabled at runtime.
356  */
357 LWS_VISIBLE LWS_EXTERN int
358 lwsl_visible(int level);
359
360 ///@}
361
362
363 #include <stddef.h>
364
365 #ifndef lws_container_of
366 #define lws_container_of(P,T,M) ((T *)((char *)(P) - offsetof(T, M)))
367 #endif
368
369
370 struct lws;
371 #ifndef ARRAY_SIZE
372 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
373 #endif
374
375 /* api change list for user code to test against */
376
377 #define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_ARG
378
379 /* the struct lws_protocols has the id field present */
380 #define LWS_FEATURE_PROTOCOLS_HAS_ID_FIELD
381
382 /* you can call lws_get_peer_write_allowance */
383 #define LWS_FEATURE_PROTOCOLS_HAS_PEER_WRITE_ALLOWANCE
384
385 /* extra parameter introduced in 917f43ab821 */
386 #define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_LEN
387
388 /* File operations stuff exists */
389 #define LWS_FEATURE_FOPS
390
391
392 #if defined(_WIN32)
393 typedef SOCKET lws_sockfd_type;
394 typedef HANDLE lws_filefd_type;
395 #define lws_sockfd_valid(sfd) (!!sfd)
396 struct lws_pollfd {
397         lws_sockfd_type fd; /**< file descriptor */
398         SHORT events; /**< which events to respond to */
399         SHORT revents; /**< which events happened */
400 };
401 #define LWS_POLLHUP (FD_CLOSE)
402 #define LWS_POLLIN (FD_READ | FD_ACCEPT)
403 #define LWS_POLLOUT (FD_WRITE)
404 #else
405
406
407 #if defined(LWS_WITH_ESP8266)
408
409 #include <user_interface.h>
410 #include <espconn.h>
411
412 typedef struct espconn * lws_sockfd_type;
413 typedef void * lws_filefd_type;
414 #define lws_sockfd_valid(sfd) (!!sfd)
415 struct pollfd {
416         lws_sockfd_type fd; /**< fd related to */
417         short events; /**< which POLL... events to respond to */
418         short revents; /**< which POLL... events occurred */
419 };
420 #define POLLIN          0x0001
421 #define POLLPRI         0x0002
422 #define POLLOUT         0x0004
423 #define POLLERR         0x0008
424 #define POLLHUP         0x0010
425 #define POLLNVAL        0x0020
426
427 struct lws_vhost;
428
429 lws_sockfd_type esp8266_create_tcp_listen_socket(struct lws_vhost *vh);
430 void esp8266_tcp_stream_accept(lws_sockfd_type fd, struct lws *wsi);
431
432 #include <os_type.h>
433 #include <osapi.h>
434 #include "ets_sys.h"
435
436 int ets_snprintf(char *str, size_t size, const char *format, ...) LWS_FORMAT(3);
437 #define snprintf  ets_snprintf
438
439 typedef os_timer_t uv_timer_t;
440 typedef void uv_cb_t(uv_timer_t *);
441
442 void os_timer_disarm(void *);
443 void os_timer_setfn(os_timer_t *, os_timer_func_t *, void *);
444
445 void ets_timer_arm_new(os_timer_t *, int, int, int);
446
447 //void os_timer_arm(os_timer_t *, int, int);
448
449 #define UV_VERSION_MAJOR 1
450
451 #define lws_uv_getloop(a, b) (NULL)
452
453 static inline void uv_timer_init(void *l, uv_timer_t *t)
454 {
455         (void)l;
456         memset(t, 0, sizeof(*t));
457         os_timer_disarm(t);
458 }
459
460 static inline void uv_timer_start(uv_timer_t *t, uv_cb_t *cb, int first, int rep)
461 {
462         os_timer_setfn(t, (os_timer_func_t *)cb, t);
463         /* ms, repeat */
464         os_timer_arm(t, first, !!rep);
465 }
466
467 static inline void uv_timer_stop(uv_timer_t *t)
468 {
469         os_timer_disarm(t);
470 }
471
472 #else
473 #if defined(LWS_WITH_ESP32)
474
475 typedef int lws_sockfd_type;
476 typedef int lws_filefd_type;
477 #define lws_sockfd_valid(sfd) (sfd >= 0)
478 struct pollfd {
479         lws_sockfd_type fd; /**< fd related to */
480         short events; /**< which POLL... events to respond to */
481         short revents; /**< which POLL... events occurred */
482 };
483 #define POLLIN          0x0001
484 #define POLLPRI         0x0002
485 #define POLLOUT         0x0004
486 #define POLLERR         0x0008
487 #define POLLHUP         0x0010
488 #define POLLNVAL        0x0020
489
490 #include <freertos/FreeRTOS.h>
491 #include <freertos/event_groups.h>
492 #include <string.h>
493 #include "esp_wifi.h"
494 #include "esp_system.h"
495 #include "esp_event.h"
496 #include "esp_event_loop.h"
497 #include "nvs.h"
498 #include "driver/gpio.h"
499 #include "esp_spi_flash.h"
500 #include "freertos/timers.h"
501
502 #if !defined(CONFIG_FREERTOS_HZ)
503 #define CONFIG_FREERTOS_HZ 100
504 #endif
505
506 typedef TimerHandle_t uv_timer_t;
507 typedef void uv_cb_t(uv_timer_t *);
508 typedef void * uv_handle_t;
509
510 struct timer_mapping {
511         uv_cb_t *cb;
512         uv_timer_t *t;
513 };
514
515 #define UV_VERSION_MAJOR 1
516
517 #define lws_uv_getloop(a, b) (NULL)
518
519 static inline void uv_timer_init(void *l, uv_timer_t *t)
520 {
521         (void)l;
522         *t = NULL;
523 }
524
525 extern void esp32_uvtimer_cb(TimerHandle_t t);
526
527 static inline void uv_timer_start(uv_timer_t *t, uv_cb_t *cb, int first, int rep)
528 {
529         struct timer_mapping *tm = (struct timer_mapping *)malloc(sizeof(*tm));
530
531         if (!tm)
532                 return;
533
534         tm->t = t;
535         tm->cb = cb;
536
537         *t = xTimerCreate("x", pdMS_TO_TICKS(first), !!rep, tm,
538                           (TimerCallbackFunction_t)esp32_uvtimer_cb);
539         xTimerStart(*t, 0);
540 }
541
542 static inline void uv_timer_stop(uv_timer_t *t)
543 {
544         xTimerStop(*t, 0);
545 }
546
547 static inline void uv_close(uv_handle_t *h, void *v)
548 {
549         free(pvTimerGetTimerID((uv_timer_t)h));
550         xTimerDelete(*(uv_timer_t *)h, 0);
551 }
552
553 /* ESP32 helper declarations */
554
555 #include <mdns.h>
556 #include <esp_partition.h>
557
558 #define LWS_PLUGIN_STATIC
559 #define LWS_MAGIC_REBOOT_TYPE_ADS 0x50001ffc
560 #define LWS_MAGIC_REBOOT_TYPE_REQ_FACTORY 0xb00bcafe
561 #define LWS_MAGIC_REBOOT_TYPE_FORCED_FACTORY 0xfaceb00b
562 #define LWS_MAGIC_REBOOT_TYPE_FORCED_FACTORY_BUTTON 0xf0cedfac
563
564
565 /* user code provides these */
566
567 extern void
568 lws_esp32_identify_physical_device(void);
569
570 /* lws-plat-esp32 provides these */
571
572 typedef void (*lws_cb_scan_done)(uint16_t count, wifi_ap_record_t *recs, void *arg);
573
574 enum genled_state {
575         LWSESP32_GENLED__INIT,
576         LWSESP32_GENLED__LOST_NETWORK,
577         LWSESP32_GENLED__NO_NETWORK,
578         LWSESP32_GENLED__CONN_AP,
579         LWSESP32_GENLED__GOT_IP,
580         LWSESP32_GENLED__OK,
581 };
582
583 struct lws_group_member {
584         struct lws_group_member *next;
585         uint64_t last_seen;
586         char model[16];
587         char role[16];
588         char host[32];
589         char mac[20];
590         int width, height;
591         struct ip4_addr addr;
592         struct ip6_addr addrv6;
593         uint8_t flags;
594 };
595
596 #define LWS_SYSTEM_GROUP_MEMBER_ADD             1
597 #define LWS_SYSTEM_GROUP_MEMBER_CHANGE          2
598 #define LWS_SYSTEM_GROUP_MEMBER_REMOVE          3
599
600 #define LWS_GROUP_FLAG_SELF 1
601
602 struct lws_esp32 {
603         char sta_ip[16];
604         char sta_mask[16];
605         char sta_gw[16];
606         char serial[16];
607         char opts[16];
608         char model[16];
609         char group[16];
610         char role[16];
611         char ssid[4][16];
612         char password[4][32];
613         char active_ssid[32];
614         char access_pw[16];
615         char hostname[32];
616         char mac[20];
617         mdns_server_t *mdns;
618         char region;
619         char inet;
620         char conn_ap;
621
622         enum genled_state genled;
623         uint64_t genled_t;
624
625         lws_cb_scan_done scan_consumer;
626         void *scan_consumer_arg;
627         struct lws_group_member *first;
628         int extant_group_members;
629 };
630
631 struct lws_esp32_image {
632         uint32_t romfs;
633         uint32_t romfs_len;
634         uint32_t json;
635         uint32_t json_len;
636 };
637
638 extern struct lws_esp32 lws_esp32;
639
640 extern esp_err_t
641 lws_esp32_event_passthru(void *ctx, system_event_t *event);
642 extern void
643 lws_esp32_wlan_config(void);
644 extern void
645 lws_esp32_wlan_start_ap(void);
646 extern void
647 lws_esp32_wlan_start_station(void);
648 struct lws_context_creation_info;
649 extern void
650 lws_esp32_set_creation_defaults(struct lws_context_creation_info *info);
651 extern struct lws_context *
652 lws_esp32_init(struct lws_context_creation_info *);
653 extern int
654 lws_esp32_wlan_nvs_get(int retry);
655 extern esp_err_t
656 lws_nvs_set_str(nvs_handle handle, const char* key, const char* value);
657 extern void
658 lws_esp32_restart_guided(uint32_t type);
659 extern const esp_partition_t *
660 lws_esp_ota_get_boot_partition(void);
661 extern int
662 lws_esp32_get_image_info(const esp_partition_t *part, struct lws_esp32_image *i, char *json, int json_len);
663 extern int
664 lws_esp32_leds_network_indication(void);
665
666 extern uint32_t lws_esp32_get_reboot_type(void);
667 extern uint16_t lws_esp32_sine_interp(int n);
668
669 /* required in external code by esp32 plat (may just return if no leds) */
670 extern void lws_esp32_leds_timer_cb(TimerHandle_t th);
671 #else
672 typedef int lws_sockfd_type;
673 typedef int lws_filefd_type;
674 #define lws_sockfd_valid(sfd) (sfd >= 0)
675 #endif
676 #endif
677
678 #define lws_pollfd pollfd
679 #define LWS_POLLHUP (POLLHUP|POLLERR)
680 #define LWS_POLLIN (POLLIN)
681 #define LWS_POLLOUT (POLLOUT)
682 #endif
683
684
685 #if (defined(WIN32) || defined(_WIN32)) && !defined(__MINGW32__)
686 /* ... */
687 #define ssize_t SSIZE_T
688 #endif
689
690 #if defined(WIN32) && defined(LWS_HAVE__STAT32I64)
691 #include <sys/types.h>
692 #include <sys/stat.h>
693 #endif
694
695 #if defined(LWS_HAVE_STDINT_H)
696 #include <stdint.h>
697 #else
698 #if defined(WIN32) || defined(_WIN32)
699 /* !!! >:-[  */
700 typedef unsigned __int32 uint32_t;
701 typedef unsigned __int16 uint16_t;
702 typedef unsigned __int8 uint8_t;
703 #else
704 typedef unsigned int uint32_t;
705 typedef unsigned short uint16_t;
706 typedef unsigned char uint8_t;
707 #endif
708 #endif
709
710 typedef unsigned long long lws_filepos_t;
711 typedef long long lws_fileofs_t;
712 typedef uint32_t lws_fop_flags_t;
713
714 /** struct lws_pollargs - argument structure for all external poll related calls
715  * passed in via 'in' */
716 struct lws_pollargs {
717         lws_sockfd_type fd;     /**< applicable socket descriptor */
718         int events;             /**< the new event mask */
719         int prev_events;        /**< the previous event mask */
720 };
721
722 struct lws_tokens;
723 struct lws_token_limits;
724
725 /*! \defgroup wsclose Websocket Close
726  *
727  * ##Websocket close frame control
728  *
729  * When we close a ws connection, we can send a reason code and a short
730  * UTF-8 description back with the close packet.
731  */
732 ///@{
733
734 /*
735  * NOTE: These public enums are part of the abi.  If you want to add one,
736  * add it at where specified so existing users are unaffected.
737  */
738 /** enum lws_close_status - RFC6455 close status codes */
739 enum lws_close_status {
740         LWS_CLOSE_STATUS_NOSTATUS                               =    0,
741         LWS_CLOSE_STATUS_NORMAL                                 = 1000,
742         /**< 1000 indicates a normal closure, meaning that the purpose for
743       which the connection was established has been fulfilled. */
744         LWS_CLOSE_STATUS_GOINGAWAY                              = 1001,
745         /**< 1001 indicates that an endpoint is "going away", such as a server
746       going down or a browser having navigated away from a page. */
747         LWS_CLOSE_STATUS_PROTOCOL_ERR                           = 1002,
748         /**< 1002 indicates that an endpoint is terminating the connection due
749       to a protocol error. */
750         LWS_CLOSE_STATUS_UNACCEPTABLE_OPCODE                    = 1003,
751         /**< 1003 indicates that an endpoint is terminating the connection
752       because it has received a type of data it cannot accept (e.g., an
753       endpoint that understands only text data MAY send this if it
754       receives a binary message). */
755         LWS_CLOSE_STATUS_RESERVED                               = 1004,
756         /**< Reserved.  The specific meaning might be defined in the future. */
757         LWS_CLOSE_STATUS_NO_STATUS                              = 1005,
758         /**< 1005 is a reserved value and MUST NOT be set as a status code in a
759       Close control frame by an endpoint.  It is designated for use in
760       applications expecting a status code to indicate that no status
761       code was actually present. */
762         LWS_CLOSE_STATUS_ABNORMAL_CLOSE                         = 1006,
763         /**< 1006 is a reserved value and MUST NOT be set as a status code in a
764       Close control frame by an endpoint.  It is designated for use in
765       applications expecting a status code to indicate that the
766       connection was closed abnormally, e.g., without sending or
767       receiving a Close control frame. */
768         LWS_CLOSE_STATUS_INVALID_PAYLOAD                        = 1007,
769         /**< 1007 indicates that an endpoint is terminating the connection
770       because it has received data within a message that was not
771       consistent with the type of the message (e.g., non-UTF-8 [RFC3629]
772       data within a text message). */
773         LWS_CLOSE_STATUS_POLICY_VIOLATION                       = 1008,
774         /**< 1008 indicates that an endpoint is terminating the connection
775       because it has received a message that violates its policy.  This
776       is a generic status code that can be returned when there is no
777       other more suitable status code (e.g., 1003 or 1009) or if there
778       is a need to hide specific details about the policy. */
779         LWS_CLOSE_STATUS_MESSAGE_TOO_LARGE                      = 1009,
780         /**< 1009 indicates that an endpoint is terminating the connection
781       because it has received a message that is too big for it to
782       process. */
783         LWS_CLOSE_STATUS_EXTENSION_REQUIRED                     = 1010,
784         /**< 1010 indicates that an endpoint (client) is terminating the
785       connection because it has expected the server to negotiate one or
786       more extension, but the server didn't return them in the response
787       message of the WebSocket handshake.  The list of extensions that
788       are needed SHOULD appear in the /reason/ part of the Close frame.
789       Note that this status code is not used by the server, because it
790       can fail the WebSocket handshake instead */
791         LWS_CLOSE_STATUS_UNEXPECTED_CONDITION                   = 1011,
792         /**< 1011 indicates that a server is terminating the connection because
793       it encountered an unexpected condition that prevented it from
794       fulfilling the request. */
795         LWS_CLOSE_STATUS_TLS_FAILURE                            = 1015,
796         /**< 1015 is a reserved value and MUST NOT be set as a status code in a
797       Close control frame by an endpoint.  It is designated for use in
798       applications expecting a status code to indicate that the
799       connection was closed due to a failure to perform a TLS handshake
800       (e.g., the server certificate can't be verified). */
801
802         /****** add new things just above ---^ ******/
803
804         LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY               = 9999,
805 };
806
807 /**
808  * lws_close_reason - Set reason and aux data to send with Close packet
809  *              If you are going to return nonzero from the callback
810  *              requesting the connection to close, you can optionally
811  *              call this to set the reason the peer will be told if
812  *              possible.
813  *
814  * \param wsi:  The websocket connection to set the close reason on
815  * \param status:       A valid close status from websocket standard
816  * \param buf:  NULL or buffer containing up to 124 bytes of auxiliary data
817  * \param len:  Length of data in \param buf to send
818  */
819 LWS_VISIBLE LWS_EXTERN void
820 lws_close_reason(struct lws *wsi, enum lws_close_status status,
821                  unsigned char *buf, size_t len);
822
823 ///@}
824
825 struct lws;
826 struct lws_context;
827 /* needed even with extensions disabled for create context */
828 struct lws_extension;
829
830 /*! \defgroup lwsmeta lws-meta
831  *
832  * ##lws-meta protocol
833  *
834  * The protocol wraps other muxed connections inside one tcp connection.
835  *
836  * Commands are assigned from 0x41 up (so they are valid unicode)
837  */
838 ///@{
839
840 enum lws_meta_commands {
841         LWS_META_CMD_OPEN_SUBCHANNEL = 'A',
842         /**< Client requests to open new subchannel
843          */
844         LWS_META_CMD_OPEN_RESULT,
845         /**< Result of client request to open new subchannel */
846         LWS_META_CMD_CLOSE_NOTIFY,
847         /**< Notification of subchannel closure */
848         LWS_META_CMD_CLOSE_RQ,
849         /**< client requests to close a subchannel */
850         LWS_META_CMD_WRITE,
851         /**< connection writes something to specific channel index */
852
853         /****** add new things just above ---^ ******/
854 };
855
856 /* channel numbers are transported offset by 0x20 so they are valid unicode */
857
858 #define LWS_META_TRANSPORT_OFFSET 0x20
859
860 ///@}
861
862 /*! \defgroup usercb User Callback
863  *
864  * ##User protocol callback
865  *
866  * The protocol callback is the primary way lws interacts with
867  * user code.  For one of a list of a few dozen reasons the callback gets
868  * called at some event to be handled.
869  *
870  * All of the events can be ignored, returning 0 is taken as "OK" and returning
871  * nonzero in most cases indicates that the connection should be closed.
872  */
873 ///@{
874
875 struct lws_ssl_info {
876         int where;
877         int ret;
878 };
879
880 /*
881  * NOTE: These public enums are part of the abi.  If you want to add one,
882  * add it at where specified so existing users are unaffected.
883  */
884 /** enum lws_callback_reasons - reason you're getting a protocol callback */
885 enum lws_callback_reasons {
886         LWS_CALLBACK_ESTABLISHED                                =  0,
887         /**< (VH) after the server completes a handshake with an incoming
888          * client.  If you built the library with ssl support, in is a
889          * pointer to the ssl struct associated with the connection or NULL.*/
890         LWS_CALLBACK_CLIENT_CONNECTION_ERROR                    =  1,
891         /**< the request client connection has been unable to complete a
892          * handshake with the remote server.  If in is non-NULL, you can
893          * find an error string of length len where it points to
894          *
895          * Diagnostic strings that may be returned include
896          *
897          *      "getaddrinfo (ipv6) failed"
898          *      "unknown address family"
899          *      "getaddrinfo (ipv4) failed"
900          *      "set socket opts failed"
901          *      "insert wsi failed"
902          *      "lws_ssl_client_connect1 failed"
903          *      "lws_ssl_client_connect2 failed"
904          *      "Peer hung up"
905          *      "read failed"
906          *      "HS: URI missing"
907          *      "HS: Redirect code but no Location"
908          *      "HS: URI did not parse"
909          *      "HS: Redirect failed"
910          *      "HS: Server did not return 200"
911          *      "HS: OOM"
912          *      "HS: disallowed by client filter"
913          *      "HS: disallowed at ESTABLISHED"
914          *      "HS: ACCEPT missing"
915          *      "HS: ws upgrade response not 101"
916          *      "HS: UPGRADE missing"
917          *      "HS: Upgrade to something other than websocket"
918          *      "HS: CONNECTION missing"
919          *      "HS: UPGRADE malformed"
920          *      "HS: PROTOCOL malformed"
921          *      "HS: Cannot match protocol"
922          *      "HS: EXT: list too big"
923          *      "HS: EXT: failed setting defaults"
924          *      "HS: EXT: failed parsing defaults"
925          *      "HS: EXT: failed parsing options"
926          *      "HS: EXT: Rejects server options"
927          *      "HS: EXT: unknown ext"
928          *      "HS: Accept hash wrong"
929          *      "HS: Rejected by filter cb"
930          *      "HS: OOM"
931          *      "HS: SO_SNDBUF failed"
932          *      "HS: Rejected at CLIENT_ESTABLISHED"
933          */
934         LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH                =  2,
935         /**< this is the last chance for the client user code to examine the
936          * http headers and decide to reject the connection.  If the
937          * content in the headers is interesting to the
938          * client (url, etc) it needs to copy it out at
939          * this point since it will be destroyed before
940          * the CLIENT_ESTABLISHED call */
941         LWS_CALLBACK_CLIENT_ESTABLISHED                         =  3,
942         /**< after your client connection completed
943          * a handshake with the remote server */
944         LWS_CALLBACK_CLOSED                                     =  4,
945         /**< when the websocket session ends */
946         LWS_CALLBACK_CLOSED_HTTP                                =  5,
947         /**< when a HTTP (non-websocket) session ends */
948         LWS_CALLBACK_RECEIVE                                    =  6,
949         /**< data has appeared for this server endpoint from a
950          * remote client, it can be found at *in and is
951          * len bytes long */
952         LWS_CALLBACK_RECEIVE_PONG                               =  7,
953         /**< servers receive PONG packets with this callback reason */
954         LWS_CALLBACK_CLIENT_RECEIVE                             =  8,
955         /**< data has appeared from the server for the client connection, it
956          * can be found at *in and is len bytes long */
957         LWS_CALLBACK_CLIENT_RECEIVE_PONG                        =  9,
958         /**< clients receive PONG packets with this callback reason */
959         LWS_CALLBACK_CLIENT_WRITEABLE                           = 10,
960         /**<  If you call lws_callback_on_writable() on a connection, you will
961          * get one of these callbacks coming when the connection socket
962          * is able to accept another write packet without blocking.
963          * If it already was able to take another packet without blocking,
964          * you'll get this callback at the next call to the service loop
965          * function.  Notice that CLIENTs get LWS_CALLBACK_CLIENT_WRITEABLE
966          * and servers get LWS_CALLBACK_SERVER_WRITEABLE. */
967         LWS_CALLBACK_SERVER_WRITEABLE                           = 11,
968         /**< See LWS_CALLBACK_CLIENT_WRITEABLE */
969         LWS_CALLBACK_HTTP                                       = 12,
970         /**< an http request has come from a client that is not
971          * asking to upgrade the connection to a websocket
972          * one.  This is a chance to serve http content,
973          * for example, to send a script to the client
974          * which will then open the websockets connection.
975          * in points to the URI path requested and
976          * lws_serve_http_file() makes it very
977          * simple to send back a file to the client.
978          * Normally after sending the file you are done
979          * with the http connection, since the rest of the
980          * activity will come by websockets from the script
981          * that was delivered by http, so you will want to
982          * return 1; to close and free up the connection. */
983         LWS_CALLBACK_HTTP_BODY                                  = 13,
984         /**< the next len bytes data from the http
985          * request body HTTP connection is now available in in. */
986         LWS_CALLBACK_HTTP_BODY_COMPLETION                       = 14,
987         /**< the expected amount of http request body has been delivered */
988         LWS_CALLBACK_HTTP_FILE_COMPLETION                       = 15,
989         /**< a file requested to be sent down http link has completed. */
990         LWS_CALLBACK_HTTP_WRITEABLE                             = 16,
991         /**< you can write more down the http protocol link now. */
992         LWS_CALLBACK_FILTER_NETWORK_CONNECTION                  = 17,
993         /**< called when a client connects to
994          * the server at network level; the connection is accepted but then
995          * passed to this callback to decide whether to hang up immediately
996          * or not, based on the client IP.  in contains the connection
997          * socket's descriptor. Since the client connection information is
998          * not available yet, wsi still pointing to the main server socket.
999          * Return non-zero to terminate the connection before sending or
1000          * receiving anything. Because this happens immediately after the
1001          * network connection from the client, there's no websocket protocol
1002          * selected yet so this callback is issued only to protocol 0. */
1003         LWS_CALLBACK_FILTER_HTTP_CONNECTION                     = 18,
1004         /**< called when the request has
1005          * been received and parsed from the client, but the response is
1006          * not sent yet.  Return non-zero to disallow the connection.
1007          * user is a pointer to the connection user space allocation,
1008          * in is the URI, eg, "/"
1009          * In your handler you can use the public APIs
1010          * lws_hdr_total_length() / lws_hdr_copy() to access all of the
1011          * headers using the header enums lws_token_indexes from
1012          * libwebsockets.h to check for and read the supported header
1013          * presence and content before deciding to allow the http
1014          * connection to proceed or to kill the connection. */
1015         LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED             = 19,
1016         /**< A new client just had
1017          * been connected, accepted, and instantiated into the pool. This
1018          * callback allows setting any relevant property to it. Because this
1019          * happens immediately after the instantiation of a new client,
1020          * there's no websocket protocol selected yet so this callback is
1021          * issued only to protocol 0. Only wsi is defined, pointing to the
1022          * new client, and the return value is ignored. */
1023         LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION                 = 20,
1024         /**< called when the handshake has
1025          * been received and parsed from the client, but the response is
1026          * not sent yet.  Return non-zero to disallow the connection.
1027          * user is a pointer to the connection user space allocation,
1028          * in is the requested protocol name
1029          * In your handler you can use the public APIs
1030          * lws_hdr_total_length() / lws_hdr_copy() to access all of the
1031          * headers using the header enums lws_token_indexes from
1032          * libwebsockets.h to check for and read the supported header
1033          * presence and content before deciding to allow the handshake
1034          * to proceed or to kill the connection. */
1035         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS     = 21,
1036         /**< if configured for
1037          * including OpenSSL support, this callback allows your user code
1038          * to perform extra SSL_CTX_load_verify_locations() or similar
1039          * calls to direct OpenSSL where to find certificates the client
1040          * can use to confirm the remote server identity.  user is the
1041          * OpenSSL SSL_CTX* */
1042         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS     = 22,
1043         /**< if configured for
1044          * including OpenSSL support, this callback allows your user code
1045          * to load extra certifcates into the server which allow it to
1046          * verify the validity of certificates returned by clients.  user
1047          * is the server's OpenSSL SSL_CTX* */
1048         LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION   = 23,
1049         /**< if the libwebsockets vhost was created with the option
1050          * LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT, then this
1051          * callback is generated during OpenSSL verification of the cert
1052          * sent from the client.  It is sent to protocol[0] callback as
1053          * no protocol has been negotiated on the connection yet.
1054          * Notice that the libwebsockets context and wsi are both NULL
1055          * during this callback.  See
1056          *  http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html
1057          * to understand more detail about the OpenSSL callback that
1058          * generates this libwebsockets callback and the meanings of the
1059          * arguments passed.  In this callback, user is the x509_ctx,
1060          * in is the ssl pointer and len is preverify_ok
1061          * Notice that this callback maintains libwebsocket return
1062          * conventions, return 0 to mean the cert is OK or 1 to fail it.
1063          * This also means that if you don't handle this callback then
1064          * the default callback action of returning 0 allows the client
1065          * certificates. */
1066         LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER             = 24,
1067         /**< this callback happens
1068          * when a client handshake is being compiled.  user is NULL,
1069          * in is a char **, it's pointing to a char * which holds the
1070          * next location in the header buffer where you can add
1071          * headers, and len is the remaining space in the header buffer,
1072          * which is typically some hundreds of bytes.  So, to add a canned
1073          * cookie, your handler code might look similar to:
1074          *
1075          *      char **p = (char **)in;
1076          *
1077          *      if (len < 100)
1078          *              return 1;
1079          *
1080          *      *p += sprintf(*p, "Cookie: a=b\x0d\x0a");
1081          *
1082          *      return 0;
1083          *
1084          * Notice if you add anything, you just have to take care about
1085          * the CRLF on the line you added.  Obviously this callback is
1086          * optional, if you don't handle it everything is fine.
1087          *
1088          * Notice the callback is coming to protocols[0] all the time,
1089          * because there is no specific protocol negotiated yet. */
1090         LWS_CALLBACK_CONFIRM_EXTENSION_OKAY                     = 25,
1091         /**< When the server handshake code
1092          * sees that it does support a requested extension, before
1093          * accepting the extension by additing to the list sent back to
1094          * the client it gives this callback just to check that it's okay
1095          * to use that extension.  It calls back to the requested protocol
1096          * and with in being the extension name, len is 0 and user is
1097          * valid.  Note though at this time the ESTABLISHED callback hasn't
1098          * happened yet so if you initialize user content there, user
1099          * content during this callback might not be useful for anything. */
1100         LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED         = 26,
1101         /**< When a client
1102          * connection is being prepared to start a handshake to a server,
1103          * each supported extension is checked with protocols[0] callback
1104          * with this reason, giving the user code a chance to suppress the
1105          * claim to support that extension by returning non-zero.  If
1106          * unhandled, by default 0 will be returned and the extension
1107          * support included in the header to the server.  Notice this
1108          * callback comes to protocols[0]. */
1109         LWS_CALLBACK_PROTOCOL_INIT                              = 27,
1110         /**< One-time call per protocol, per-vhost using it, so it can
1111          * do initial setup / allocations etc */
1112         LWS_CALLBACK_PROTOCOL_DESTROY                           = 28,
1113         /**< One-time call per protocol, per-vhost using it, indicating
1114          * this protocol won't get used at all after this callback, the
1115          * vhost is getting destroyed.  Take the opportunity to
1116          * deallocate everything that was allocated by the protocol. */
1117         LWS_CALLBACK_WSI_CREATE                                 = 29,
1118         /**< outermost (earliest) wsi create notification to protocols[0] */
1119         LWS_CALLBACK_WSI_DESTROY                                = 30,
1120         /**< outermost (latest) wsi destroy notification to protocols[0] */
1121         LWS_CALLBACK_GET_THREAD_ID                              = 31,
1122         /**< lws can accept callback when writable requests from other
1123          * threads, if you implement this callback and return an opaque
1124          * current thread ID integer. */
1125
1126         /* external poll() management support */
1127         LWS_CALLBACK_ADD_POLL_FD                                = 32,
1128         /**< lws normally deals with its poll() or other event loop
1129          * internally, but in the case you are integrating with another
1130          * server you will need to have lws sockets share a
1131          * polling array with the other server.  This and the other
1132          * POLL_FD related callbacks let you put your specialized
1133          * poll array interface code in the callback for protocol 0, the
1134          * first protocol you support, usually the HTTP protocol in the
1135          * serving case.
1136          * This callback happens when a socket needs to be
1137          * added to the polling loop: in points to a struct
1138          * lws_pollargs; the fd member of the struct is the file
1139          * descriptor, and events contains the active events
1140          *
1141          * If you are using the internal lws polling / event loop
1142          * you can just ignore these callbacks. */
1143         LWS_CALLBACK_DEL_POLL_FD                                = 33,
1144         /**< This callback happens when a socket descriptor
1145          * needs to be removed from an external polling array.  in is
1146          * again the struct lws_pollargs containing the fd member
1147          * to be removed.  If you are using the internal polling
1148          * loop, you can just ignore it. */
1149         LWS_CALLBACK_CHANGE_MODE_POLL_FD                        = 34,
1150         /**< This callback happens when lws wants to modify the events for
1151          * a connection.
1152          * in is the struct lws_pollargs with the fd to change.
1153          * The new event mask is in events member and the old mask is in
1154          * the prev_events member.
1155          * If you are using the internal polling loop, you can just ignore
1156          * it. */
1157         LWS_CALLBACK_LOCK_POLL                                  = 35,
1158         /**< These allow the external poll changes driven
1159          * by lws to participate in an external thread locking
1160          * scheme around the changes, so the whole thing is threadsafe.
1161          * These are called around three activities in the library,
1162          *      - inserting a new wsi in the wsi / fd table (len=1)
1163          *      - deleting a wsi from the wsi / fd table (len=1)
1164          *      - changing a wsi's POLLIN/OUT state (len=0)
1165          * Locking and unlocking external synchronization objects when
1166          * len == 1 allows external threads to be synchronized against
1167          * wsi lifecycle changes if it acquires the same lock for the
1168          * duration of wsi dereference from the other thread context. */
1169         LWS_CALLBACK_UNLOCK_POLL                                = 36,
1170         /**< See LWS_CALLBACK_LOCK_POLL, ignore if using lws internal poll */
1171
1172         LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY       = 37,
1173         /**< if configured for including OpenSSL support but no private key
1174          * file has been specified (ssl_private_key_filepath is NULL), this is
1175          * called to allow the user to set the private key directly via
1176          * libopenssl and perform further operations if required; this might be
1177          * useful in situations where the private key is not directly accessible
1178          * by the OS, for example if it is stored on a smartcard.
1179          * user is the server's OpenSSL SSL_CTX* */
1180         LWS_CALLBACK_WS_PEER_INITIATED_CLOSE                    = 38,
1181         /**< The peer has sent an unsolicited Close WS packet.  in and
1182          * len are the optional close code (first 2 bytes, network
1183          * order) and the optional additional information which is not
1184          * defined in the standard, and may be a string or non-human- readable data.
1185          * If you return 0 lws will echo the close and then close the
1186          * connection.  If you return nonzero lws will just close the
1187          * connection. */
1188
1189         LWS_CALLBACK_WS_EXT_DEFAULTS                            = 39,
1190         /**<  */
1191
1192         LWS_CALLBACK_CGI                                        = 40,
1193         /**<  */
1194         LWS_CALLBACK_CGI_TERMINATED                             = 41,
1195         /**<  */
1196         LWS_CALLBACK_CGI_STDIN_DATA                             = 42,
1197         /**<  */
1198         LWS_CALLBACK_CGI_STDIN_COMPLETED                        = 43,
1199         /**<  */
1200         LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP                    = 44,
1201         /**<  */
1202         LWS_CALLBACK_CLOSED_CLIENT_HTTP                         = 45,
1203         /**<  */
1204         LWS_CALLBACK_RECEIVE_CLIENT_HTTP                        = 46,
1205         /**<  */
1206         LWS_CALLBACK_COMPLETED_CLIENT_HTTP                      = 47,
1207         /**<  */
1208         LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ                   = 48,
1209         /**<  */
1210         LWS_CALLBACK_HTTP_BIND_PROTOCOL                         = 49,
1211         /**<  */
1212         LWS_CALLBACK_HTTP_DROP_PROTOCOL                         = 50,
1213         /**<  */
1214         LWS_CALLBACK_CHECK_ACCESS_RIGHTS                        = 51,
1215         /**<  */
1216         LWS_CALLBACK_PROCESS_HTML                               = 52,
1217         /**<  */
1218         LWS_CALLBACK_ADD_HEADERS                                = 53,
1219         /**<  */
1220         LWS_CALLBACK_SESSION_INFO                               = 54,
1221         /**<  */
1222
1223         LWS_CALLBACK_GS_EVENT                                   = 55,
1224         /**<  */
1225         LWS_CALLBACK_HTTP_PMO                                   = 56,
1226         /**< per-mount options for this connection, called before
1227          * the normal LWS_CALLBACK_HTTP when the mount has per-mount
1228          * options
1229          */
1230         LWS_CALLBACK_CLIENT_HTTP_WRITEABLE                      = 57,
1231         /**< when doing an HTTP type client connection, you can call
1232          * lws_client_http_body_pending(wsi, 1) from
1233          * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER to get these callbacks
1234          * sending the HTTP headers.
1235          *
1236          * From this callback, when you have sent everything, you should let
1237          * lws know by calling lws_client_http_body_pending(wsi, 0)
1238          */
1239         LWS_CALLBACK_OPENSSL_PERFORM_SERVER_CERT_VERIFICATION = 58,
1240         /**< Similar to LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION
1241          * this callback is called during OpenSSL verification of the cert
1242          * sent from the server to the client. It is sent to protocol[0]
1243          * callback as no protocol has been negotiated on the connection yet.
1244          * Notice that the wsi is set because lws_client_connect_via_info was
1245          * successful.
1246          *
1247          * See http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html
1248          * to understand more detail about the OpenSSL callback that
1249          * generates this libwebsockets callback and the meanings of the
1250          * arguments passed. In this callback, user is the x509_ctx,
1251          * in is the ssl pointer and len is preverify_ok.
1252          *
1253          * THIS IS NOT RECOMMENDED BUT if a cert validation error shall be
1254          * overruled and cert shall be accepted as ok,
1255          * X509_STORE_CTX_set_error((X509_STORE_CTX*)user, X509_V_OK); must be
1256          * called and return value must be 0 to mean the cert is OK;
1257          * returning 1 will fail the cert in any case.
1258          *
1259          * This also means that if you don't handle this callback then
1260          * the default callback action of returning 0 will not accept the
1261          * certificate in case of a validation error decided by the SSL lib.
1262          *
1263          * This is expected and secure behaviour when validating certificates.
1264          *
1265          * Note: LCCSCF_ALLOW_SELFSIGNED and
1266          * LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK still work without this
1267          * callback being implemented.
1268          */
1269         LWS_CALLBACK_RAW_RX                                     = 59,
1270         /**< RAW mode connection RX */
1271         LWS_CALLBACK_RAW_CLOSE                                  = 60,
1272         /**< RAW mode connection is closing */
1273         LWS_CALLBACK_RAW_WRITEABLE                              = 61,
1274         /**< RAW mode connection may be written */
1275         LWS_CALLBACK_RAW_ADOPT                                  = 62,
1276         /**< RAW mode connection was adopted (equivalent to 'wsi created') */
1277         LWS_CALLBACK_RAW_ADOPT_FILE                             = 63,
1278         /**< RAW mode file was adopted (equivalent to 'wsi created') */
1279         LWS_CALLBACK_RAW_RX_FILE                                = 64,
1280         /**< RAW mode file has something to read */
1281         LWS_CALLBACK_RAW_WRITEABLE_FILE                         = 65,
1282         /**< RAW mode file is writeable */
1283         LWS_CALLBACK_RAW_CLOSE_FILE                             = 66,
1284         /**< RAW mode wsi that adopted a file is closing */
1285         LWS_CALLBACK_SSL_INFO                                   = 67,
1286         /**< SSL connections only.  An event you registered an
1287          * interest in at the vhost has occurred on a connection
1288          * using the vhost.  @in is a pointer to a
1289          * struct lws_ssl_info containing information about the
1290          * event*/
1291         LWS_CALLBACK_CHILD_WRITE_VIA_PARENT                     = 68,
1292         /**< Child has been marked with parent_carries_io attribute, so
1293          * lws_write directs the to this callback at the parent,
1294          * @in is a struct lws_write_passthru containing the args
1295          * the lws_write() was called with.
1296          */
1297         LWS_CALLBACK_CHILD_CLOSING                              = 69,
1298         /**< Sent to parent to notify them a child is closing / being
1299          * destroyed.  @in is the child wsi.
1300          */
1301
1302         /****** add new things just above ---^ ******/
1303
1304         LWS_CALLBACK_USER = 1000,
1305         /**<  user code can use any including above without fear of clashes */
1306 };
1307
1308
1309
1310 /**
1311  * typedef lws_callback_function() - User server actions
1312  * \param wsi:  Opaque websocket instance pointer
1313  * \param reason:       The reason for the call
1314  * \param user: Pointer to per-session user data allocated by library
1315  * \param in:           Pointer used for some callback reasons
1316  * \param len:  Length set for some callback reasons
1317  *
1318  *      This callback is the way the user controls what is served.  All the
1319  *      protocol detail is hidden and handled by the library.
1320  *
1321  *      For each connection / session there is user data allocated that is
1322  *      pointed to by "user".  You set the size of this user data area when
1323  *      the library is initialized with lws_create_server.
1324  */
1325 typedef int
1326 lws_callback_function(struct lws *wsi, enum lws_callback_reasons reason,
1327                     void *user, void *in, size_t len);
1328 ///@}
1329
1330 /*! \defgroup extensions
1331  *
1332  * ##Extension releated functions
1333  *
1334  *  Ws defines optional extensions, lws provides the ability to implement these
1335  *  in user code if so desired.
1336  *
1337  *  We provide one extensions permessage-deflate.
1338  */
1339 ///@{
1340
1341 /*
1342  * NOTE: These public enums are part of the abi.  If you want to add one,
1343  * add it at where specified so existing users are unaffected.
1344  */
1345 enum lws_extension_callback_reasons {
1346         LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT             =  0,
1347         LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT             =  1,
1348         LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT              =  2,
1349         LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT              =  3,
1350         LWS_EXT_CB_CONSTRUCT                            =  4,
1351         LWS_EXT_CB_CLIENT_CONSTRUCT                     =  5,
1352         LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE             =  6,
1353         LWS_EXT_CB_CHECK_OK_TO_PROPOSE_EXTENSION        =  7,
1354         LWS_EXT_CB_DESTROY                              =  8,
1355         LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING              =  9,
1356         LWS_EXT_CB_ANY_WSI_ESTABLISHED                  = 10,
1357         LWS_EXT_CB_PACKET_RX_PREPARSE                   = 11,
1358         LWS_EXT_CB_PACKET_TX_PRESEND                    = 12,
1359         LWS_EXT_CB_PACKET_TX_DO_SEND                    = 13,
1360         LWS_EXT_CB_HANDSHAKE_REPLY_TX                   = 14,
1361         LWS_EXT_CB_FLUSH_PENDING_TX                     = 15,
1362         LWS_EXT_CB_EXTENDED_PAYLOAD_RX                  = 16,
1363         LWS_EXT_CB_CAN_PROXY_CLIENT_CONNECTION          = 17,
1364         LWS_EXT_CB_1HZ                                  = 18,
1365         LWS_EXT_CB_REQUEST_ON_WRITEABLE                 = 19,
1366         LWS_EXT_CB_IS_WRITEABLE                         = 20,
1367         LWS_EXT_CB_PAYLOAD_TX                           = 21,
1368         LWS_EXT_CB_PAYLOAD_RX                           = 22,
1369         LWS_EXT_CB_OPTION_DEFAULT                       = 23,
1370         LWS_EXT_CB_OPTION_SET                           = 24,
1371         LWS_EXT_CB_OPTION_CONFIRM                       = 25,
1372         LWS_EXT_CB_NAMED_OPTION_SET                     = 26,
1373
1374         /****** add new things just above ---^ ******/
1375 };
1376
1377 /** enum lws_ext_options_types */
1378 enum lws_ext_options_types {
1379         EXTARG_NONE, /**< does not take an argument */
1380         EXTARG_DEC,  /**< requires a decimal argument */
1381         EXTARG_OPT_DEC /**< may have an optional decimal argument */
1382
1383         /* Add new things just above here ---^
1384          * This is part of the ABI, don't needlessly break compatibility */
1385 };
1386
1387 /** struct lws_ext_options -    Option arguments to the extension.  These are
1388  *                              used in the negotiation at ws upgrade time.
1389  *                              The helper function lws_ext_parse_options()
1390  *                              uses these to generate callbacks */
1391 struct lws_ext_options {
1392         const char *name; /**< Option name, eg, "server_no_context_takeover" */
1393         enum lws_ext_options_types type; /**< What kind of args the option can take */
1394
1395         /* Add new things just above here ---^
1396          * This is part of the ABI, don't needlessly break compatibility */
1397 };
1398
1399 /** struct lws_ext_option_arg */
1400 struct lws_ext_option_arg {
1401         const char *option_name; /**< may be NULL, option_index used then */
1402         int option_index; /**< argument ordinal to use if option_name missing */
1403         const char *start; /**< value */
1404         int len; /**< length of value */
1405 };
1406
1407 /**
1408  * typedef lws_extension_callback_function() - Hooks to allow extensions to operate
1409  * \param context:      Websockets context
1410  * \param ext:  This extension
1411  * \param wsi:  Opaque websocket instance pointer
1412  * \param reason:       The reason for the call
1413  * \param user: Pointer to ptr to per-session user data allocated by library
1414  * \param in:           Pointer used for some callback reasons
1415  * \param len:  Length set for some callback reasons
1416  *
1417  *      Each extension that is active on a particular connection receives
1418  *      callbacks during the connection lifetime to allow the extension to
1419  *      operate on websocket data and manage itself.
1420  *
1421  *      Libwebsockets takes care of allocating and freeing "user" memory for
1422  *      each active extension on each connection.  That is what is pointed to
1423  *      by the user parameter.
1424  *
1425  *      LWS_EXT_CB_CONSTRUCT:  called when the server has decided to
1426  *              select this extension from the list provided by the client,
1427  *              just before the server will send back the handshake accepting
1428  *              the connection with this extension active.  This gives the
1429  *              extension a chance to initialize its connection context found
1430  *              in user.
1431  *
1432  *      LWS_EXT_CB_CLIENT_CONSTRUCT: same as LWS_EXT_CB_CONSTRUCT
1433  *              but called when client is instantiating this extension.  Some
1434  *              extensions will work the same on client and server side and then
1435  *              you can just merge handlers for both CONSTRUCTS.
1436  *
1437  *      LWS_EXT_CB_DESTROY:  called when the connection the extension was
1438  *              being used on is about to be closed and deallocated.  It's the
1439  *              last chance for the extension to deallocate anything it has
1440  *              allocated in the user data (pointed to by user) before the
1441  *              user data is deleted.  This same callback is used whether you
1442  *              are in client or server instantiation context.
1443  *
1444  *      LWS_EXT_CB_PACKET_RX_PREPARSE: when this extension was active on
1445  *              a connection, and a packet of data arrived at the connection,
1446  *              it is passed to this callback to give the extension a chance to
1447  *              change the data, eg, decompress it.  user is pointing to the
1448  *              extension's private connection context data, in is pointing
1449  *              to an lws_tokens struct, it consists of a char * pointer called
1450  *              token, and an int called token_len.  At entry, these are
1451  *              set to point to the received buffer and set to the content
1452  *              length.  If the extension will grow the content, it should use
1453  *              a new buffer allocated in its private user context data and
1454  *              set the pointed-to lws_tokens members to point to its buffer.
1455  *
1456  *      LWS_EXT_CB_PACKET_TX_PRESEND: this works the same way as
1457  *              LWS_EXT_CB_PACKET_RX_PREPARSE above, except it gives the
1458  *              extension a chance to change websocket data just before it will
1459  *              be sent out.  Using the same lws_token pointer scheme in in,
1460  *              the extension can change the buffer and the length to be
1461  *              transmitted how it likes.  Again if it wants to grow the
1462  *              buffer safely, it should copy the data into its own buffer and
1463  *              set the lws_tokens token pointer to it.
1464  *
1465  *      LWS_EXT_CB_ARGS_VALIDATE:
1466  */
1467 typedef int
1468 lws_extension_callback_function(struct lws_context *context,
1469                               const struct lws_extension *ext, struct lws *wsi,
1470                               enum lws_extension_callback_reasons reason,
1471                               void *user, void *in, size_t len);
1472
1473 /** struct lws_extension -      An extension we support */
1474 struct lws_extension {
1475         const char *name; /**< Formal extension name, eg, "permessage-deflate" */
1476         lws_extension_callback_function *callback; /**< Service callback */
1477         const char *client_offer; /**< String containing exts and options client offers */
1478
1479         /* Add new things just above here ---^
1480          * This is part of the ABI, don't needlessly break compatibility */
1481 };
1482
1483 /**
1484  * lws_set_extension_option(): set extension option if possible
1485  *
1486  * \param wsi:  websocket connection
1487  * \param ext_name:     name of ext, like "permessage-deflate"
1488  * \param opt_name:     name of option, like "rx_buf_size"
1489  * \param opt_val:      value to set option to
1490  */
1491 LWS_VISIBLE LWS_EXTERN int
1492 lws_set_extension_option(struct lws *wsi, const char *ext_name,
1493                          const char *opt_name, const char *opt_val);
1494
1495 #ifndef LWS_NO_EXTENSIONS
1496 /* lws_get_internal_extensions() - DEPRECATED
1497  *
1498  * \Deprecated There is no longer a set internal extensions table.  The table is provided
1499  * by user code along with application-specific settings.  See the test
1500  * client and server for how to do.
1501  */
1502 static LWS_INLINE LWS_WARN_DEPRECATED const struct lws_extension *
1503 lws_get_internal_extensions(void) { return NULL; }
1504
1505 /**
1506  * lws_ext_parse_options() - deal with parsing negotiated extension options
1507  *
1508  * \param ext: related extension struct
1509  * \param wsi:  websocket connection
1510  * \param ext_user: per-connection extension private data
1511  * \param opts: list of supported options
1512  * \param o: option string to parse
1513  * \param len: length
1514  */
1515 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
1516 lws_ext_parse_options(const struct lws_extension *ext, struct lws *wsi,
1517                        void *ext_user, const struct lws_ext_options *opts,
1518                        const char *o, int len);
1519 #endif
1520
1521 /** lws_extension_callback_pm_deflate() - extension for RFC7692
1522  *
1523  * \param context:      lws context
1524  * \param ext:  related lws_extension struct
1525  * \param wsi:  websocket connection
1526  * \param reason:       incoming callback reason
1527  * \param user: per-connection extension private data
1528  * \param in:   pointer parameter
1529  * \param len:  length parameter
1530  *
1531  * Built-in callback implementing RFC7692 permessage-deflate
1532  */
1533 LWS_EXTERN
1534 int lws_extension_callback_pm_deflate(
1535         struct lws_context *context, const struct lws_extension *ext,
1536         struct lws *wsi, enum lws_extension_callback_reasons reason,
1537         void *user, void *in, size_t len);
1538
1539 /*
1540  * The internal exts are part of the public abi
1541  * If we add more extensions, publish the callback here  ------v
1542  */
1543 ///@}
1544
1545 /*! \defgroup Protocols-and-Plugins Protocols and Plugins
1546  * \ingroup lwsapi
1547  *
1548  * ##Protocol and protocol plugin -related apis
1549  *
1550  * Protocols bind ws protocol names to a custom callback specific to that
1551  * protocol implementaion.
1552  *
1553  * A list of protocols can be passed in at context creation time, but it is
1554  * also legal to leave that NULL and add the protocols and their callback code
1555  * using plugins.
1556  *
1557  * Plugins are much preferable compared to cut and pasting code into an
1558  * application each time, since they can be used standalone.
1559  */
1560 ///@{
1561 /** struct lws_protocols -      List of protocols and handlers client or server
1562  *                                      supports. */
1563
1564 struct lws_protocols {
1565         const char *name;
1566         /**< Protocol name that must match the one given in the client
1567          * Javascript new WebSocket(url, 'protocol') name. */
1568         lws_callback_function *callback;
1569         /**< The service callback used for this protocol.  It allows the
1570          * service action for an entire protocol to be encapsulated in
1571          * the protocol-specific callback */
1572         size_t per_session_data_size;
1573         /**< Each new connection using this protocol gets
1574          * this much memory allocated on connection establishment and
1575          * freed on connection takedown.  A pointer to this per-connection
1576          * allocation is passed into the callback in the 'user' parameter */
1577         size_t rx_buffer_size;
1578         /**< lws allocates this much space for rx data and informs callback
1579          * when something came.  Due to rx flow control, the callback may not
1580          * be able to consume it all without having to return to the event
1581          * loop.  That is supported in lws.
1582          *
1583          * If .tx_packet_size is 0, this also controls how much may be sent at once
1584          * for backwards compatibility.
1585          */
1586         unsigned int id;
1587         /**< ignored by lws, but useful to contain user information bound
1588          * to the selected protocol.  For example if this protocol was
1589          * called "myprotocol-v2", you might set id to 2, and the user
1590          * code that acts differently according to the version can do so by
1591          * switch (wsi->protocol->id), user code might use some bits as
1592          * capability flags based on selected protocol version, etc. */
1593         void *user; /**< ignored by lws, but user code can pass a pointer
1594                         here it can later access from the protocol callback */
1595         size_t tx_packet_size;
1596         /**< 0 indicates restrict send() size to .rx_buffer_size for backwards-
1597          * compatibility.
1598          * If greater than zero, a single send() is restricted to this amount
1599          * and any remainder is buffered by lws and sent afterwards also in
1600          * these size chunks.  Since that is expensive, it's preferable
1601          * to restrict one fragment you are trying to send to match this
1602          * size.
1603          */
1604
1605         /* Add new things just above here ---^
1606          * This is part of the ABI, don't needlessly break compatibility */
1607 };
1608
1609 struct lws_vhost;
1610
1611 /**
1612  * lws_vhost_name_to_protocol() - get vhost's protocol object from its name
1613  *
1614  * \param vh: vhost to search
1615  * \param name: protocol name
1616  *
1617  * Returns NULL or a pointer to the vhost's protocol of the requested name
1618  */
1619 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1620 lws_vhost_name_to_protocol(struct lws_vhost *vh, const char *name);
1621
1622 /**
1623  * lws_get_protocol() - Returns a protocol pointer from a websocket
1624  *                                connection.
1625  * \param wsi:  pointer to struct websocket you want to know the protocol of
1626  *
1627  *
1628  *      Some apis can act on all live connections of a given protocol,
1629  *      this is how you can get a pointer to the active protocol if needed.
1630  */
1631 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1632 lws_get_protocol(struct lws *wsi);
1633
1634 /** lws_protocol_get() -  deprecated: use lws_get_protocol */
1635 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1636 lws_protocol_get(struct lws *wsi) LWS_WARN_DEPRECATED;
1637
1638 /**
1639  * lws_protocol_vh_priv_zalloc() - Allocate and zero down a protocol's per-vhost
1640  *                                 storage
1641  * \param vhost:        vhost the instance is related to
1642  * \param prot:         protocol the instance is related to
1643  * \param size:         bytes to allocate
1644  *
1645  * Protocols often find it useful to allocate a per-vhost struct, this is a
1646  * helper to be called in the per-vhost init LWS_CALLBACK_PROTOCOL_INIT
1647  */
1648 LWS_VISIBLE LWS_EXTERN void *
1649 lws_protocol_vh_priv_zalloc(struct lws_vhost *vhost, const struct lws_protocols *prot,
1650                             int size);
1651
1652 /**
1653  * lws_protocol_vh_priv_get() - retreive a protocol's per-vhost storage
1654  *
1655  * \param vhost:        vhost the instance is related to
1656  * \param prot:         protocol the instance is related to
1657  *
1658  * Recover a pointer to the allocated per-vhost storage for the protocol created
1659  * by lws_protocol_vh_priv_zalloc() earlier
1660  */
1661 LWS_VISIBLE LWS_EXTERN void *
1662 lws_protocol_vh_priv_get(struct lws_vhost *vhost, const struct lws_protocols *prot);
1663
1664 /**
1665  * lws_finalize_startup() - drop initial process privileges
1666  *
1667  * \param context:      lws context
1668  *
1669  * This is called after the end of the vhost protocol initializations, but
1670  * you may choose to call it earlier
1671  */
1672 LWS_VISIBLE LWS_EXTERN int
1673 lws_finalize_startup(struct lws_context *context);
1674
1675 LWS_VISIBLE LWS_EXTERN int
1676 lws_protocol_init(struct lws_context *context);
1677
1678 #ifdef LWS_WITH_PLUGINS
1679
1680 /* PLUGINS implies LIBUV */
1681
1682 #define LWS_PLUGIN_API_MAGIC 180
1683
1684 /** struct lws_plugin_capability - how a plugin introduces itself to lws */
1685 struct lws_plugin_capability {
1686         unsigned int api_magic; /**< caller fills this in, plugin fills rest */
1687         const struct lws_protocols *protocols; /**< array of supported protocols provided by plugin */
1688         int count_protocols; /**< how many protocols */
1689         const struct lws_extension *extensions; /**< array of extensions provided by plugin */
1690         int count_extensions; /**< how many extensions */
1691 };
1692
1693 typedef int (*lws_plugin_init_func)(struct lws_context *,
1694                                     struct lws_plugin_capability *);
1695 typedef int (*lws_plugin_destroy_func)(struct lws_context *);
1696
1697 /** struct lws_plugin */
1698 struct lws_plugin {
1699         struct lws_plugin *list; /**< linked list */
1700 #if (UV_VERSION_MAJOR > 0)
1701         uv_lib_t lib; /**< shared library pointer */
1702 #else
1703         void *l; /**< so we can compile on ancient libuv */
1704 #endif
1705         char name[64]; /**< name of the plugin */
1706         struct lws_plugin_capability caps; /**< plugin capabilities */
1707 };
1708
1709 #endif
1710
1711 ///@}
1712
1713
1714 /*! \defgroup generic-sessions plugin: generic-sessions
1715  * \ingroup Protocols-and-Plugins
1716  *
1717  * ##Plugin Generic-sessions related
1718  *
1719  * generic-sessions plugin provides a reusable, generic session and login /
1720  * register / forgot password framework including email verification.
1721  */
1722 ///@{
1723
1724 #define LWSGS_EMAIL_CONTENT_SIZE 16384
1725 /**< Maximum size of email we might send */
1726
1727 /* SHA-1 binary and hexified versions */
1728 /** typedef struct lwsgw_hash_bin */
1729 typedef struct { unsigned char bin[20]; /**< binary representation of hash */} lwsgw_hash_bin;
1730 /** typedef struct lwsgw_hash */
1731 typedef struct { char id[41]; /**< ascii hex representation of hash */ } lwsgw_hash;
1732
1733 /** enum lwsgs_auth_bits */
1734 enum lwsgs_auth_bits {
1735         LWSGS_AUTH_LOGGED_IN = 1, /**< user is logged in as somebody */
1736         LWSGS_AUTH_ADMIN = 2,   /**< logged in as the admin user */
1737         LWSGS_AUTH_VERIFIED = 4,  /**< user has verified his email */
1738         LWSGS_AUTH_FORGOT_FLOW = 8,     /**< he just completed "forgot password" flow */
1739 };
1740
1741 /** struct lws_session_info - information about user session status */
1742 struct lws_session_info {
1743         char username[32]; /**< username logged in as, or empty string */
1744         char email[100]; /**< email address associated with login, or empty string */
1745         char ip[72]; /**< ip address session was started from */
1746         unsigned int mask; /**< access rights mask associated with session
1747                             * see enum lwsgs_auth_bits */
1748         char session[42]; /**< session id string, usable as opaque uid when not logged in */
1749 };
1750
1751 /** enum lws_gs_event */
1752 enum lws_gs_event {
1753         LWSGSE_CREATED, /**< a new user was created */
1754         LWSGSE_DELETED  /**< an existing user was deleted */
1755 };
1756
1757 /** struct lws_gs_event_args */
1758 struct lws_gs_event_args {
1759         enum lws_gs_event event; /**< which event happened */
1760         const char *username; /**< which username the event happened to */
1761         const char *email; /**< the email address of that user */
1762 };
1763
1764 ///@}
1765
1766
1767 /*! \defgroup context-and-vhost
1768  * \ingroup lwsapi
1769  *
1770  * ##Context and Vhost releated functions
1771  *
1772  *  LWS requires that there is one context, in which you may define multiple
1773  *  vhosts.  Each vhost is a virtual host, with either its own listen port
1774  *  or sharing an existing one.  Each vhost has its own SSL context that can
1775  *  be set up individually or left disabled.
1776  *
1777  *  If you don't care about multiple "site" support, you can ignore it and
1778  *  lws will create a single default vhost at context creation time.
1779  */
1780 ///@{
1781
1782 /*
1783  * NOTE: These public enums are part of the abi.  If you want to add one,
1784  * add it at where specified so existing users are unaffected.
1785  */
1786
1787 /** enum lws_context_options - context and vhost options */
1788 enum lws_context_options {
1789         LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT     = (1 << 1) |
1790                                                                   (1 << 12),
1791         /**< (VH) Don't allow the connection unless the client has a
1792          * client cert that we recognize; provides
1793          * LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT */
1794         LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME            = (1 << 2),
1795         /**< (CTX) Don't try to get the server's hostname */
1796         LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT             = (1 << 3) |
1797                                                                   (1 << 12),
1798         /**< (VH) Allow non-SSL (plaintext) connections on the same
1799          * port as SSL is listening... undermines the security of SSL;
1800          * provides  LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT */
1801         LWS_SERVER_OPTION_LIBEV                                 = (1 << 4),
1802         /**< (CTX) Use libev event loop */
1803         LWS_SERVER_OPTION_DISABLE_IPV6                          = (1 << 5),
1804         /**< (VH) Disable IPV6 support */
1805         LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS                   = (1 << 6),
1806         /**< (VH) Don't load OS CA certs, you will need to load your
1807          * own CA cert(s) */
1808         LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED                = (1 << 7),
1809         /**< (VH) Accept connections with no valid Cert (eg, selfsigned) */
1810         LWS_SERVER_OPTION_VALIDATE_UTF8                         = (1 << 8),
1811         /**< (VH) Check UT-8 correctness */
1812         LWS_SERVER_OPTION_SSL_ECDH                              = (1 << 9) |
1813                                                                   (1 << 12),
1814         /**< (VH)  initialize ECDH ciphers */
1815         LWS_SERVER_OPTION_LIBUV                                 = (1 << 10),
1816         /**< (CTX)  Use libuv event loop */
1817         LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS                = (1 << 11) |
1818                                                                   (1 << 12),
1819         /**< (VH) Use http redirect to force http to https
1820          * (deprecated: use mount redirection) */
1821         LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT                    = (1 << 12),
1822         /**< (CTX) Initialize the SSL library at all */
1823         LWS_SERVER_OPTION_EXPLICIT_VHOSTS                       = (1 << 13),
1824         /**< (CTX) Only create the context when calling context
1825          * create api, implies user code will create its own vhosts */
1826         LWS_SERVER_OPTION_UNIX_SOCK                             = (1 << 14),
1827         /**< (VH) Use Unix socket */
1828         LWS_SERVER_OPTION_STS                                   = (1 << 15),
1829         /**< (VH) Send Strict Transport Security header, making
1830          * clients subsequently go to https even if user asked for http */
1831         LWS_SERVER_OPTION_IPV6_V6ONLY_MODIFY                    = (1 << 16),
1832         /**< (VH) Enable LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE to take effect */
1833         LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE                     = (1 << 17),
1834         /**< (VH) if set, only ipv6 allowed on the vhost */
1835         LWS_SERVER_OPTION_UV_NO_SIGSEGV_SIGFPE_SPIN             = (1 << 18),
1836         /**< (CTX) Libuv only: Do not spin on SIGSEGV / SIGFPE.  A segfault
1837          * normally makes the lib spin so you can attach a debugger to it
1838          * even if it happened without a debugger in place.  You can disable
1839          * that by giving this option.
1840          */
1841         LWS_SERVER_OPTION_JUST_USE_RAW_ORIGIN                   = (1 << 19),
1842         /**< For backwards-compatibility reasons, by default
1843          * lws prepends "http://" to the origin you give in the client
1844          * connection info struct.  If you give this flag when you create
1845          * the context, only the string you give in the client connect
1846          * info for .origin (if any) will be used directly.
1847          */
1848         LWS_SERVER_OPTION_FALLBACK_TO_RAW                       = (1 << 20),
1849         /**< (VH) if invalid http is coming in the first line,  */
1850         LWS_SERVER_OPTION_LIBEVENT                              = (1 << 21),
1851         /**< (CTX) Use libevent event loop */
1852         LWS_SERVER_OPTION_ONLY_RAW                              = (1 << 22),
1853         /**< (VH) All connections to this vhost / port are RAW as soon as
1854          * the connection is accepted, no HTTP is going to be coming.
1855          */
1856         LWS_SERVER_OPTION_ALLOW_LISTEN_SHARE                    = (1 << 23),
1857         /**< (VH) Set to allow multiple listen sockets on one interface +
1858          * address + port.  The default is to strictly allow only one
1859          * listen socket at a time.  This is automatically selected if you
1860          * have multiple service threads.
1861          */
1862
1863         /****** add new things just above ---^ ******/
1864 };
1865
1866 #define lws_check_opt(c, f) (((c) & (f)) == (f))
1867
1868 struct lws_plat_file_ops;
1869
1870 /** struct lws_context_creation_info - parameters to create context and /or vhost with
1871  *
1872  * This is also used to create vhosts.... if LWS_SERVER_OPTION_EXPLICIT_VHOSTS
1873  * is not given, then for backwards compatibility one vhost is created at
1874  * context-creation time using the info from this struct.
1875  *
1876  * If LWS_SERVER_OPTION_EXPLICIT_VHOSTS is given, then no vhosts are created
1877  * at the same time as the context, they are expected to be created afterwards.
1878  */
1879 struct lws_context_creation_info {
1880         int port;
1881         /**< VHOST: Port to listen on. Use CONTEXT_PORT_NO_LISTEN to suppress
1882          * listening for a client. Use CONTEXT_PORT_NO_LISTEN_SERVER if you are
1883          * writing a server but you are using \ref sock-adopt instead of the
1884          * built-in listener */
1885         const char *iface;
1886         /**< VHOST: NULL to bind the listen socket to all interfaces, or the
1887          * interface name, eg, "eth2"
1888          * If options specifies LWS_SERVER_OPTION_UNIX_SOCK, this member is
1889          * the pathname of a UNIX domain socket. you can use the UNIX domain
1890          * sockets in abstract namespace, by prepending an at symbol to the
1891          * socket name. */
1892         const struct lws_protocols *protocols;
1893         /**< VHOST: Array of structures listing supported protocols and a protocol-
1894          * specific callback for each one.  The list is ended with an
1895          * entry that has a NULL callback pointer. */
1896         const struct lws_extension *extensions;
1897         /**< VHOST: NULL or array of lws_extension structs listing the
1898          * extensions this context supports. */
1899         const struct lws_token_limits *token_limits;
1900         /**< CONTEXT: NULL or struct lws_token_limits pointer which is initialized
1901          * with a token length limit for each possible WSI_TOKEN_ */
1902         const char *ssl_private_key_password;
1903         /**< VHOST: NULL or the passphrase needed for the private key */
1904         const char *ssl_cert_filepath;
1905         /**< VHOST: If libwebsockets was compiled to use ssl, and you want
1906          * to listen using SSL, set to the filepath to fetch the
1907          * server cert from, otherwise NULL for unencrypted */
1908         const char *ssl_private_key_filepath;
1909         /**<  VHOST: filepath to private key if wanting SSL mode;
1910          * if this is set to NULL but sll_cert_filepath is set, the
1911          * OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY callback is called
1912          * to allow setting of the private key directly via openSSL
1913          * library calls */
1914         const char *ssl_ca_filepath;
1915         /**< VHOST: CA certificate filepath or NULL */
1916         const char *ssl_cipher_list;
1917         /**< VHOST: List of valid ciphers to use (eg,
1918          * "RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL"
1919          * or you can leave it as NULL to get "DEFAULT" */
1920         const char *http_proxy_address;
1921         /**< VHOST: If non-NULL, attempts to proxy via the given address.
1922          * If proxy auth is required, use format "username:password\@server:port" */
1923         unsigned int http_proxy_port;
1924         /**< VHOST: If http_proxy_address was non-NULL, uses this port */
1925         int gid;
1926         /**< CONTEXT: group id to change to after setting listen socket, or -1. */
1927         int uid;
1928         /**< CONTEXT: user id to change to after setting listen socket, or -1. */
1929         unsigned int options;
1930         /**< VHOST + CONTEXT: 0, or LWS_SERVER_OPTION_... bitfields */
1931         void *user;
1932         /**< CONTEXT: optional user pointer that can be recovered via the context
1933          *              pointer using lws_context_user */
1934         int ka_time;
1935         /**< CONTEXT: 0 for no TCP keepalive, otherwise apply this keepalive
1936          * timeout to all libwebsocket sockets, client or server */
1937         int ka_probes;
1938         /**< CONTEXT: if ka_time was nonzero, after the timeout expires how many
1939          * times to try to get a response from the peer before giving up
1940          * and killing the connection */
1941         int ka_interval;
1942         /**< CONTEXT: if ka_time was nonzero, how long to wait before each ka_probes
1943          * attempt */
1944 #ifdef LWS_OPENSSL_SUPPORT
1945         SSL_CTX *provided_client_ssl_ctx;
1946         /**< CONTEXT: If non-null, swap out libwebsockets ssl
1947  *              implementation for the one provided by provided_ssl_ctx.
1948  *              Libwebsockets no longer is responsible for freeing the context
1949  *              if this option is selected. */
1950 #else /* maintain structure layout either way */
1951         void *provided_client_ssl_ctx; /**< dummy if ssl disabled */
1952 #endif
1953
1954         short max_http_header_data;
1955         /**< CONTEXT: The max amount of header payload that can be handled
1956          * in an http request (unrecognized header payload is dropped) */
1957         short max_http_header_pool;
1958         /**< CONTEXT: The max number of connections with http headers that
1959          * can be processed simultaneously (the corresponding memory is
1960          * allocated for the lifetime of the context).  If the pool is
1961          * busy new incoming connections must wait for accept until one
1962          * becomes free. */
1963
1964         unsigned int count_threads;
1965         /**< CONTEXT: how many contexts to create in an array, 0 = 1 */
1966         unsigned int fd_limit_per_thread;
1967         /**< CONTEXT: nonzero means restrict each service thread to this
1968          * many fds, 0 means the default which is divide the process fd
1969          * limit by the number of threads. */
1970         unsigned int timeout_secs;
1971         /**< VHOST: various processes involving network roundtrips in the
1972          * library are protected from hanging forever by timeouts.  If
1973          * nonzero, this member lets you set the timeout used in seconds.
1974          * Otherwise a default timeout is used. */
1975         const char *ecdh_curve;
1976         /**< VHOST: if NULL, defaults to initializing server with "prime256v1" */
1977         const char *vhost_name;
1978         /**< VHOST: name of vhost, must match external DNS name used to
1979          * access the site, like "warmcat.com" as it's used to match
1980          * Host: header and / or SNI name for SSL. */
1981         const char * const *plugin_dirs;
1982         /**< CONTEXT: NULL, or NULL-terminated array of directories to
1983          * scan for lws protocol plugins at context creation time */
1984         const struct lws_protocol_vhost_options *pvo;
1985         /**< VHOST: pointer to optional linked list of per-vhost
1986          * options made accessible to protocols */
1987         int keepalive_timeout;
1988         /**< VHOST: (default = 0 = 60s) seconds to allow remote
1989          * client to hold on to an idle HTTP/1.1 connection */
1990         const char *log_filepath;
1991         /**< VHOST: filepath to append logs to... this is opened before
1992          *              any dropping of initial privileges */
1993         const struct lws_http_mount *mounts;
1994         /**< VHOST: optional linked list of mounts for this vhost */
1995         const char *server_string;
1996         /**< CONTEXT: string used in HTTP headers to identify server
1997  *              software, if NULL, "libwebsockets". */
1998         unsigned int pt_serv_buf_size;
1999         /**< CONTEXT: 0 = default of 4096.  This buffer is used by
2000          * various service related features including file serving, it
2001          * defines the max chunk of file that can be sent at once.
2002          * At the risk of lws having to buffer failed large sends, it
2003          * can be increased to, eg, 128KiB to improve throughput. */
2004         unsigned int max_http_header_data2;
2005         /**< CONTEXT: if max_http_header_data is 0 and this
2006          * is nonzero, this will be used in place of the default.  It's
2007          * like this for compatibility with the original short version,
2008          * this is unsigned int length. */
2009         long ssl_options_set;
2010         /**< VHOST: Any bits set here will be set as SSL options */
2011         long ssl_options_clear;
2012         /**< VHOST: Any bits set here will be cleared as SSL options */
2013         unsigned short ws_ping_pong_interval;
2014         /**< CONTEXT: 0 for none, else interval in seconds between sending
2015          * PINGs on idle websocket connections.  When the PING is sent,
2016          * the PONG must come within the normal timeout_secs timeout period
2017          * or the connection will be dropped.
2018          * Any RX or TX traffic on the connection restarts the interval timer,
2019          * so a connection which always sends or receives something at intervals
2020          * less than the interval given here will never send PINGs / expect
2021          * PONGs.  Conversely as soon as the ws connection is established, an
2022          * idle connection will do the PING / PONG roundtrip as soon as
2023          * ws_ping_pong_interval seconds has passed without traffic
2024          */
2025         const struct lws_protocol_vhost_options *headers;
2026                 /**< VHOST: pointer to optional linked list of per-vhost
2027                  * canned headers that are added to server responses */
2028
2029         const struct lws_protocol_vhost_options *reject_service_keywords;
2030         /**< CONTEXT: Optional list of keywords and rejection codes + text.
2031          *
2032          * The keywords are checked for existing in the user agent string.
2033          *
2034          * Eg, "badrobot" "404 Not Found"
2035          */
2036         void *external_baggage_free_on_destroy;
2037         /**< CONTEXT: NULL, or pointer to something externally malloc'd, that
2038          * should be freed when the context is destroyed.  This allows you to
2039          * automatically sync the freeing action to the context destruction
2040          * action, so there is no need for an external free() if the context
2041          * succeeded to create.
2042          */
2043
2044 #ifdef LWS_OPENSSL_SUPPORT
2045          /**< CONTEXT: NULL or struct lws_token_limits pointer which is initialized
2046          * with a token length limit for each possible WSI_TOKEN_ */
2047         const char *client_ssl_private_key_password;
2048         /**< VHOST: NULL or the passphrase needed for the private key */
2049         const char *client_ssl_cert_filepath;
2050         /**< VHOST: If libwebsockets was compiled to use ssl, and you want
2051         * to listen using SSL, set to the filepath to fetch the
2052         * server cert from, otherwise NULL for unencrypted */
2053         const char *client_ssl_private_key_filepath;
2054         /**<  VHOST: filepath to private key if wanting SSL mode;
2055         * if this is set to NULL but sll_cert_filepath is set, the
2056         * OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY callback is called
2057         * to allow setting of the private key directly via openSSL
2058         * library calls */
2059         const char *client_ssl_ca_filepath;
2060         /**< VHOST: CA certificate filepath or NULL */
2061         const char *client_ssl_cipher_list;
2062         /**< VHOST: List of valid ciphers to use (eg,
2063         * "RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL"
2064         * or you can leave it as NULL to get "DEFAULT" */
2065 #endif
2066
2067         const struct lws_plat_file_ops *fops;
2068         /**< CONTEXT: NULL, or pointer to an array of fops structs, terminated
2069          * by a sentinel with NULL .open.
2070          *
2071          * If NULL, lws provides just the platform file operations struct for
2072          * backwards compatibility.
2073          */
2074         int simultaneous_ssl_restriction;
2075         /**< CONTEXT: 0 (no limit) or limit of simultaneous SSL sessions possible.*/
2076         const char *socks_proxy_address;
2077         /**< VHOST: If non-NULL, attempts to proxy via the given address.
2078          * If proxy auth is required, use format "username:password\@server:port" */
2079         unsigned int socks_proxy_port;
2080         /**< VHOST: If socks_proxy_address was non-NULL, uses this port */
2081 #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
2082         cap_value_t caps[4];
2083         /**< CONTEXT: array holding Linux capabilities you want to
2084          * continue to be available to the server after it transitions
2085          * to a noprivileged user.  Usually none are needed but for, eg,
2086          * .bind_iface, CAP_NET_RAW is required.  This gives you a way
2087          * to still have the capability but drop root.
2088          */
2089         char count_caps;
2090         /**< CONTEXT: count of Linux capabilities in .caps[].  0 means
2091          * no capabilities will be inherited from root (the default) */
2092 #endif
2093         int bind_iface;
2094         /**< VHOST: nonzero to strictly bind sockets to the interface name in
2095          * .iface (eg, "eth2"), using SO_BIND_TO_DEVICE.
2096          *
2097          * Requires SO_BINDTODEVICE support from your OS and CAP_NET_RAW
2098          * capability.
2099          *
2100          * Notice that common things like access network interface IP from
2101          * your local machine use your lo / loopback interface and will be
2102          * disallowed by this.
2103          */
2104
2105         /* Add new things just above here ---^
2106          * This is part of the ABI, don't needlessly break compatibility
2107          *
2108          * The below is to ensure later library versions with new
2109          * members added above will see 0 (default) even if the app
2110          * was not built against the newer headers.
2111          */
2112         int ssl_info_event_mask;
2113         /**< VHOST: mask of ssl events to be reported on LWS_CALLBACK_SSL_INFO
2114          * callback for connections on this vhost.  The mask values are of
2115          * the form SSL_CB_ALERT, defined in openssl/ssl.h.  The default of
2116          * 0 means no info events will be reported.
2117          */
2118         unsigned int timeout_secs_ah_idle;
2119         /**< VHOST: seconds to allow a client to hold an ah without using it.
2120          * 0 defaults to 10s. */
2121
2122         void *_unused[8]; /**< dummy */
2123 };
2124
2125 /**
2126  * lws_create_context() - Create the websocket handler
2127  * \param info: pointer to struct with parameters
2128  *
2129  *      This function creates the listening socket (if serving) and takes care
2130  *      of all initialization in one step.
2131  *
2132  *      If option LWS_SERVER_OPTION_EXPLICIT_VHOSTS is given, no vhost is
2133  *      created; you're expected to create your own vhosts afterwards using
2134  *      lws_create_vhost().  Otherwise a vhost named "default" is also created
2135  *      using the information in the vhost-related members, for compatibility.
2136  *
2137  *      After initialization, it returns a struct lws_context * that
2138  *      represents this server.  After calling, user code needs to take care
2139  *      of calling lws_service() with the context pointer to get the
2140  *      server's sockets serviced.  This must be done in the same process
2141  *      context as the initialization call.
2142  *
2143  *      The protocol callback functions are called for a handful of events
2144  *      including http requests coming in, websocket connections becoming
2145  *      established, and data arriving; it's also called periodically to allow
2146  *      async transmission.
2147  *
2148  *      HTTP requests are sent always to the FIRST protocol in protocol, since
2149  *      at that time websocket protocol has not been negotiated.  Other
2150  *      protocols after the first one never see any HTTP callback activity.
2151  *
2152  *      The server created is a simple http server by default; part of the
2153  *      websocket standard is upgrading this http connection to a websocket one.
2154  *
2155  *      This allows the same server to provide files like scripts and favicon /
2156  *      images or whatever over http and dynamic data over websockets all in
2157  *      one place; they're all handled in the user callback.
2158  */
2159 LWS_VISIBLE LWS_EXTERN struct lws_context *
2160 lws_create_context(struct lws_context_creation_info *info);
2161
2162 /**
2163  * lws_context_destroy() - Destroy the websocket context
2164  * \param context:      Websocket context
2165  *
2166  *      This function closes any active connections and then frees the
2167  *      context.  After calling this, any further use of the context is
2168  *      undefined.
2169  */
2170 LWS_VISIBLE LWS_EXTERN void
2171 lws_context_destroy(struct lws_context *context);
2172
2173 LWS_VISIBLE LWS_EXTERN void
2174 lws_context_destroy2(struct lws_context *context);
2175
2176 typedef int (*lws_reload_func)(void);
2177
2178 /**
2179  * lws_context_deprecate() - Deprecate the websocket context
2180  * \param context:      Websocket context
2181  *
2182  *      This function is used on an existing context before superceding it
2183  *      with a new context.
2184  *
2185  *      It closes any listen sockets in the context, so new connections are
2186  *      not possible.
2187  *
2188  *      And it marks the context to be deleted when the number of active
2189  *      connections into it falls to zero.
2190  *
2191  *      Otherwise if you attach the deprecated context to the replacement
2192  *      context when it has been created using lws_context_attach_deprecated()
2193  *      both any deprecated and the new context will service their connections.
2194  *
2195  *      This is aimed at allowing seamless configuration reloads.
2196  *
2197  *      The callback cb will be called after the listen sockets are actually
2198  *      closed and may be reopened.  In the callback the new context should be
2199  *      configured and created.  (With libuv, socket close happens async after
2200  *      more loop events).
2201  */
2202 LWS_VISIBLE LWS_EXTERN void
2203 lws_context_deprecate(struct lws_context *context, lws_reload_func cb);
2204
2205 LWS_VISIBLE LWS_EXTERN int
2206 lws_context_is_deprecated(struct lws_context *context);
2207
2208 /**
2209  * lws_set_proxy() - Setups proxy to lws_context.
2210  * \param vhost:        pointer to struct lws_vhost you want set proxy for
2211  * \param proxy: pointer to c string containing proxy in format address:port
2212  *
2213  * Returns 0 if proxy string was parsed and proxy was setup.
2214  * Returns -1 if proxy is NULL or has incorrect format.
2215  *
2216  * This is only required if your OS does not provide the http_proxy
2217  * environment variable (eg, OSX)
2218  *
2219  *   IMPORTANT! You should call this function right after creation of the
2220  *   lws_context and before call to connect. If you call this
2221  *   function after connect behavior is undefined.
2222  *   This function will override proxy settings made on lws_context
2223  *   creation with genenv() call.
2224  */
2225 LWS_VISIBLE LWS_EXTERN int
2226 lws_set_proxy(struct lws_vhost *vhost, const char *proxy);
2227
2228 /**
2229  * lws_set_socks() - Setup socks to lws_context.
2230  * \param vhost:        pointer to struct lws_vhost you want set socks for
2231  * \param socks: pointer to c string containing socks in format address:port
2232  *
2233  * Returns 0 if socks string was parsed and socks was setup.
2234  * Returns -1 if socks is NULL or has incorrect format.
2235  *
2236  * This is only required if your OS does not provide the socks_proxy
2237  * environment variable (eg, OSX)
2238  *
2239  *   IMPORTANT! You should call this function right after creation of the
2240  *   lws_context and before call to connect. If you call this
2241  *   function after connect behavior is undefined.
2242  *   This function will override proxy settings made on lws_context
2243  *   creation with genenv() call.
2244  */
2245 LWS_VISIBLE LWS_EXTERN int
2246 lws_set_socks(struct lws_vhost *vhost, const char *socks);
2247
2248 struct lws_vhost;
2249
2250 /**
2251  * lws_create_vhost() - Create a vhost (virtual server context)
2252  * \param context:      pointer to result of lws_create_context()
2253  * \param info:         pointer to struct with parameters
2254  *
2255  * This function creates a virtual server (vhost) using the vhost-related
2256  * members of the info struct.  You can create many vhosts inside one context
2257  * if you created the context with the option LWS_SERVER_OPTION_EXPLICIT_VHOSTS
2258  */
2259 LWS_VISIBLE LWS_EXTERN struct lws_vhost *
2260 lws_create_vhost(struct lws_context *context,
2261                  struct lws_context_creation_info *info);
2262
2263 /**
2264  * lws_destroy_vhost() - Destroy a vhost (virtual server context)
2265  * \param vhost:        pointer to result of lws_create_vhost()
2266  *
2267  * This function destroys a vhost.  Normally, if you just want to exit,
2268  * then lws_destroy_context() will take care of everything.  If you want
2269  * to destroy an individual vhost and all connections and allocations, you
2270  * can do it with this.
2271  */
2272 LWS_VISIBLE LWS_EXTERN void
2273 lws_vhost_destroy(struct lws_vhost *vh);
2274
2275 /**
2276  * lwsws_get_config_globals() - Parse a JSON server config file
2277  * \param info:         pointer to struct with parameters
2278  * \param d:            filepath of the config file
2279  * \param config_strings: storage for the config strings extracted from JSON,
2280  *                        the pointer is incremented as strings are stored
2281  * \param len:          pointer to the remaining length left in config_strings
2282  *                        the value is decremented as strings are stored
2283  *
2284  * This function prepares a n lws_context_creation_info struct with global
2285  * settings from a file d.
2286  *
2287  * Requires CMake option LWS_WITH_LEJP_CONF to have been enabled
2288  */
2289 LWS_VISIBLE LWS_EXTERN int
2290 lwsws_get_config_globals(struct lws_context_creation_info *info, const char *d,
2291                          char **config_strings, int *len);
2292
2293 /**
2294  * lwsws_get_config_vhosts() - Create vhosts from a JSON server config file
2295  * \param context:      pointer to result of lws_create_context()
2296  * \param info:         pointer to struct with parameters
2297  * \param d:            filepath of the config file
2298  * \param config_strings: storage for the config strings extracted from JSON,
2299  *                        the pointer is incremented as strings are stored
2300  * \param len:          pointer to the remaining length left in config_strings
2301  *                        the value is decremented as strings are stored
2302  *
2303  * This function creates vhosts into a context according to the settings in
2304  *JSON files found in directory d.
2305  *
2306  * Requires CMake option LWS_WITH_LEJP_CONF to have been enabled
2307  */
2308 LWS_VISIBLE LWS_EXTERN int
2309 lwsws_get_config_vhosts(struct lws_context *context,
2310                         struct lws_context_creation_info *info, const char *d,
2311                         char **config_strings, int *len);
2312
2313 /** lws_vhost_get() - \deprecated deprecated: use lws_get_vhost() */
2314 LWS_VISIBLE LWS_EXTERN struct lws_vhost *
2315 lws_vhost_get(struct lws *wsi) LWS_WARN_DEPRECATED;
2316
2317 /**
2318  * lws_get_vhost() - return the vhost a wsi belongs to
2319  *
2320  * \param wsi: which connection
2321  */
2322 LWS_VISIBLE LWS_EXTERN struct lws_vhost *
2323 lws_get_vhost(struct lws *wsi);
2324
2325 /**
2326  * lws_json_dump_vhost() - describe vhost state and stats in JSON
2327  *
2328  * \param vh: the vhost
2329  * \param buf: buffer to fill with JSON
2330  * \param len: max length of buf
2331  */
2332 LWS_VISIBLE LWS_EXTERN int
2333 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len);
2334
2335 /**
2336  * lws_json_dump_context() - describe context state and stats in JSON
2337  *
2338  * \param context: the context
2339  * \param buf: buffer to fill with JSON
2340  * \param len: max length of buf
2341  */
2342 LWS_VISIBLE LWS_EXTERN int
2343 lws_json_dump_context(const struct lws_context *context, char *buf, int len,
2344                       int hide_vhosts);
2345
2346 /**
2347  * lws_context_user() - get the user data associated with the context
2348  * \param context: Websocket context
2349  *
2350  * This returns the optional user allocation that can be attached to
2351  * the context the sockets live in at context_create time.  It's a way
2352  * to let all sockets serviced in the same context share data without
2353  * using globals statics in the user code.
2354  */
2355 LWS_VISIBLE LWS_EXTERN void *
2356 lws_context_user(struct lws_context *context);
2357
2358 /*! \defgroup vhost-mounts Vhost mounts and options
2359  * \ingroup context-and-vhost-creation
2360  *
2361  * ##Vhost mounts and options
2362  */
2363 ///@{
2364 /** struct lws_protocol_vhost_options - linked list of per-vhost protocol
2365  *                                      name=value options
2366  *
2367  * This provides a general way to attach a linked-list of name=value pairs,
2368  * which can also have an optional child link-list using the options member.
2369  */
2370 struct lws_protocol_vhost_options {
2371         const struct lws_protocol_vhost_options *next; /**< linked list */
2372         const struct lws_protocol_vhost_options *options; /**< child linked-list of more options for this node */
2373         const char *name; /**< name of name=value pair */
2374         const char *value; /**< value of name=value pair */
2375 };
2376
2377 /** enum lws_mount_protocols
2378  * This specifies the mount protocol for a mountpoint, whether it is to be
2379  * served from a filesystem, or it is a cgi etc.
2380  */
2381 enum lws_mount_protocols {
2382         LWSMPRO_HTTP            = 0, /**< http reverse proxy */
2383         LWSMPRO_HTTPS           = 1, /**< https reverse proxy */
2384         LWSMPRO_FILE            = 2, /**< serve from filesystem directory */
2385         LWSMPRO_CGI             = 3, /**< pass to CGI to handle */
2386         LWSMPRO_REDIR_HTTP      = 4, /**< redirect to http:// url */
2387         LWSMPRO_REDIR_HTTPS     = 5, /**< redirect to https:// url */
2388         LWSMPRO_CALLBACK        = 6, /**< hand by named protocol's callback */
2389 };
2390
2391 /** struct lws_http_mount
2392  *
2393  * arguments for mounting something in a vhost's url namespace
2394  */
2395 struct lws_http_mount {
2396         const struct lws_http_mount *mount_next;
2397         /**< pointer to next struct lws_http_mount */
2398         const char *mountpoint;
2399         /**< mountpoint in http pathspace, eg, "/" */
2400         const char *origin;
2401         /**< path to be mounted, eg, "/var/www/warmcat.com" */
2402         const char *def;
2403         /**< default target, eg, "index.html" */
2404         const char *protocol;
2405         /**<"protocol-name" to handle mount */
2406
2407         const struct lws_protocol_vhost_options *cgienv;
2408         /**< optional linked-list of cgi options.  These are created
2409          * as environment variables for the cgi process
2410          */
2411         const struct lws_protocol_vhost_options *extra_mimetypes;
2412         /**< optional linked-list of mimetype mappings */
2413         const struct lws_protocol_vhost_options *interpret;
2414         /**< optional linked-list of files to be interpreted */
2415
2416         int cgi_timeout;
2417         /**< seconds cgi is allowed to live, if cgi://mount type */
2418         int cache_max_age;
2419         /**< max-age for reuse of client cache of files, seconds */
2420         unsigned int auth_mask;
2421         /**< bits set here must be set for authorized client session */
2422
2423         unsigned int cache_reusable:1; /**< set if client cache may reuse this */
2424         unsigned int cache_revalidate:1; /**< set if client cache should revalidate on use */
2425         unsigned int cache_intermediaries:1; /**< set if intermediaries are allowed to cache */
2426
2427         unsigned char origin_protocol; /**< one of enum lws_mount_protocols */
2428         unsigned char mountpoint_len; /**< length of mountpoint string */
2429
2430         const char *basic_auth_login_file;
2431         /**<NULL, or filepath to use to check basic auth logins against */
2432
2433         /* Add new things just above here ---^
2434          * This is part of the ABI, don't needlessly break compatibility
2435          *
2436          * The below is to ensure later library versions with new
2437          * members added above will see 0 (default) even if the app
2438          * was not built against the newer headers.
2439          */
2440
2441         void *_unused[2]; /**< dummy */
2442 };
2443 ///@}
2444 ///@}
2445
2446 /*! \defgroup client
2447  * \ingroup lwsapi
2448  *
2449  * ##Client releated functions
2450  * */
2451 ///@{
2452
2453 /** enum lws_client_connect_ssl_connection_flags - flags that may be used
2454  * with struct lws_client_connect_info ssl_connection member to control if
2455  * and how SSL checks apply to the client connection being created
2456  */
2457
2458 enum lws_client_connect_ssl_connection_flags {
2459         LCCSCF_USE_SSL                          = (1 << 0),
2460         LCCSCF_ALLOW_SELFSIGNED                 = (1 << 1),
2461         LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK  = (1 << 2),
2462         LCCSCF_ALLOW_EXPIRED                    = (1 << 3)
2463 };
2464
2465 /** struct lws_client_connect_info - parameters to connect with when using
2466  *                                  lws_client_connect_via_info() */
2467
2468 struct lws_client_connect_info {
2469         struct lws_context *context;
2470         /**< lws context to create connection in */
2471         const char *address;
2472         /**< remote address to connect to */
2473         int port;
2474         /**< remote port to connect to */
2475         int ssl_connection;
2476         /**< nonzero for ssl */
2477         const char *path;
2478         /**< uri path */
2479         const char *host;
2480         /**< content of host header */
2481         const char *origin;
2482         /**< content of origin header */
2483         const char *protocol;
2484         /**< list of ws protocols we could accept */
2485         int ietf_version_or_minus_one;
2486         /**< deprecated: currently leave at 0 or -1 */
2487         void *userdata;
2488         /**< if non-NULL, use this as wsi user_data instead of malloc it */
2489         const void *client_exts;
2490         /**< UNUSED... provide in info.extensions at context creation time */
2491         const char *method;
2492         /**< if non-NULL, do this http method instead of ws[s] upgrade.
2493          * use "GET" to be a simple http client connection */
2494         struct lws *parent_wsi;
2495         /**< if another wsi is responsible for this connection, give it here.
2496          * this is used to make sure if the parent closes so do any
2497          * child connections first. */
2498         const char *uri_replace_from;
2499         /**< if non-NULL, when this string is found in URIs in
2500          * text/html content-encoding, it's replaced with uri_replace_to */
2501         const char *uri_replace_to;
2502         /**< see uri_replace_from */
2503         struct lws_vhost *vhost;
2504         /**< vhost to bind to (used to determine related SSL_CTX) */
2505         struct lws **pwsi;
2506         /**< if not NULL, store the new wsi here early in the connection
2507          * process.  Although we return the new wsi, the call to create the
2508          * client connection does progress the connection somewhat and may
2509          * meet an error that will result in the connection being scrubbed and
2510          * NULL returned.  While the wsi exists though, he may process a
2511          * callback like CLIENT_CONNECTION_ERROR with his wsi: this gives the
2512          * user callback a way to identify which wsi it is that faced the error
2513          * even before the new wsi is returned and even if ultimately no wsi
2514          * is returned.
2515          */
2516         const char *iface;
2517         /**< NULL to allow routing on any interface, or interface name or IP
2518          * to bind the socket to */
2519
2520         /* Add new things just above here ---^
2521          * This is part of the ABI, don't needlessly break compatibility
2522          *
2523          * The below is to ensure later library versions with new
2524          * members added above will see 0 (default) even if the app
2525          * was not built against the newer headers.
2526          */
2527
2528         void *_unused[4]; /**< dummy */
2529 };
2530
2531 /**
2532  * lws_client_connect_via_info() - Connect to another websocket server
2533  * \param ccinfo: pointer to lws_client_connect_info struct
2534  *
2535  *      This function creates a connection to a remote server using the
2536  *      information provided in ccinfo.
2537  */
2538 LWS_VISIBLE LWS_EXTERN struct lws *
2539 lws_client_connect_via_info(struct lws_client_connect_info * ccinfo);
2540
2541 /**
2542  * lws_client_connect() - Connect to another websocket server
2543  *              \deprecated DEPRECATED use lws_client_connect_via_info
2544  * \param clients:      Websocket context
2545  * \param address:      Remote server address, eg, "myserver.com"
2546  * \param port: Port to connect to on the remote server, eg, 80
2547  * \param ssl_connection:       0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
2548  *                      signed certs
2549  * \param path: Websocket path on server
2550  * \param host: Hostname on server
2551  * \param origin:       Socket origin name
2552  * \param protocol:     Comma-separated list of protocols being asked for from
2553  *              the server, or just one.  The server will pick the one it
2554  *              likes best.  If you don't want to specify a protocol, which is
2555  *              legal, use NULL here.
2556  * \param ietf_version_or_minus_one: -1 to ask to connect using the default, latest
2557  *              protocol supported, or the specific protocol ordinal
2558  *
2559  *      This function creates a connection to a remote server
2560  */
2561 /* deprecated, use lws_client_connect_via_info() */
2562 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
2563 lws_client_connect(struct lws_context *clients, const char *address,
2564                    int port, int ssl_connection, const char *path,
2565                    const char *host, const char *origin, const char *protocol,
2566                    int ietf_version_or_minus_one) LWS_WARN_DEPRECATED;
2567 /* deprecated, use lws_client_connect_via_info() */
2568 /**
2569  * lws_client_connect_extended() - Connect to another websocket server
2570  *                      \deprecated DEPRECATED use lws_client_connect_via_info
2571  * \param clients:      Websocket context
2572  * \param address:      Remote server address, eg, "myserver.com"
2573  * \param port: Port to connect to on the remote server, eg, 80
2574  * \param ssl_connection:       0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
2575  *                      signed certs
2576  * \param path: Websocket path on server
2577  * \param host: Hostname on server
2578  * \param origin:       Socket origin name
2579  * \param protocol:     Comma-separated list of protocols being asked for from
2580  *              the server, or just one.  The server will pick the one it
2581  *              likes best.
2582  * \param ietf_version_or_minus_one: -1 to ask to connect using the default, latest
2583  *              protocol supported, or the specific protocol ordinal
2584  * \param userdata: Pre-allocated user data
2585  *
2586  *      This function creates a connection to a remote server
2587  */
2588 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
2589 lws_client_connect_extended(struct lws_context *clients, const char *address,
2590                             int port, int ssl_connection, const char *path,
2591                             const char *host, const char *origin,
2592                             const char *protocol, int ietf_version_or_minus_one,
2593                             void *userdata) LWS_WARN_DEPRECATED;
2594
2595 /**
2596  * lws_init_vhost_client_ssl() - also enable client SSL on an existing vhost
2597  *
2598  * \param info: client ssl related info
2599  * \param vhost: which vhost to initialize client ssl operations on
2600  *
2601  * You only need to call this if you plan on using SSL client connections on
2602  * the vhost.  For non-SSL client connections, it's not necessary to call this.
2603  *
2604  * The following members of info are used during the call
2605  *
2606  *       - options must have LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT set,
2607  *           otherwise the call does nothing
2608  *       - provided_client_ssl_ctx must be NULL to get a generated client
2609  *           ssl context, otherwise you can pass a prepared one in by setting it
2610  *       - ssl_cipher_list may be NULL or set to the client valid cipher list
2611  *       - ssl_ca_filepath may be NULL or client cert filepath
2612  *       - ssl_cert_filepath may be NULL or client cert filepath
2613  *       - ssl_private_key_filepath may be NULL or client cert private key
2614  *
2615  * You must create your vhost explicitly if you want to use this, so you have
2616  * a pointer to the vhost.  Create the context first with the option flag
2617  * LWS_SERVER_OPTION_EXPLICIT_VHOSTS and then call lws_create_vhost() with
2618  * the same info struct.
2619  */
2620 LWS_VISIBLE LWS_EXTERN int
2621 lws_init_vhost_client_ssl(const struct lws_context_creation_info *info,
2622                           struct lws_vhost *vhost);
2623 /**
2624  * lws_http_client_read() - consume waiting received http client data
2625  *
2626  * \param wsi: client connection
2627  * \param buf: pointer to buffer pointer - fill with pointer to your buffer
2628  * \param len: pointer to chunk length - fill with max length of buffer
2629  *
2630  * This is called when the user code is notified client http data has arrived.
2631  * The user code may choose to delay calling it to consume the data, for example
2632  * waiting until an onward connection is writeable.
2633  *
2634  * For non-chunked connections, up to len bytes of buf are filled with the
2635  * received content.  len is set to the actual amount filled before return.
2636  *
2637  * For chunked connections, the linear buffer content contains the chunking
2638  * headers and it cannot be passed in one lump.  Instead, this function will
2639  * call back LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ with in pointing to the
2640  * chunk start and len set to the chunk length.  There will be as many calls
2641  * as there are chunks or partial chunks in the buffer.
2642  */
2643 LWS_VISIBLE LWS_EXTERN int
2644 lws_http_client_read(struct lws *wsi, char **buf, int *len);
2645
2646 /**
2647  * lws_http_client_http_response() - get last HTTP response code
2648  *
2649  * \param wsi: client connection
2650  *
2651  * Returns the last server response code, eg, 200 for client http connections.
2652  */
2653 LWS_VISIBLE LWS_EXTERN unsigned int
2654 lws_http_client_http_response(struct lws *wsi);
2655
2656 LWS_VISIBLE LWS_EXTERN void
2657 lws_client_http_body_pending(struct lws *wsi, int something_left_to_send);
2658
2659 /**
2660  * lws_client_http_body_pending() - control if client connection neeeds to send body
2661  *
2662  * \param wsi: client connection
2663  * \param something_left_to_send: nonzero if need to send more body, 0 (default)
2664  *                              if nothing more to send
2665  *
2666  * If you will send payload data with your HTTP client connection, eg, for POST,
2667  * when you set the related http headers in
2668  * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER callback you should also call
2669  * this API with something_left_to_send nonzero, and call
2670  * lws_callback_on_writable(wsi);
2671  *
2672  * After sending the headers, lws will call your callback with
2673  * LWS_CALLBACK_CLIENT_HTTP_WRITEABLE reason when writable.  You can send the
2674  * next part of the http body payload, calling lws_callback_on_writable(wsi);
2675  * if there is more to come, or lws_client_http_body_pending(wsi, 0); to
2676  * let lws know the last part is sent and the connection can move on.
2677  */
2678
2679 ///@}
2680
2681 /** \defgroup service Built-in service loop entry
2682  *
2683  * ##Built-in service loop entry
2684  *
2685  * If you're not using libev / libuv, these apis are needed to enter the poll()
2686  * wait in lws and service any connections with pending events.
2687  */
2688 ///@{
2689
2690 /**
2691  * lws_service() - Service any pending websocket activity
2692  * \param context:      Websocket context
2693  * \param timeout_ms:   Timeout for poll; 0 means return immediately if nothing needed
2694  *              service otherwise block and service immediately, returning
2695  *              after the timeout if nothing needed service.
2696  *
2697  *      This function deals with any pending websocket traffic, for three
2698  *      kinds of event.  It handles these events on both server and client
2699  *      types of connection the same.
2700  *
2701  *      1) Accept new connections to our context's server
2702  *
2703  *      2) Call the receive callback for incoming frame data received by
2704  *          server or client connections.
2705  *
2706  *      You need to call this service function periodically to all the above
2707  *      functions to happen; if your application is single-threaded you can
2708  *      just call it in your main event loop.
2709  *
2710  *      Alternatively you can fork a new process that asynchronously handles
2711  *      calling this service in a loop.  In that case you are happy if this
2712  *      call blocks your thread until it needs to take care of something and
2713  *      would call it with a large nonzero timeout.  Your loop then takes no
2714  *      CPU while there is nothing happening.
2715  *
2716  *      If you are calling it in a single-threaded app, you don't want it to
2717  *      wait around blocking other things in your loop from happening, so you
2718  *      would call it with a timeout_ms of 0, so it returns immediately if
2719  *      nothing is pending, or as soon as it services whatever was pending.
2720  */
2721 LWS_VISIBLE LWS_EXTERN int
2722 lws_service(struct lws_context *context, int timeout_ms);
2723
2724 /**
2725  * lws_service() - Service any pending websocket activity
2726  *
2727  * \param context:      Websocket context
2728  * \param timeout_ms:   Timeout for poll; 0 means return immediately if nothing needed
2729  *              service otherwise block and service immediately, returning
2730  *              after the timeout if nothing needed service.
2731  *
2732  * Same as lws_service(), but for a specific thread service index.  Only needed
2733  * if you are spawning multiple service threads.
2734  */
2735 LWS_VISIBLE LWS_EXTERN int
2736 lws_service_tsi(struct lws_context *context, int timeout_ms, int tsi);
2737
2738 /**
2739  * lws_cancel_service_pt() - Cancel servicing of pending socket activity
2740  *                              on one thread
2741  * \param wsi:  Cancel service on the thread this wsi is serviced by
2742  *
2743  *      This function lets a call to lws_service() waiting for a timeout
2744  *      immediately return.
2745  *
2746  *      It works by creating a phony event and then swallowing it silently.
2747  *
2748  *      The reason it may be needed is when waiting in poll(), changes to
2749  *      the event masks are ignored by the OS until poll() is reentered.  This
2750  *      lets you halt the poll() wait and make the reentry happen immediately
2751  *      instead of having the wait out the rest of the poll timeout.
2752  */
2753 LWS_VISIBLE LWS_EXTERN void
2754 lws_cancel_service_pt(struct lws *wsi);
2755
2756 /**
2757  * lws_cancel_service() - Cancel wait for new pending socket activity
2758  * \param context:      Websocket context
2759  *
2760  *      This function let a call to lws_service() waiting for a timeout
2761  *      immediately return.
2762  *
2763  *      What it basically does is provide a fake event that will be swallowed,
2764  *      so the wait in poll() is ended.  That's useful because poll() doesn't
2765  *      attend to changes in POLLIN/OUT/ERR until it re-enters the wait.
2766  */
2767 LWS_VISIBLE LWS_EXTERN void
2768 lws_cancel_service(struct lws_context *context);
2769
2770 /**
2771  * lws_service_fd() - Service polled socket with something waiting
2772  * \param context:      Websocket context
2773  * \param pollfd:       The pollfd entry describing the socket fd and which events
2774  *              happened, or NULL to tell lws to do only timeout servicing.
2775  *
2776  * This function takes a pollfd that has POLLIN or POLLOUT activity and
2777  * services it according to the state of the associated
2778  * struct lws.
2779  *
2780  * The one call deals with all "service" that might happen on a socket
2781  * including listen accepts, http files as well as websocket protocol.
2782  *
2783  * If a pollfd says it has something, you can just pass it to
2784  * lws_service_fd() whether it is a socket handled by lws or not.
2785  * If it sees it is a lws socket, the traffic will be handled and
2786  * pollfd->revents will be zeroed now.
2787  *
2788  * If the socket is foreign to lws, it leaves revents alone.  So you can
2789  * see if you should service yourself by checking the pollfd revents
2790  * after letting lws try to service it.
2791  *
2792  * You should also call this with pollfd = NULL to just allow the
2793  * once-per-second global timeout checks; if less than a second since the last
2794  * check it returns immediately then.
2795  */
2796 LWS_VISIBLE LWS_EXTERN int
2797 lws_service_fd(struct lws_context *context, struct lws_pollfd *pollfd);
2798
2799 /**
2800  * lws_service_fd_tsi() - Service polled socket in specific service thread
2801  * \param context:      Websocket context
2802  * \param pollfd:       The pollfd entry describing the socket fd and which events
2803  *              happened.
2804  * \param tsi: thread service index
2805  *
2806  * Same as lws_service_fd() but used with multiple service threads
2807  */
2808 LWS_VISIBLE LWS_EXTERN int
2809 lws_service_fd_tsi(struct lws_context *context, struct lws_pollfd *pollfd,
2810                    int tsi);
2811
2812 /**
2813  * lws_service_adjust_timeout() - Check for any connection needing forced service
2814  * \param context:      Websocket context
2815  * \param timeout_ms:   The original poll timeout value.  You can just set this
2816  *                      to 1 if you don't really have a poll timeout.
2817  * \param tsi: thread service index
2818  *
2819  * Under some conditions connections may need service even though there is no
2820  * pending network action on them, this is "forced service".  For default
2821  * poll() and libuv / libev, the library takes care of calling this and
2822  * dealing with it for you.  But for external poll() integration, you need
2823  * access to the apis.
2824  *
2825  * If anybody needs "forced service", returned timeout is zero.  In that case,
2826  * you can call lws_service_tsi() with a timeout of -1 to only service
2827  * guys who need forced service.
2828  */
2829 LWS_VISIBLE LWS_EXTERN int
2830 lws_service_adjust_timeout(struct lws_context *context, int timeout_ms, int tsi);
2831
2832 /* Backwards compatibility */
2833 #define lws_plat_service_tsi lws_service_tsi
2834
2835 LWS_VISIBLE LWS_EXTERN int
2836 lws_handle_POLLOUT_event(struct lws *wsi, struct lws_pollfd *pollfd);
2837
2838 ///@}
2839
2840 /*! \defgroup http HTTP
2841
2842     Modules related to handling HTTP
2843 */
2844 //@{
2845
2846 /*! \defgroup httpft HTTP File transfer
2847  * \ingroup http
2848
2849     APIs for sending local files in response to HTTP requests
2850 */
2851 //@{
2852
2853 /**
2854  * lws_get_mimetype() - Determine mimetype to use from filename
2855  *
2856  * \param file:         filename
2857  * \param m:            NULL, or mount context
2858  *
2859  * This uses a canned list of known filetypes first, if no match and m is
2860  * non-NULL, then tries a list of per-mount file suffix to mimtype mappings.
2861  *
2862  * Returns either NULL or a pointer to the mimetype matching the file.
2863  */
2864 LWS_VISIBLE LWS_EXTERN const char *
2865 lws_get_mimetype(const char *file, const struct lws_http_mount *m);
2866
2867 /**
2868  * lws_serve_http_file() - Send a file back to the client using http
2869  * \param wsi:          Websocket instance (available from user callback)
2870  * \param file:         The file to issue over http
2871  * \param content_type: The http content type, eg, text/html
2872  * \param other_headers:        NULL or pointer to header string
2873  * \param other_headers_len:    length of the other headers if non-NULL
2874  *
2875  *      This function is intended to be called from the callback in response
2876  *      to http requests from the client.  It allows the callback to issue
2877  *      local files down the http link in a single step.
2878  *
2879  *      Returning <0 indicates error and the wsi should be closed.  Returning
2880  *      >0 indicates the file was completely sent and
2881  *      lws_http_transaction_completed() called on the wsi (and close if != 0)
2882  *      ==0 indicates the file transfer is started and needs more service later,
2883  *      the wsi should be left alone.
2884  */
2885 LWS_VISIBLE LWS_EXTERN int
2886 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
2887                     const char *other_headers, int other_headers_len);
2888
2889 LWS_VISIBLE LWS_EXTERN int
2890 lws_serve_http_file_fragment(struct lws *wsi);
2891 //@}
2892
2893 /*! \defgroup html-chunked-substitution HTML Chunked Substitution
2894  * \ingroup http
2895  *
2896  * ##HTML chunked Substitution
2897  *
2898  * APIs for receiving chunks of text, replacing a set of variable names via
2899  * a callback, and then prepending and appending HTML chunked encoding
2900  * headers.
2901  */
2902 //@{
2903
2904 enum http_status {
2905         HTTP_STATUS_OK                                          = 200,
2906         HTTP_STATUS_NO_CONTENT                                  = 204,
2907         HTTP_STATUS_PARTIAL_CONTENT                             = 206,
2908
2909         HTTP_STATUS_MOVED_PERMANENTLY                           = 301,
2910         HTTP_STATUS_FOUND                                       = 302,
2911         HTTP_STATUS_SEE_OTHER                                   = 303,
2912         HTTP_STATUS_NOT_MODIFIED                                = 304,
2913
2914         HTTP_STATUS_BAD_REQUEST                                 = 400,
2915         HTTP_STATUS_UNAUTHORIZED,
2916         HTTP_STATUS_PAYMENT_REQUIRED,
2917         HTTP_STATUS_FORBIDDEN,
2918         HTTP_STATUS_NOT_FOUND,
2919         HTTP_STATUS_METHOD_NOT_ALLOWED,
2920         HTTP_STATUS_NOT_ACCEPTABLE,
2921         HTTP_STATUS_PROXY_AUTH_REQUIRED,
2922         HTTP_STATUS_REQUEST_TIMEOUT,
2923         HTTP_STATUS_CONFLICT,
2924         HTTP_STATUS_GONE,
2925         HTTP_STATUS_LENGTH_REQUIRED,
2926         HTTP_STATUS_PRECONDITION_FAILED,
2927         HTTP_STATUS_REQ_ENTITY_TOO_LARGE,
2928         HTTP_STATUS_REQ_URI_TOO_LONG,
2929         HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE,
2930         HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE,
2931         HTTP_STATUS_EXPECTATION_FAILED,
2932
2933         HTTP_STATUS_INTERNAL_SERVER_ERROR                       = 500,
2934         HTTP_STATUS_NOT_IMPLEMENTED,
2935         HTTP_STATUS_BAD_GATEWAY,
2936         HTTP_STATUS_SERVICE_UNAVAILABLE,
2937         HTTP_STATUS_GATEWAY_TIMEOUT,
2938         HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED,
2939 };
2940
2941 struct lws_process_html_args {
2942         char *p; /**< pointer to the buffer containing the data */
2943         int len; /**< length of the original data at p */
2944         int max_len; /**< maximum length we can grow the data to */
2945         int final; /**< set if this is the last chunk of the file */
2946 };
2947
2948 typedef const char *(*lws_process_html_state_cb)(void *data, int index);
2949
2950 struct lws_process_html_state {
2951         char *start; /**< pointer to start of match */
2952         char swallow[16]; /**< matched character buffer */
2953         int pos; /**< position in match */
2954         void *data; /**< opaque pointer */
2955         const char * const *vars; /**< list of variable names */
2956         int count_vars; /**< count of variable names */
2957
2958         lws_process_html_state_cb replace; /**< called on match to perform substitution */
2959 };
2960
2961 /*! lws_chunked_html_process() - generic chunked substitution
2962  * \param args: buffer to process using chunked encoding
2963  * \param s: current processing state
2964  */
2965 LWS_VISIBLE LWS_EXTERN int
2966 lws_chunked_html_process(struct lws_process_html_args *args,
2967                          struct lws_process_html_state *s);
2968 //@}
2969
2970 /** \defgroup HTTP-headers-read HTTP headers: read
2971  * \ingroup http
2972  *
2973  * ##HTTP header releated functions
2974  *
2975  *  In lws the client http headers are temporarily stored in a pool, only for the
2976  *  duration of the http part of the handshake.  It's because in most cases,
2977  *  the header content is ignored for the whole rest of the connection lifetime
2978  *  and would then just be taking up space needlessly.
2979  *
2980  *  During LWS_CALLBACK_HTTP when the URI path is delivered is the last time
2981  *  the http headers are still allocated, you can use these apis then to
2982  *  look at and copy out interesting header content (cookies, etc)
2983  *
2984  *  Notice that the header total length reported does not include a terminating
2985  *  '\0', however you must allocate for it when using the _copy apis.  So the
2986  *  length reported for a header containing "123" is 3, but you must provide
2987  *  a buffer of length 4 so that "123\0" may be copied into it, or the copy
2988  *  will fail with a nonzero return code.
2989  *
2990  *  In the special case of URL arguments, like ?x=1&y=2, the arguments are
2991  *  stored in a token named for the method, eg,  WSI_TOKEN_GET_URI if it
2992  *  was a GET or WSI_TOKEN_POST_URI if POST.  You can check the total
2993  *  length to confirm the method.
2994  *
2995  *  For URL arguments, each argument is stored urldecoded in a "fragment", so
2996  *  you can use the fragment-aware api lws_hdr_copy_fragment() to access each
2997  *  argument in turn: the fragments contain urldecoded strings like x=1 or y=2.
2998  *
2999  *  As a convenience, lws has an api that will find the fragment with a
3000  *  given name= part, lws_get_urlarg_by_name().
3001  */
3002 ///@{
3003
3004 /** struct lws_tokens
3005  * you need these to look at headers that have been parsed if using the
3006  * LWS_CALLBACK_FILTER_CONNECTION callback.  If a header from the enum
3007  * list below is absent, .token = NULL and token_len = 0.  Otherwise .token
3008  * points to .token_len chars containing that header content.
3009  */
3010 struct lws_tokens {
3011         char *token; /**< pointer to start of the token */
3012         int token_len; /**< length of the token's value */
3013 };
3014
3015 /* enum lws_token_indexes
3016  * these have to be kept in sync with lextable.h / minilex.c
3017  *
3018  * NOTE: These public enums are part of the abi.  If you want to add one,
3019  * add it at where specified so existing users are unaffected.
3020  */
3021 enum lws_token_indexes {
3022         WSI_TOKEN_GET_URI                                       =  0,
3023         WSI_TOKEN_POST_URI                                      =  1,
3024         WSI_TOKEN_OPTIONS_URI                                   =  2,
3025         WSI_TOKEN_HOST                                          =  3,
3026         WSI_TOKEN_CONNECTION                                    =  4,
3027         WSI_TOKEN_UPGRADE                                       =  5,
3028         WSI_TOKEN_ORIGIN                                        =  6,
3029         WSI_TOKEN_DRAFT                                         =  7,
3030         WSI_TOKEN_CHALLENGE                                     =  8,
3031         WSI_TOKEN_EXTENSIONS                                    =  9,
3032         WSI_TOKEN_KEY1                                          = 10,
3033         WSI_TOKEN_KEY2                                          = 11,
3034         WSI_TOKEN_PROTOCOL                                      = 12,
3035         WSI_TOKEN_ACCEPT                                        = 13,
3036         WSI_TOKEN_NONCE                                         = 14,
3037         WSI_TOKEN_HTTP                                          = 15,
3038         WSI_TOKEN_HTTP2_SETTINGS                                = 16,
3039         WSI_TOKEN_HTTP_ACCEPT                                   = 17,
3040         WSI_TOKEN_HTTP_AC_REQUEST_HEADERS                       = 18,
3041         WSI_TOKEN_HTTP_IF_MODIFIED_SINCE                        = 19,
3042         WSI_TOKEN_HTTP_IF_NONE_MATCH                            = 20,
3043         WSI_TOKEN_HTTP_ACCEPT_ENCODING                          = 21,
3044         WSI_TOKEN_HTTP_ACCEPT_LANGUAGE                          = 22,
3045         WSI_TOKEN_HTTP_PRAGMA                                   = 23,
3046         WSI_TOKEN_HTTP_CACHE_CONTROL                            = 24,
3047         WSI_TOKEN_HTTP_AUTHORIZATION                            = 25,
3048         WSI_TOKEN_HTTP_COOKIE                                   = 26,
3049         WSI_TOKEN_HTTP_CONTENT_LENGTH                           = 27,
3050         WSI_TOKEN_HTTP_CONTENT_TYPE                             = 28,
3051         WSI_TOKEN_HTTP_DATE                                     = 29,
3052         WSI_TOKEN_HTTP_RANGE                                    = 30,
3053         WSI_TOKEN_HTTP_REFERER                                  = 31,
3054         WSI_TOKEN_KEY                                           = 32,
3055         WSI_TOKEN_VERSION                                       = 33,
3056         WSI_TOKEN_SWORIGIN                                      = 34,
3057
3058         WSI_TOKEN_HTTP_COLON_AUTHORITY                          = 35,
3059         WSI_TOKEN_HTTP_COLON_METHOD                             = 36,
3060         WSI_TOKEN_HTTP_COLON_PATH                               = 37,
3061         WSI_TOKEN_HTTP_COLON_SCHEME                             = 38,
3062         WSI_TOKEN_HTTP_COLON_STATUS                             = 39,
3063
3064         WSI_TOKEN_HTTP_ACCEPT_CHARSET                           = 40,
3065         WSI_TOKEN_HTTP_ACCEPT_RANGES                            = 41,
3066         WSI_TOKEN_HTTP_ACCESS_CONTROL_ALLOW_ORIGIN              = 42,
3067         WSI_TOKEN_HTTP_AGE                                      = 43,
3068         WSI_TOKEN_HTTP_ALLOW                                    = 44,
3069         WSI_TOKEN_HTTP_CONTENT_DISPOSITION                      = 45,
3070         WSI_TOKEN_HTTP_CONTENT_ENCODING                         = 46,
3071         WSI_TOKEN_HTTP_CONTENT_LANGUAGE                         = 47,
3072         WSI_TOKEN_HTTP_CONTENT_LOCATION                         = 48,
3073         WSI_TOKEN_HTTP_CONTENT_RANGE                            = 49,
3074         WSI_TOKEN_HTTP_ETAG                                     = 50,
3075         WSI_TOKEN_HTTP_EXPECT                                   = 51,
3076         WSI_TOKEN_HTTP_EXPIRES                                  = 52,
3077         WSI_TOKEN_HTTP_FROM                                     = 53,
3078         WSI_TOKEN_HTTP_IF_MATCH                                 = 54,
3079         WSI_TOKEN_HTTP_IF_RANGE                                 = 55,
3080         WSI_TOKEN_HTTP_IF_UNMODIFIED_SINCE                      = 56,
3081         WSI_TOKEN_HTTP_LAST_MODIFIED                            = 57,
3082         WSI_TOKEN_HTTP_LINK                                     = 58,
3083         WSI_TOKEN_HTTP_LOCATION                                 = 59,
3084         WSI_TOKEN_HTTP_MAX_FORWARDS                             = 60,
3085         WSI_TOKEN_HTTP_PROXY_AUTHENTICATE                       = 61,
3086         WSI_TOKEN_HTTP_PROXY_AUTHORIZATION                      = 62,
3087         WSI_TOKEN_HTTP_REFRESH                                  = 63,
3088         WSI_TOKEN_HTTP_RETRY_AFTER                              = 64,
3089         WSI_TOKEN_HTTP_SERVER                                   = 65,
3090         WSI_TOKEN_HTTP_SET_COOKIE                               = 66,
3091         WSI_TOKEN_HTTP_STRICT_TRANSPORT_SECURITY                = 67,
3092         WSI_TOKEN_HTTP_TRANSFER_ENCODING                        = 68,
3093         WSI_TOKEN_HTTP_USER_AGENT                               = 69,
3094         WSI_TOKEN_HTTP_VARY                                     = 70,
3095         WSI_TOKEN_HTTP_VIA                                      = 71,
3096         WSI_TOKEN_HTTP_WWW_AUTHENTICATE                         = 72,
3097
3098         WSI_TOKEN_PATCH_URI                                     = 73,
3099         WSI_TOKEN_PUT_URI                                       = 74,
3100         WSI_TOKEN_DELETE_URI                                    = 75,
3101
3102         WSI_TOKEN_HTTP_URI_ARGS                                 = 76,
3103         WSI_TOKEN_PROXY                                         = 77,
3104         WSI_TOKEN_HTTP_X_REAL_IP                                = 78,
3105         WSI_TOKEN_HTTP1_0                                       = 79,
3106         WSI_TOKEN_X_FORWARDED_FOR                               = 80,
3107         WSI_TOKEN_CONNECT                                       = 81,
3108         /****** add new things just above ---^ ******/
3109
3110         /* use token storage to stash these internally, not for
3111          * user use */
3112
3113         _WSI_TOKEN_CLIENT_SENT_PROTOCOLS,
3114         _WSI_TOKEN_CLIENT_PEER_ADDRESS,
3115         _WSI_TOKEN_CLIENT_URI,
3116         _WSI_TOKEN_CLIENT_HOST,
3117         _WSI_TOKEN_CLIENT_ORIGIN,
3118         _WSI_TOKEN_CLIENT_METHOD,
3119         _WSI_TOKEN_CLIENT_IFACE,
3120
3121         /* always last real token index*/
3122         WSI_TOKEN_COUNT,
3123
3124         /* parser state additions, no storage associated */
3125         WSI_TOKEN_NAME_PART,
3126         WSI_TOKEN_SKIPPING,
3127         WSI_TOKEN_SKIPPING_SAW_CR,
3128         WSI_PARSING_COMPLETE,
3129         WSI_INIT_TOKEN_MUXURL,
3130 };
3131
3132 struct lws_token_limits {
3133         unsigned short token_limit[WSI_TOKEN_COUNT]; /**< max chars for this token */
3134 };
3135
3136 /**
3137  * lws_token_to_string() - returns a textual representation of a hdr token index
3138  *
3139  * \param: token index
3140  */
3141 LWS_VISIBLE LWS_EXTERN const unsigned char *
3142 lws_token_to_string(enum lws_token_indexes token);
3143
3144
3145 /**
3146  * lws_hdr_total_length: report length of all fragments of a header totalled up
3147  *              The returned length does not include the space for a
3148  *              terminating '\0'
3149  *
3150  * \param wsi: websocket connection
3151  * \param h: which header index we are interested in
3152  */
3153 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3154 lws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h);
3155
3156 /**
3157  * lws_hdr_fragment_length: report length of a single fragment of a header
3158  *              The returned length does not include the space for a
3159  *              terminating '\0'
3160  *
3161  * \param wsi: websocket connection
3162  * \param h: which header index we are interested in
3163  * \param frag_idx: which fragment of h we want to get the length of
3164  */
3165 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3166 lws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx);
3167
3168 /**
3169  * lws_hdr_copy() - copy a single fragment of the given header to a buffer
3170  *              The buffer length len must include space for an additional
3171  *              terminating '\0', or it will fail returning -1.
3172  *
3173  * \param wsi: websocket connection
3174  * \param dest: destination buffer
3175  * \param len: length of destination buffer
3176  * \param h: which header index we are interested in
3177  *
3178  * copies the whole, aggregated header, even if it was delivered in
3179  * several actual headers piece by piece
3180  */
3181 LWS_VISIBLE LWS_EXTERN int
3182 lws_hdr_copy(struct lws *wsi, char *dest, int len, enum lws_token_indexes h);
3183
3184 /**
3185  * lws_hdr_copy_fragment() - copy a single fragment of the given header to a buffer
3186  *              The buffer length len must include space for an additional
3187  *              terminating '\0', or it will fail returning -1.
3188  *              If the requested fragment index is not present, it fails
3189  *              returning -1.
3190  *
3191  * \param wsi: websocket connection
3192  * \param dest: destination buffer
3193  * \param len: length of destination buffer
3194  * \param h: which header index we are interested in
3195  * \param frag_idx: which fragment of h we want to copy
3196  *
3197  * Normally this is only useful
3198  * to parse URI arguments like ?x=1&y=2, token index WSI_TOKEN_HTTP_URI_ARGS
3199  * fragment 0 will contain "x=1" and fragment 1 "y=2"
3200  */
3201 LWS_VISIBLE LWS_EXTERN int
3202 lws_hdr_copy_fragment(struct lws *wsi, char *dest, int len,
3203                       enum lws_token_indexes h, int frag_idx);
3204
3205 /**
3206  * lws_get_urlarg_by_name() - return pointer to arg value if present
3207  * \param wsi: the connection to check
3208  * \param name: the arg name, like "token="
3209  * \param buf: the buffer to receive the urlarg (including the name= part)
3210  * \param len: the length of the buffer to receive the urlarg
3211  *
3212  *     Returns NULL if not found or a pointer inside buf to just after the
3213  *     name= part.
3214  */
3215 LWS_VISIBLE LWS_EXTERN const char *
3216 lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len);
3217 ///@}
3218
3219 /*! \defgroup HTTP-headers-create HTTP headers: create
3220  *
3221  * ## HTTP headers: Create
3222  *
3223  * These apis allow you to create HTTP response headers in a way compatible with
3224  * both HTTP/1.x and HTTP/2.
3225  *
3226  * They each append to a buffer taking care about the buffer end, which is
3227  * passed in as a pointer.  When data is written to the buffer, the current
3228  * position p is updated accordingly.
3229  *
3230  * All of these apis are LWS_WARN_UNUSED_RESULT as they can run out of space
3231  * and fail with nonzero return.
3232  */
3233 ///@{
3234
3235 #define LWSAHH_CODE_MASK                        ((1 << 16) - 1)
3236 #define LWSAHH_FLAG_NO_SERVER_NAME              (1 << 30)
3237
3238 /**
3239  * lws_add_http_header_status() - add the HTTP response status code
3240  *
3241  * \param wsi: the connection to check
3242  * \param code: an HTTP code like 200, 404 etc (see enum http_status)
3243  * \param p: pointer to current position in buffer pointer
3244  * \param end: pointer to end of buffer
3245  *
3246  * Adds the initial response code, so should be called first.
3247  *
3248  * Code may additionally take OR'd flags:
3249  *
3250  *    LWSAHH_FLAG_NO_SERVER_NAME:  don't apply server name header this time
3251  */
3252 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3253 lws_add_http_header_status(struct lws *wsi,
3254                            unsigned int code, unsigned char **p,
3255                            unsigned char *end);
3256 /**
3257  * lws_add_http_header_by_name() - append named header and value
3258  *
3259  * \param wsi: the connection to check
3260  * \param name: the hdr name, like "my-header"
3261  * \param value: the value after the = for this header
3262  * \param length: the length of the value
3263  * \param p: pointer to current position in buffer pointer
3264  * \param end: pointer to end of buffer
3265  *
3266  * Appends name: value to the headers
3267  */
3268 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3269 lws_add_http_header_by_name(struct lws *wsi, const unsigned char *name,
3270                             const unsigned char *value, int length,
3271                             unsigned char **p, unsigned char *end);
3272 /**
3273  * lws_add_http_header_by_token() - append given header and value
3274  *
3275  * \param wsi: the connection to check
3276  * \param token: the token index for the hdr
3277  * \param value: the value after the = for this header
3278  * \param length: the length of the value
3279  * \param p: pointer to current position in buffer pointer
3280  * \param end: pointer to end of buffer
3281  *
3282  * Appends name=value to the headers, but is able to take advantage of better
3283  * HTTP/2 coding mechanisms where possible.
3284  */
3285 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3286 lws_add_http_header_by_token(struct lws *wsi, enum lws_token_indexes token,
3287                              const unsigned char *value, int length,
3288                              unsigned char **p, unsigned char *end);
3289 /**
3290  * lws_add_http_header_content_length() - append content-length helper
3291  *
3292  * \param wsi: the connection to check
3293  * \param content_length: the content length to use
3294  * \param p: pointer to current position in buffer pointer
3295  * \param end: pointer to end of buffer
3296  *
3297  * Appends content-length: content_length to the headers
3298  */
3299 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3300 lws_add_http_header_content_length(struct lws *wsi,
3301                                    lws_filepos_t content_length,
3302                                    unsigned char **p, unsigned char *end);
3303 /**
3304  * lws_finalize_http_header() - terminate header block
3305  *
3306  * \param wsi: the connection to check
3307  * \param p: pointer to current position in buffer pointer
3308  * \param end: pointer to end of buffer
3309  *
3310  * Indicates no more headers will be added
3311  */
3312 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3313 lws_finalize_http_header(struct lws *wsi, unsigned char **p,
3314                          unsigned char *end);
3315 ///@}
3316
3317 /** \defgroup form-parsing  Form Parsing
3318  * \ingroup http
3319  * ##POSTed form parsing functions
3320  *
3321  * These lws_spa (stateful post arguments) apis let you parse and urldecode
3322  * POSTed form arguments, both using simple urlencoded and multipart transfer
3323  * encoding.
3324  *
3325  * It's capable of handling file uploads as well a named input parsing,
3326  * and the apis are the same for both form upload styles.
3327  *
3328  * You feed it a list of parameter names and it creates pointers to the
3329  * urldecoded arguments: file upload parameters pass the file data in chunks to
3330  * a user-supplied callback as they come.
3331  *
3332  * Since it's stateful, it handles the incoming data needing more than one
3333  * POST_BODY callback and has no limit on uploaded file size.
3334  */
3335 ///@{
3336
3337 /** enum lws_spa_fileupload_states */
3338 enum lws_spa_fileupload_states {
3339         LWS_UFS_CONTENT,
3340         /**< a chunk of file content has arrived */
3341         LWS_UFS_FINAL_CONTENT,
3342         /**< the last chunk (possibly zero length) of file content has arrived */
3343         LWS_UFS_OPEN
3344         /**< a new file is starting to arrive */
3345 };
3346
3347 /**
3348  * lws_spa_fileupload_cb() - callback to receive file upload data
3349  *
3350  * \param data: opt_data pointer set in lws_spa_create
3351  * \param name: name of the form field being uploaded
3352  * \param filename: original filename from client
3353  * \param buf: start of data to receive
3354  * \param len: length of data to receive
3355  * \param state: information about how this call relates to file
3356  *
3357  * Notice name and filename shouldn't be trusted, as they are passed from
3358  * HTTP provided by the client.
3359  */
3360 typedef int (*lws_spa_fileupload_cb)(void *data, const char *name,
3361                         const char *filename, char *buf, int len,
3362                         enum lws_spa_fileupload_states state);
3363
3364 /** struct lws_spa - opaque urldecode parser capable of handling multipart
3365  *                      and file uploads */
3366 struct lws_spa;
3367
3368 /**
3369  * lws_spa_create() - create urldecode parser
3370  *
3371  * \param wsi: lws connection (used to find Content Type)
3372  * \param param_names: array of form parameter names, like "username"
3373  * \param count_params: count of param_names
3374  * \param max_storage: total amount of form parameter values we can store
3375  * \param opt_cb: NULL, or callback to receive file upload data.
3376  * \param opt_data: NULL, or user pointer provided to opt_cb.
3377  *
3378  * Creates a urldecode parser and initializes it.
3379  *
3380  * opt_cb can be NULL if you just want normal name=value parsing, however
3381  * if one or more entries in your form are bulk data (file transfer), you
3382  * can provide this callback and filter on the name callback parameter to
3383  * treat that urldecoded data separately.  The callback should return -1
3384  * in case of fatal error, and 0 if OK.
3385  */
3386 LWS_VISIBLE LWS_EXTERN struct lws_spa *
3387 lws_spa_create(struct lws *wsi, const char * const *param_names,
3388                int count_params, int max_storage, lws_spa_fileupload_cb opt_cb,
3389                void *opt_data);
3390
3391 /**
3392  * lws_spa_process() - parses a chunk of input data
3393  *
3394  * \param spa: the parser object previously created
3395  * \param in: incoming, urlencoded data
3396  * \param len: count of bytes valid at \param in
3397  */
3398 LWS_VISIBLE LWS_EXTERN int
3399 lws_spa_process(struct lws_spa *spa, const char *in, int len);
3400
3401 /**
3402  * lws_spa_finalize() - indicate incoming data completed
3403  *
3404  * \param spa: the parser object previously created
3405  */
3406 LWS_VISIBLE LWS_EXTERN int
3407 lws_spa_finalize(struct lws_spa *spa);
3408
3409 /**
3410  * lws_spa_get_length() - return length of parameter value
3411  *
3412  * \param spa: the parser object previously created
3413  * \param n: parameter ordinal to return length of value for
3414  */
3415 LWS_VISIBLE LWS_EXTERN int
3416 lws_spa_get_length(struct lws_spa *spa, int n);
3417
3418 /**
3419  * lws_spa_get_string() - return pointer to parameter value
3420  * \param spa: the parser object previously created
3421  * \param n: parameter ordinal to return pointer to value for
3422  */
3423 LWS_VISIBLE LWS_EXTERN const char *
3424 lws_spa_get_string(struct lws_spa *spa, int n);
3425
3426 /**
3427  * lws_spa_destroy() - destroy parser object
3428  *
3429  * \param spa: the parser object previously created
3430  */
3431 LWS_VISIBLE LWS_EXTERN int
3432 lws_spa_destroy(struct lws_spa *spa);
3433 ///@}
3434
3435 /*! \defgroup urlendec Urlencode and Urldecode
3436  * \ingroup http
3437  *
3438  * ##HTML chunked Substitution
3439  *
3440  * APIs for receiving chunks of text, replacing a set of variable names via
3441  * a callback, and then prepending and appending HTML chunked encoding
3442  * headers.
3443  */
3444 //@{
3445
3446 /**
3447  * lws_urlencode() - like strncpy but with urlencoding
3448  *
3449  * \param escaped: output buffer
3450  * \param string: input buffer ('/0' terminated)
3451  * \param len: output buffer max length
3452  *
3453  * Because urlencoding expands the output string, it's not
3454  * possible to do it in-place, ie, with escaped == string
3455  */
3456 LWS_VISIBLE LWS_EXTERN const char *
3457 lws_urlencode(char *escaped, const char *string, int len);
3458
3459 /*
3460  * URLDECODE 1 / 2
3461  *
3462  * This simple urldecode only operates until the first '\0' and requires the
3463  * data to exist all at once
3464  */
3465 /**
3466  * lws_urldecode() - like strncpy but with urldecoding
3467  *
3468  * \param string: output buffer
3469  * \param escaped: input buffer ('\0' terminated)
3470  * \param len: output buffer max length
3471  *
3472  * This is only useful for '\0' terminated strings
3473  *
3474  * Since urldecoding only shrinks the output string, it is possible to
3475  * do it in-place, ie, string == escaped
3476  */
3477 LWS_VISIBLE LWS_EXTERN int
3478 lws_urldecode(char *string, const char *escaped, int len);
3479 ///@}
3480 /**
3481  * lws_return_http_status() - Return simple http status
3482  * \param wsi:          Websocket instance (available from user callback)
3483  * \param code:         Status index, eg, 404
3484  * \param html_body:            User-readable HTML description < 1KB, or NULL
3485  *
3486  *      Helper to report HTTP errors back to the client cleanly and
3487  *      consistently
3488  */
3489 LWS_VISIBLE LWS_EXTERN int
3490 lws_return_http_status(struct lws *wsi, unsigned int code,
3491                        const char *html_body);
3492
3493 /**
3494  * lws_http_redirect() - write http redirect into buffer
3495  *
3496  * \param wsi:  websocket connection
3497  * \param code: HTTP response code (eg, 301)
3498  * \param loc:  where to redirect to
3499  * \param len:  length of loc
3500  * \param p:    pointer current position in buffer (updated as we write)
3501  * \param end:  pointer to end of buffer
3502  */
3503 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3504 lws_http_redirect(struct lws *wsi, int code, const unsigned char *loc, int len,
3505                   unsigned char **p, unsigned char *end);
3506
3507 /**
3508  * lws_http_transaction_completed() - wait for new http transaction or close
3509  * \param wsi:  websocket connection
3510  *
3511  *      Returns 1 if the HTTP connection must close now
3512  *      Returns 0 and resets connection to wait for new HTTP header /
3513  *        transaction if possible
3514  */
3515 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3516 lws_http_transaction_completed(struct lws *wsi);
3517 ///@}
3518
3519 /*! \defgroup pur Sanitize / purify SQL and JSON helpers
3520  *
3521  * ##Sanitize / purify SQL and JSON helpers
3522  *
3523  * APIs for escaping untrusted JSON and SQL safely before use
3524  */
3525 //@{
3526
3527 /**
3528  * lws_sql_purify() - like strncpy but with escaping for sql quotes
3529  *
3530  * \param escaped: output buffer
3531  * \param string: input buffer ('/0' terminated)
3532  * \param len: output buffer max length
3533  *
3534  * Because escaping expands the output string, it's not
3535  * possible to do it in-place, ie, with escaped == string
3536  */
3537 LWS_VISIBLE LWS_EXTERN const char *
3538 lws_sql_purify(char *escaped, const char *string, int len);
3539
3540 /**
3541  * lws_json_purify() - like strncpy but with escaping for json chars
3542  *
3543  * \param escaped: output buffer
3544  * \param string: input buffer ('/0' terminated)
3545  * \param len: output buffer max length
3546  *
3547  * Because escaping expands the output string, it's not
3548  * possible to do it in-place, ie, with escaped == string
3549  */
3550 LWS_VISIBLE LWS_EXTERN const char *
3551 lws_json_purify(char *escaped, const char *string, int len);
3552 ///@}
3553
3554 /*! \defgroup ev libev helpers
3555  *
3556  * ##libev helpers
3557  *
3558  * APIs specific to libev event loop itegration
3559  */
3560 ///@{
3561
3562 #ifdef LWS_USE_LIBEV
3563 typedef void (lws_ev_signal_cb_t)(EV_P_ struct ev_signal *w, int revents);
3564
3565 LWS_VISIBLE LWS_EXTERN int
3566 lws_ev_sigint_cfg(struct lws_context *context, int use_ev_sigint,
3567                   lws_ev_signal_cb_t *cb);
3568
3569 LWS_VISIBLE LWS_EXTERN int
3570 lws_ev_initloop(struct lws_context *context, struct ev_loop *loop, int tsi);
3571
3572 LWS_VISIBLE LWS_EXTERN void
3573 lws_ev_sigint_cb(struct ev_loop *loop, struct ev_signal *watcher, int revents);
3574 #endif /* LWS_USE_LIBEV */
3575
3576 ///@}
3577
3578 /*! \defgroup uv libuv helpers
3579  *
3580  * ##libuv helpers
3581  *
3582  * APIs specific to libuv event loop itegration
3583  */
3584 ///@{
3585 #ifdef LWS_USE_LIBUV
3586 LWS_VISIBLE LWS_EXTERN int
3587 lws_uv_sigint_cfg(struct lws_context *context, int use_uv_sigint,
3588                   uv_signal_cb cb);
3589
3590 LWS_VISIBLE LWS_EXTERN void
3591 lws_libuv_run(const struct lws_context *context, int tsi);
3592
3593 LWS_VISIBLE LWS_EXTERN void
3594 lws_libuv_stop(struct lws_context *context);
3595
3596 LWS_VISIBLE LWS_EXTERN void
3597 lws_libuv_stop_without_kill(const struct lws_context *context, int tsi);
3598
3599 LWS_VISIBLE LWS_EXTERN int
3600 lws_uv_initloop(struct lws_context *context, uv_loop_t *loop, int tsi);
3601
3602 LWS_VISIBLE LWS_EXTERN uv_loop_t *
3603 lws_uv_getloop(struct lws_context *context, int tsi);
3604
3605 LWS_VISIBLE LWS_EXTERN void
3606 lws_uv_sigint_cb(uv_signal_t *watcher, int signum);
3607
3608 LWS_VISIBLE LWS_EXTERN void
3609 lws_close_all_handles_in_loop(uv_loop_t *loop);
3610 #endif /* LWS_USE_LIBUV */
3611 ///@}
3612
3613 /*! \defgroup event libevent helpers
3614  *
3615  * ##libevent helpers
3616  *
3617  * APIs specific to libevent event loop itegration
3618  */
3619 ///@{
3620
3621 #ifdef LWS_USE_LIBEVENT
3622 typedef void (lws_event_signal_cb_t) (evutil_socket_t sock_fd, short revents,
3623                   void *ctx);
3624
3625 LWS_VISIBLE LWS_EXTERN int
3626 lws_event_sigint_cfg(struct lws_context *context, int use_event_sigint,
3627                   lws_event_signal_cb_t cb);
3628
3629 LWS_VISIBLE LWS_EXTERN int
3630 lws_event_initloop(struct lws_context *context, struct event_base *loop,
3631                   int tsi);
3632
3633 LWS_VISIBLE LWS_EXTERN void
3634 lws_event_sigint_cb(evutil_socket_t sock_fd, short revents,
3635                   void *ctx);
3636 #endif /* LWS_USE_LIBEVENT */
3637
3638 ///@}
3639
3640 /*! \defgroup timeout Connection timeouts
3641
3642     APIs related to setting connection timeouts
3643 */
3644 //@{
3645
3646 /*
3647  * NOTE: These public enums are part of the abi.  If you want to add one,
3648  * add it at where specified so existing users are unaffected.
3649  */
3650 enum pending_timeout {
3651         NO_PENDING_TIMEOUT                                      =  0,
3652         PENDING_TIMEOUT_AWAITING_PROXY_RESPONSE                 =  1,
3653         PENDING_TIMEOUT_AWAITING_CONNECT_RESPONSE               =  2,
3654         PENDING_TIMEOUT_ESTABLISH_WITH_SERVER                   =  3,
3655         PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE                =  4,
3656         PENDING_TIMEOUT_AWAITING_PING                           =  5,
3657         PENDING_TIMEOUT_CLOSE_ACK                               =  6,
3658         PENDING_TIMEOUT_AWAITING_EXTENSION_CONNECT_RESPONSE     =  7,
3659         PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE                   =  8,
3660         PENDING_TIMEOUT_SSL_ACCEPT                              =  9,
3661         PENDING_TIMEOUT_HTTP_CONTENT                            = 10,
3662         PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND                 = 11,
3663         PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE                  = 12,
3664         PENDING_TIMEOUT_SHUTDOWN_FLUSH                          = 13,
3665         PENDING_TIMEOUT_CGI                                     = 14,
3666         PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE                     = 15,
3667         PENDING_TIMEOUT_WS_PONG_CHECK_SEND_PING                 = 16,
3668         PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG                  = 17,
3669         PENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD                    = 18,
3670         PENDING_TIMEOUT_AWAITING_SOCKS_GREETING_REPLY           = 19,
3671         PENDING_TIMEOUT_AWAITING_SOCKS_CONNECT_REPLY            = 20,
3672         PENDING_TIMEOUT_AWAITING_SOCKS_AUTH_REPLY               = 21,
3673         PENDING_TIMEOUT_KILLED_BY_SSL_INFO                      = 22,
3674         PENDING_TIMEOUT_KILLED_BY_PARENT                        = 23,
3675         PENDING_TIMEOUT_CLOSE_SEND                              = 24,
3676         PENDING_TIMEOUT_HOLDING_AH                              = 25,
3677
3678         /****** add new things just above ---^ ******/
3679 };
3680
3681 #define LWS_TO_KILL_ASYNC -1
3682 /**< If LWS_TO_KILL_ASYNC is given as the timeout sec in a lws_set_timeout()
3683  * call, then the connection is marked to be killed at the next timeout
3684  * check.  This is how you should force-close the wsi being serviced if
3685  * you are doing it outside the callback (where you should close by nonzero
3686  * return).
3687  */
3688 #define LWS_TO_KILL_SYNC -2
3689 /**< If LWS_TO_KILL_SYNC is given as the timeout sec in a lws_set_timeout()
3690  * call, then the connection is closed before returning (which may delete
3691  * the wsi).  This should only be used where the wsi being closed is not the
3692  * wsi currently being serviced.
3693  */
3694 /**
3695  * lws_set_timeout() - marks the wsi as subject to a timeout
3696  *
3697  * You will not need this unless you are doing something special
3698  *
3699  * \param wsi:  Websocket connection instance
3700  * \param reason:       timeout reason
3701  * \param secs: how many seconds.  You may set to LWS_TO_KILL_ASYNC to
3702  *              force the connection to timeout at the next opportunity, or
3703  *              LWS_TO_KILL_SYNC to close it synchronously if you know the
3704  *              wsi is not the one currently being serviced.
3705  */
3706 LWS_VISIBLE LWS_EXTERN void
3707 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs);
3708 ///@}
3709
3710 /*! \defgroup sending-data Sending data
3711
3712     APIs related to writing data on a connection
3713 */
3714 //@{
3715 #if !defined(LWS_SIZEOFPTR)
3716 #define LWS_SIZEOFPTR (sizeof (void *))
3717 #endif
3718 #if !defined(u_int64_t)
3719 #define u_int64_t unsigned long long
3720 #endif
3721
3722 #if defined(__x86_64__)
3723 #define _LWS_PAD_SIZE 16        /* Intel recommended for best performance */
3724 #else
3725 #define _LWS_PAD_SIZE LWS_SIZEOFPTR   /* Size of a pointer on the target arch */
3726 #endif
3727 #define _LWS_PAD(n) (((n) % _LWS_PAD_SIZE) ? \
3728                 ((n) + (_LWS_PAD_SIZE - ((n) % _LWS_PAD_SIZE))) : (n))
3729 /* last 2 is for lws-meta */
3730 #define LWS_PRE _LWS_PAD(4 + 10 + 2)
3731 /* used prior to 1.7 and retained for backward compatibility */
3732 #define LWS_SEND_BUFFER_PRE_PADDING LWS_PRE
3733 #define LWS_SEND_BUFFER_POST_PADDING 0
3734
3735 /*
3736  * NOTE: These public enums are part of the abi.  If you want to add one,
3737  * add it at where specified so existing users are unaffected.
3738  */
3739 enum lws_write_protocol {
3740         LWS_WRITE_TEXT                                          = 0,
3741         /**< Send a ws TEXT message,the pointer must have LWS_PRE valid
3742          * memory behind it.  The receiver expects only valid utf-8 in the
3743          * payload */
3744         LWS_WRITE_BINARY                                        = 1,
3745         /**< Send a ws BINARY message, the pointer must have LWS_PRE valid
3746          * memory behind it.  Any sequence of bytes is valid */
3747         LWS_WRITE_CONTINUATION                                  = 2,
3748         /**< Continue a previous ws message, the pointer must have LWS_PRE valid
3749          * memory behind it */
3750         LWS_WRITE_HTTP                                          = 3,
3751         /**< Send HTTP content */
3752
3753         /* LWS_WRITE_CLOSE is handled by lws_close_reason() */
3754         LWS_WRITE_PING                                          = 5,
3755         LWS_WRITE_PONG                                          = 6,
3756
3757         /* Same as write_http but we know this write ends the transaction */
3758         LWS_WRITE_HTTP_FINAL                                    = 7,
3759
3760         /* HTTP2 */
3761
3762         LWS_WRITE_HTTP_HEADERS                                  = 8,
3763         /**< Send http headers (http2 encodes this payload and LWS_WRITE_HTTP
3764          * payload differently, http 1.x links also handle this correctly. so
3765          * to be compatible with both in the future,header response part should
3766          * be sent using this regardless of http version expected)
3767          */
3768
3769         /****** add new things just above ---^ ******/
3770
3771         /* flags */
3772
3773         LWS_WRITE_NO_FIN = 0x40,
3774         /**< This part of the message is not the end of the message */
3775
3776         LWS_WRITE_CLIENT_IGNORE_XOR_MASK = 0x80
3777         /**< client packet payload goes out on wire unmunged
3778          * only useful for security tests since normal servers cannot
3779          * decode the content if used */
3780 };
3781
3782 /* used with LWS_CALLBACK_CHILD_WRITE_VIA_PARENT */
3783
3784 struct lws_write_passthru {
3785         struct lws *wsi;
3786         unsigned char *buf;
3787         size_t len;
3788         enum lws_write_protocol wp;
3789 };
3790
3791
3792 /**
3793  * lws_write() - Apply protocol then write data to client
3794  * \param wsi:  Websocket instance (available from user callback)
3795  * \param buf:  The data to send.  For data being sent on a websocket
3796  *              connection (ie, not default http), this buffer MUST have
3797  *              LWS_PRE bytes valid BEFORE the pointer.
3798  *              This is so the protocol header data can be added in-situ.
3799  * \param len:  Count of the data bytes in the payload starting from buf
3800  * \param protocol:     Use LWS_WRITE_HTTP to reply to an http connection, and one
3801  *              of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
3802  *              data on a websockets connection.  Remember to allow the extra
3803  *              bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
3804  *              are used.
3805  *
3806  *      This function provides the way to issue data back to the client
3807  *      for both http and websocket protocols.
3808  *
3809  * IMPORTANT NOTICE!
3810  *
3811  * When sending with websocket protocol
3812  *
3813  * LWS_WRITE_TEXT,
3814  * LWS_WRITE_BINARY,
3815  * LWS_WRITE_CONTINUATION,
3816  * LWS_WRITE_PING,
3817  * LWS_WRITE_PONG
3818  *
3819  * the send buffer has to have LWS_PRE bytes valid BEFORE
3820  * the buffer pointer you pass to lws_write().
3821  *
3822  * This allows us to add protocol info before and after the data, and send as
3823  * one packet on the network without payload copying, for maximum efficiency.
3824  *
3825  * So for example you need this kind of code to use lws_write with a
3826  * 128-byte payload
3827  *
3828  *   char buf[LWS_PRE + 128];
3829  *
3830  *   // fill your part of the buffer... for example here it's all zeros
3831  *   memset(&buf[LWS_PRE], 0, 128);
3832  *
3833  *   lws_write(wsi, &buf[LWS_PRE], 128, LWS_WRITE_TEXT);
3834  *
3835  * When sending HTTP, with
3836  *
3837  * LWS_WRITE_HTTP,
3838  * LWS_WRITE_HTTP_HEADERS
3839  * LWS_WRITE_HTTP_FINAL
3840  *
3841  * there is no protocol data prepended, and don't need to take care about the
3842  * LWS_PRE bytes valid before the buffer pointer.
3843  *
3844  * LWS_PRE is at least the frame nonce + 2 header + 8 length
3845  * LWS_SEND_BUFFER_POST_PADDING is deprecated, it's now 0 and can be left off.
3846  * The example apps no longer use it.
3847  *
3848  * Pad LWS_PRE to the CPU word size, so that word references
3849  * to the address immediately after the padding won't cause an unaligned access
3850  * error. Sometimes for performance reasons the recommended padding is even
3851  * larger than sizeof(void *).
3852  *
3853  *      In the case of sending using websocket protocol, be sure to allocate
3854  *      valid storage before and after buf as explained above.  This scheme
3855  *      allows maximum efficiency of sending data and protocol in a single
3856  *      packet while not burdening the user code with any protocol knowledge.
3857  *
3858  *      Return may be -1 for a fatal error needing connection close, or the
3859  *      number of bytes sent.
3860  *
3861  * Truncated Writes
3862  * ================
3863  *
3864  * The OS may not accept everything you asked to write on the connection.
3865  *
3866  * Posix defines POLLOUT indication from poll() to show that the connection
3867  * will accept more write data, but it doesn't specifiy how much.  It may just
3868  * accept one byte of whatever you wanted to send.
3869  *
3870  * LWS will buffer the remainder automatically, and send it out autonomously.
3871  *
3872  * During that time, WRITABLE callbacks will be suppressed.
3873  *
3874  * This is to handle corner cases where unexpectedly the OS refuses what we
3875  * usually expect it to accept.  You should try to send in chunks that are
3876  * almost always accepted in order to avoid the inefficiency of the buffering.
3877  */
3878 LWS_VISIBLE LWS_EXTERN int
3879 lws_write(struct lws *wsi, unsigned char *buf, size_t len,
3880           enum lws_write_protocol protocol);
3881
3882 /* helper for case where buffer may be const */
3883 #define lws_write_http(wsi, buf, len) \
3884         lws_write(wsi, (unsigned char *)(buf), len, LWS_WRITE_HTTP)
3885 ///@}
3886
3887 /** \defgroup callback-when-writeable Callback when writeable
3888  *
3889  * ##Callback When Writeable
3890  *
3891  * lws can only write data on a connection when it is able to accept more
3892  * data without blocking.
3893  *
3894  * So a basic requirement is we should only use the lws_write() apis when the
3895  * connection we want to write on says that he can accept more data.
3896  *
3897  * When lws cannot complete your send at the time, it will buffer the data
3898  * and send it in the background, suppressing any further WRITEABLE callbacks
3899  * on that connection until it completes.  So it is important to write new
3900  * things in a new writeable callback.
3901  *
3902  * These apis reflect the various ways we can indicate we would like to be
3903  * called back when one or more connections is writeable.
3904  */
3905 ///@{
3906
3907 /**
3908  * lws_callback_on_writable() - Request a callback when this socket
3909  *                                       becomes able to be written to without
3910  *                                       blocking
3911  *
3912  * \param wsi:  Websocket connection instance to get callback for
3913  *
3914  * - Which:  only this wsi
3915  * - When:   when the individual connection becomes writeable
3916  * - What: LWS_CALLBACK_*_WRITEABLE
3917  */
3918 LWS_VISIBLE LWS_EXTERN int
3919 lws_callback_on_writable(struct lws *wsi);
3920
3921 /**
3922  * lws_callback_on_writable_all_protocol() - Request a callback for all
3923  *                      connections using the given protocol when it
3924  *                      becomes possible to write to each socket without
3925  *                      blocking in turn.
3926  *
3927  * \param context:      lws_context
3928  * \param protocol:     Protocol whose connections will get callbacks
3929  *
3930  * - Which:  connections using this protocol on ANY VHOST
3931  * - When:   when the individual connection becomes writeable
3932  * - What: LWS_CALLBACK_*_WRITEABLE
3933  */
3934 LWS_VISIBLE LWS_EXTERN int
3935 lws_callback_on_writable_all_protocol(const struct lws_context *context,
3936                                       const struct lws_protocols *protocol);
3937
3938 /**
3939  * lws_callback_on_writable_all_protocol_vhost() - Request a callback for
3940  *                      all connections on same vhost using the given protocol
3941  *                      when it becomes possible to write to each socket without
3942  *                      blocking in turn.
3943  *
3944  * \param vhost:        Only consider connections on this lws_vhost
3945  * \param protocol:     Protocol whose connections will get callbacks
3946  *
3947  * - Which:  connections using this protocol on GIVEN VHOST ONLY
3948  * - When:   when the individual connection becomes writeable
3949  * - What: LWS_CALLBACK_*_WRITEABLE
3950  */
3951 LWS_VISIBLE LWS_EXTERN int
3952 lws_callback_on_writable_all_protocol_vhost(const struct lws_vhost *vhost,
3953                                       const struct lws_protocols *protocol);
3954
3955 /**
3956  * lws_callback_all_protocol() - Callback all connections using
3957  *                              the given protocol with the given reason
3958  *
3959  * \param context:      lws_context
3960  * \param protocol:     Protocol whose connections will get callbacks
3961  * \param reason:       Callback reason index
3962  *
3963  * - Which:  connections using this protocol on ALL VHOSTS
3964  * - When:   before returning
3965  * - What:   reason
3966  *
3967  * This isn't normally what you want... normally any update of connection-
3968  * specific information can wait until a network-related callback like rx,
3969  * writable, or close.
3970  */
3971 LWS_VISIBLE LWS_EXTERN int
3972 lws_callback_all_protocol(struct lws_context *context,
3973                           const struct lws_protocols *protocol, int reason);
3974
3975 /**
3976  * lws_callback_all_protocol_vhost() - Callback all connections using
3977  *                              the given protocol with the given reason
3978  *
3979  * \param vh:           Vhost whose connections will get callbacks
3980  * \param protocol:     Which protocol to match
3981  * \param reason:       Callback reason index
3982  *
3983  * - Which:  connections using this protocol on GIVEN VHOST ONLY
3984  * - When:   now
3985  * - What:   reason
3986  */
3987 LWS_VISIBLE LWS_EXTERN int
3988 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
3989                           const struct lws_protocols *protocol, int reason);
3990
3991 /**
3992  * lws_callback_vhost_protocols() - Callback all protocols enabled on a vhost
3993  *                                      with the given reason
3994  *
3995  * \param wsi:  wsi whose vhost will get callbacks
3996  * \param reason:       Callback reason index
3997  * \param in:           in argument to callback
3998  * \param len:  len argument to callback
3999  *
4000  * - Which:  connections using this protocol on same VHOST as wsi ONLY
4001  * - When:   now
4002  * - What:   reason
4003  */
4004 LWS_VISIBLE LWS_EXTERN int
4005 lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len);
4006
4007 LWS_VISIBLE LWS_EXTERN int
4008 lws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason,
4009                     void *user, void *in, size_t len);
4010
4011 /**
4012  * lws_get_socket_fd() - returns the socket file descriptor
4013  *
4014  * You will not need this unless you are doing something special
4015  *
4016  * \param wsi:  Websocket connection instance
4017  */
4018 LWS_VISIBLE LWS_EXTERN int
4019 lws_get_socket_fd(struct lws *wsi);
4020
4021 /**
4022  * lws_get_peer_write_allowance() - get the amount of data writeable to peer
4023  *                                      if known
4024  *
4025  * \param wsi:  Websocket connection instance
4026  *
4027  * if the protocol does not have any guidance, returns -1.  Currently only
4028  * http2 connections get send window information from this API.  But your code
4029  * should use it so it can work properly with any protocol.
4030  *
4031  * If nonzero return is the amount of payload data the peer or intermediary has
4032  * reported it has buffer space for.  That has NO relationship with the amount
4033  * of buffer space your OS can accept on this connection for a write action.
4034  *
4035  * This number represents the maximum you could send to the peer or intermediary
4036  * on this connection right now without the protocol complaining.
4037  *
4038  * lws manages accounting for send window updates and payload writes
4039  * automatically, so this number reflects the situation at the peer or
4040  * intermediary dynamically.
4041  */
4042 LWS_VISIBLE LWS_EXTERN size_t
4043 lws_get_peer_write_allowance(struct lws *wsi);
4044 ///@}
4045
4046 /**
4047  * lws_rx_flow_control() - Enable and disable socket servicing for
4048  *                              received packets.
4049  *
4050  * If the output side of a server process becomes choked, this allows flow
4051  * control for the input side.
4052  *
4053  * \param wsi:  Websocket connection instance to get callback for
4054  * \param enable:       0 = disable read servicing for this connection, 1 = enable
4055  */
4056 LWS_VISIBLE LWS_EXTERN int
4057 lws_rx_flow_control(struct lws *wsi, int enable);
4058
4059 /**
4060  * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
4061  *
4062  * When the user server code realizes it can accept more input, it can
4063  * call this to have the RX flow restriction removed from all connections using
4064  * the given protocol.
4065  * \param context:      lws_context
4066  * \param protocol:     all connections using this protocol will be allowed to receive
4067  */
4068 LWS_VISIBLE LWS_EXTERN void
4069 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
4070                                const struct lws_protocols *protocol);
4071
4072 /**
4073  * lws_remaining_packet_payload() - Bytes to come before "overall"
4074  *                                            rx packet is complete
4075  * \param wsi:          Websocket instance (available from user callback)
4076  *
4077  *      This function is intended to be called from the callback if the
4078  *  user code is interested in "complete packets" from the client.
4079  *  libwebsockets just passes through payload as it comes and issues a buffer
4080  *  additionally when it hits a built-in limit.  The LWS_CALLBACK_RECEIVE
4081  *  callback handler can use this API to find out if the buffer it has just
4082  *  been given is the last piece of a "complete packet" from the client --
4083  *  when that is the case lws_remaining_packet_payload() will return
4084  *  0.
4085  *
4086  *  Many protocols won't care becuse their packets are always small.
4087  */
4088 LWS_VISIBLE LWS_EXTERN size_t
4089 lws_remaining_packet_payload(struct lws *wsi);
4090
4091
4092 /** \defgroup sock-adopt Socket adoption helpers
4093  * ##Socket adoption helpers
4094  *
4095  * When integrating with an external app with its own event loop, these can
4096  * be used to accept connections from someone else's listening socket.
4097  *
4098  * When using lws own event loop, these are not needed.
4099  */
4100 ///@{
4101
4102 /**
4103  * lws_adopt_socket() - adopt foreign socket as if listen socket accepted it
4104  * for the default vhost of context.
4105  * \param context: lws context
4106  * \param accept_fd: fd of already-accepted socket to adopt
4107  *
4108  * Either returns new wsi bound to accept_fd, or closes accept_fd and
4109  * returns NULL, having cleaned up any new wsi pieces.
4110  *
4111  * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
4112  * to ws or just serve http.
4113  */
4114 LWS_VISIBLE LWS_EXTERN struct lws *
4115 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd);
4116 /**
4117  * lws_adopt_socket_vhost() - adopt foreign socket as if listen socket accepted it
4118  * for vhost
4119  * \param vhost: lws vhost
4120  * \param accept_fd: fd of already-accepted socket to adopt
4121  *
4122  * Either returns new wsi bound to accept_fd, or closes accept_fd and
4123  * returns NULL, having cleaned up any new wsi pieces.
4124  *
4125  * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
4126  * to ws or just serve http.
4127  */
4128 LWS_VISIBLE LWS_EXTERN struct lws *
4129 lws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd);
4130
4131 typedef enum {
4132         LWS_ADOPT_RAW_FILE_DESC = 0,    /* convenience constant */
4133         LWS_ADOPT_HTTP = 1,             /* flag: absent implies RAW */
4134         LWS_ADOPT_SOCKET = 2,           /* flag: absent implies file descr */
4135         LWS_ADOPT_ALLOW_SSL = 4,        /* flag: if set requires LWS_ADOPT_SOCKET */
4136         LWS_ADOPT_WS_PARENTIO = 8,      /* flag: ws mode parent handles IO
4137                                          *   if given must be only flag
4138                                          *   wsi put directly into ws mode
4139                                          */
4140 } lws_adoption_type;
4141
4142 typedef union {
4143         lws_sockfd_type sockfd;
4144         lws_filefd_type filefd;
4145 } lws_sock_file_fd_type;
4146
4147 /*
4148 * lws_adopt_descriptor_vhost() - adopt foreign socket or file descriptor
4149 * if socket descriptor, should already have been accepted from listen socket
4150 *
4151 * \param vhost: lws vhost
4152 * \param type: OR-ed combinations of lws_adoption_type flags
4153 * \param fd: union with either .sockfd or .filefd set
4154 * \param vh_prot_name: NULL or vh protocol name to bind raw connection to
4155 * \param parent: NULL or struct lws to attach new_wsi to as a child
4156 *
4157 * Either returns new wsi bound to accept_fd, or closes accept_fd and
4158 * returns NULL, having cleaned up any new wsi pieces.
4159 *
4160 * If LWS_ADOPT_SOCKET is set, LWS adopts the socket in http serving mode, it's
4161 * ready to accept an upgrade to ws or just serve http.
4162 *
4163 * parent may be NULL, if given it should be an existing wsi that will become the
4164 * parent of the new wsi created by this call.
4165 */
4166 LWS_VISIBLE LWS_EXTERN struct lws *
4167 lws_adopt_descriptor_vhost(struct lws_vhost *vh, lws_adoption_type type,
4168                            lws_sock_file_fd_type fd, const char *vh_prot_name,
4169                            struct lws *parent);
4170
4171 /**
4172  * lws_adopt_socket_readbuf() - adopt foreign socket and first rx as if listen socket accepted it
4173  * for the default vhost of context.
4174  * \param context:      lws context
4175  * \param accept_fd:    fd of already-accepted socket to adopt
4176  * \param readbuf:      NULL or pointer to data that must be drained before reading from
4177  *              accept_fd
4178  * \param len:  The length of the data held at \param readbuf
4179  *
4180  * Either returns new wsi bound to accept_fd, or closes accept_fd and
4181  * returns NULL, having cleaned up any new wsi pieces.
4182  *
4183  * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
4184  * to ws or just serve http.
4185  *
4186  * If your external code did not already read from the socket, you can use
4187  * lws_adopt_socket() instead.
4188  *
4189  * This api is guaranteed to use the data at \param readbuf first, before reading from
4190  * the socket.
4191  *
4192  * readbuf is limited to the size of the ah rx buf, currently 2048 bytes.
4193  */
4194 LWS_VISIBLE LWS_EXTERN struct lws *
4195 lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
4196                          const char *readbuf, size_t len);
4197 /**
4198  * lws_adopt_socket_vhost_readbuf() - adopt foreign socket and first rx as if listen socket
4199  * accepted it for vhost.
4200  * \param vhost:        lws vhost
4201  * \param accept_fd:    fd of already-accepted socket to adopt
4202  * \param readbuf:      NULL or pointer to data that must be drained before reading from
4203  *                      accept_fd
4204  * \param len:          The length of the data held at \param readbuf
4205  *
4206  * Either returns new wsi bound to accept_fd, or closes accept_fd and
4207  * returns NULL, having cleaned up any new wsi pieces.
4208  *
4209  * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
4210  * to ws or just serve http.
4211  *
4212  * If your external code did not already read from the socket, you can use
4213  * lws_adopt_socket() instead.
4214  *
4215  * This api is guaranteed to use the data at \param readbuf first, before reading from
4216  * the socket.
4217  *
4218  * readbuf is limited to the size of the ah rx buf, currently 2048 bytes.
4219  */
4220 LWS_VISIBLE LWS_EXTERN struct lws *
4221 lws_adopt_socket_vhost_readbuf(struct lws_vhost *vhost, lws_sockfd_type accept_fd,
4222                                const char *readbuf, size_t len);
4223 ///@}
4224
4225 /** \defgroup net Network related helper APIs
4226  * ##Network related helper APIs
4227  *
4228  * These wrap miscellaneous useful network-related functions
4229  */
4230 ///@{
4231
4232 /**
4233  * lws_canonical_hostname() - returns this host's hostname
4234  *
4235  * This is typically used by client code to fill in the host parameter
4236  * when making a client connection.  You can only call it after the context
4237  * has been created.
4238  *
4239  * \param context:      Websocket context
4240  */
4241 LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
4242 lws_canonical_hostname(struct lws_context *context);
4243
4244 /**
4245  * lws_get_peer_addresses() - Get client address information
4246  * \param wsi:  Local struct lws associated with
4247  * \param fd:           Connection socket descriptor
4248  * \param name: Buffer to take client address name
4249  * \param name_len:     Length of client address name buffer
4250  * \param rip:  Buffer to take client address IP dotted quad
4251  * \param rip_len:      Length of client address IP buffer
4252  *
4253  *      This function fills in name and rip with the name and IP of
4254  *      the client connected with socket descriptor fd.  Names may be
4255  *      truncated if there is not enough room.  If either cannot be
4256  *      determined, they will be returned as valid zero-length strings.
4257  */
4258 LWS_VISIBLE LWS_EXTERN void
4259 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
4260                        int name_len, char *rip, int rip_len);
4261
4262 /**
4263  * lws_get_peer_simple() - Get client address information without RDNS
4264  *
4265  * \param wsi:  Local struct lws associated with
4266  * \param name: Buffer to take client address name
4267  * \param namelen:      Length of client address name buffer
4268  *
4269  * This provides a 123.123.123.123 type IP address in name from the
4270  * peer that has connected to wsi
4271  */
4272 LWS_VISIBLE LWS_EXTERN const char *
4273 lws_get_peer_simple(struct lws *wsi, char *name, int namelen);
4274 #if !defined(LWS_WITH_ESP8266) && !defined(LWS_WITH_ESP32)
4275 /**
4276  * lws_interface_to_sa() - Convert interface name or IP to sockaddr struct
4277  *
4278  * \param ipv6: Allow IPV6 addresses
4279  * \param ifname:       Interface name or IP
4280  * \param addr: struct sockaddr_in * to be written
4281  * \param addrlen:      Length of addr
4282  *
4283  * This converts a textual network interface name to a sockaddr usable by
4284  * other network functions
4285  */
4286 LWS_VISIBLE LWS_EXTERN int
4287 lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr,
4288                     size_t addrlen);
4289 ///@}
4290 #endif
4291
4292 /** \defgroup misc Miscellaneous APIs
4293 * ##Miscellaneous APIs
4294 *
4295 * Various APIs outside of other categories
4296 */
4297 ///@{
4298
4299 /**
4300  * lws_start_foreach_ll(): linkedlist iterator helper start
4301  *
4302  * \param type: type of iteration, eg, struct xyz *
4303  * \param it: iterator var name to create
4304  * \param start: start of list
4305  *
4306  * This helper creates an iterator and starts a while (it) {
4307  * loop.  The iterator runs through the linked list starting at start and
4308  * ends when it gets a NULL.
4309  * The while loop should be terminated using lws_start_foreach_ll().
4310  */
4311 #define lws_start_foreach_ll(type, it, start)\
4312 { \
4313         type it = start; \
4314         while (it) {
4315
4316 /**
4317  * lws_end_foreach_ll(): linkedlist iterator helper end
4318  *
4319  * \param it: same iterator var name given when starting
4320  * \param nxt: member name in the iterator pointing to next list element
4321  *
4322  * This helper is the partner for lws_start_foreach_ll() that ends the
4323  * while loop.
4324  */
4325
4326 #define lws_end_foreach_ll(it, nxt) \
4327                 it = it->nxt; \
4328         } \
4329 }
4330
4331 /**
4332  * lws_start_foreach_llp(): linkedlist pointer iterator helper start
4333  *
4334  * \param type: type of iteration, eg, struct xyz **
4335  * \param it: iterator var name to create
4336  * \param start: start of list
4337  *
4338  * This helper creates an iterator and starts a while (it) {
4339  * loop.  The iterator runs through the linked list starting at the
4340  * address of start and ends when it gets a NULL.
4341  * The while loop should be terminated using lws_start_foreach_llp().
4342  *
4343  * This helper variant iterates using a pointer to the previous linked-list
4344  * element.  That allows you to easily delete list members by rewriting the
4345  * previous pointer to the element's next pointer.
4346  */
4347 #define lws_start_foreach_llp(type, it, start)\
4348 { \
4349         type it = &(start); \
4350         while (*(it)) {
4351
4352 /**
4353  * lws_end_foreach_llp(): linkedlist pointer iterator helper end
4354  *
4355  * \param it: same iterator var name given when starting
4356  * \param nxt: member name in the iterator pointing to next list element
4357  *
4358  * This helper is the partner for lws_start_foreach_llp() that ends the
4359  * while loop.
4360  */
4361
4362 #define lws_end_foreach_llp(it, nxt) \
4363                 it = &(*(it))->nxt; \
4364         } \
4365 }
4366
4367 /**
4368  * lws_snprintf(): snprintf that truncates the returned length too
4369  *
4370  * \param str: destination buffer
4371  * \param size: bytes left in destination buffer
4372  * \param format: format string
4373  * \param ...: args for format
4374  *
4375  * This lets you correctly truncate buffers by concatenating lengths, if you
4376  * reach the limit the reported length doesn't exceed the limit.
4377  */
4378 LWS_VISIBLE LWS_EXTERN int
4379 lws_snprintf(char *str, size_t size, const char *format, ...) LWS_FORMAT(3);
4380
4381 /**
4382  * lws_get_random(): fill a buffer with platform random data
4383  *
4384  * \param context: the lws context
4385  * \param buf: buffer to fill
4386  * \param len: how much to fill
4387  *
4388  * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
4389  * it's interested to see if the frame it's dealing with was sent in binary
4390  * mode.
4391  */
4392 LWS_VISIBLE LWS_EXTERN int
4393 lws_get_random(struct lws_context *context, void *buf, int len);
4394 /**
4395  * lws_daemonize(): make current process run in the background
4396  *
4397  * \param _lock_path: the filepath to write the lock file
4398  *
4399  * Spawn lws as a background process, taking care of various things
4400  */
4401 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4402 lws_daemonize(const char *_lock_path);
4403 /**
4404  * lws_get_library_version(): return string describing the version of lws
4405  *
4406  * On unix, also includes the git describe
4407  */
4408 LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
4409 lws_get_library_version(void);
4410
4411 /**
4412  * lws_wsi_user() - get the user data associated with the connection
4413  * \param wsi: lws connection
4414  *
4415  * Not normally needed since it's passed into the callback
4416  */
4417 LWS_VISIBLE LWS_EXTERN void *
4418 lws_wsi_user(struct lws *wsi);
4419
4420 /**
4421  * lws_wsi_set_user() - set the user data associated with the client connection
4422  * \param wsi: lws connection
4423  * \param user: user data
4424  *
4425  * By default lws allocates this and it's not legal to externally set it
4426  * yourself.  However client connections may have it set externally when the
4427  * connection is created... if so, this api can be used to modify it at
4428  * runtime additionally.
4429  */
4430 LWS_VISIBLE LWS_EXTERN void
4431 lws_set_wsi_user(struct lws *wsi, void *user);
4432
4433 /**
4434  * lws_parse_uri:       cut up prot:/ads:port/path into pieces
4435  *                      Notice it does so by dropping '\0' into input string
4436  *                      and the leading / on the path is consequently lost
4437  *
4438  * \param p:                    incoming uri string.. will get written to
4439  * \param prot:         result pointer for protocol part (https://)
4440  * \param ads:          result pointer for address part
4441  * \param port:         result pointer for port part
4442  * \param path:         result pointer for path part
4443  */
4444 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4445 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
4446               const char **path);
4447
4448 /**
4449  * lws_now_secs(): return seconds since 1970-1-1
4450  */
4451 LWS_VISIBLE LWS_EXTERN unsigned long
4452 lws_now_secs(void);
4453
4454 /**
4455  * lws_get_context - Allow geting lws_context from a Websocket connection
4456  * instance
4457  *
4458  * With this function, users can access context in the callback function.
4459  * Otherwise users may have to declare context as a global variable.
4460  *
4461  * \param wsi:  Websocket connection instance
4462  */
4463 LWS_VISIBLE LWS_EXTERN struct lws_context * LWS_WARN_UNUSED_RESULT
4464 lws_get_context(const struct lws *wsi);
4465
4466 /**
4467  * lws_get_count_threads(): how many service threads the context uses
4468  *
4469  * \param context: the lws context
4470  *
4471  * By default this is always 1, if you asked for more than lws can handle it
4472  * will clip the number of threads.  So you can use this to find out how many
4473  * threads are actually in use.
4474  */
4475 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4476 lws_get_count_threads(struct lws_context *context);
4477
4478 /**
4479  * lws_get_parent() - get parent wsi or NULL
4480  * \param wsi: lws connection
4481  *
4482  * Specialized wsi like cgi stdin/out/err are associated to a parent wsi,
4483  * this allows you to get their parent.
4484  */
4485 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
4486 lws_get_parent(const struct lws *wsi);
4487
4488 /**
4489  * lws_get_child() - get child wsi or NULL
4490  * \param wsi: lws connection
4491  *
4492  * Allows you to find a related wsi from the parent wsi.
4493  */
4494 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
4495 lws_get_child(const struct lws *wsi);
4496
4497 /**
4498  * lws_parent_carries_io() - mark wsi as needing to send messages via parent
4499  *
4500  * \param wsi: child lws connection
4501  */
4502
4503 LWS_VISIBLE LWS_EXTERN void
4504 lws_set_parent_carries_io(struct lws *wsi);
4505
4506 LWS_VISIBLE LWS_EXTERN void *
4507 lws_get_opaque_parent_data(const struct lws *wsi);
4508
4509 LWS_VISIBLE LWS_EXTERN void
4510 lws_set_opaque_parent_data(struct lws *wsi, void *data);
4511
4512 LWS_VISIBLE LWS_EXTERN int
4513 lws_get_child_pending_on_writable(const struct lws *wsi);
4514
4515 LWS_VISIBLE LWS_EXTERN void
4516 lws_clear_child_pending_on_writable(struct lws *wsi);
4517
4518 LWS_VISIBLE LWS_EXTERN int
4519 lws_get_close_length(struct lws *wsi);
4520
4521 LWS_VISIBLE LWS_EXTERN unsigned char *
4522 lws_get_close_payload(struct lws *wsi);
4523
4524 /*
4525  * \deprecated DEPRECATED Note: this is not normally needed as a user api.
4526  * It's provided in case it is
4527  * useful when integrating with other app poll loop service code.
4528  */
4529 LWS_VISIBLE LWS_EXTERN int
4530 lws_read(struct lws *wsi, unsigned char *buf, lws_filepos_t len);
4531
4532 /**
4533  * lws_set_allocator() - custom allocator support
4534  *
4535  * \param realloc
4536  *
4537  * Allows you to replace the allocator (and deallocator) used by lws
4538  */
4539 LWS_VISIBLE LWS_EXTERN void
4540 lws_set_allocator(void *(*realloc)(void *ptr, size_t size));
4541 ///@}
4542
4543 /** \defgroup wsstatus Websocket status APIs
4544  * ##Websocket connection status APIs
4545  *
4546  * These provide information about ws connection or message status
4547  */
4548 ///@{
4549 /**
4550  * lws_send_pipe_choked() - tests if socket is writable or not
4551  * \param wsi: lws connection
4552  *
4553  * Allows you to check if you can write more on the socket
4554  */
4555 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4556 lws_send_pipe_choked(struct lws *wsi);
4557
4558 /**
4559  * lws_is_final_fragment() - tests if last part of ws message
4560  *
4561  * \param wsi: lws connection
4562  */
4563 LWS_VISIBLE LWS_EXTERN int
4564 lws_is_final_fragment(struct lws *wsi);
4565
4566 /**
4567  * lws_is_first_fragment() - tests if first part of ws message
4568  *
4569  * \param wsi: lws connection
4570  */
4571 LWS_VISIBLE LWS_EXTERN int
4572 lws_is_first_fragment(struct lws *wsi);
4573
4574 /**
4575  * lws_get_reserved_bits() - access reserved bits of ws frame
4576  * \param wsi: lws connection
4577  */
4578 LWS_VISIBLE LWS_EXTERN unsigned char
4579 lws_get_reserved_bits(struct lws *wsi);
4580
4581 /**
4582  * lws_partial_buffered() - find out if lws buffered the last write
4583  * \param wsi:  websocket connection to check
4584  *
4585  * Returns 1 if you cannot use lws_write because the last
4586  * write on this connection is still buffered, and can't be cleared without
4587  * returning to the service loop and waiting for the connection to be
4588  * writeable again.
4589  *
4590  * If you will try to do >1 lws_write call inside a single
4591  * WRITEABLE callback, you must check this after every write and bail if
4592  * set, ask for a new writeable callback and continue writing from there.
4593  *
4594  * This is never set at the start of a writeable callback, but any write
4595  * may set it.
4596  */
4597 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4598 lws_partial_buffered(struct lws *wsi);
4599
4600 /**
4601  * lws_frame_is_binary(): true if the current frame was sent in binary mode
4602  *
4603  * \param wsi: the connection we are inquiring about
4604  *
4605  * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
4606  * it's interested to see if the frame it's dealing with was sent in binary
4607  * mode.
4608  */
4609 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4610 lws_frame_is_binary(struct lws *wsi);
4611
4612 /**
4613  * lws_is_ssl() - Find out if connection is using SSL
4614  * \param wsi:  websocket connection to check
4615  *
4616  *      Returns 0 if the connection is not using SSL, 1 if using SSL and
4617  *      using verified cert, and 2 if using SSL but the cert was not
4618  *      checked (appears for client wsi told to skip check on connection)
4619  */
4620 LWS_VISIBLE LWS_EXTERN int
4621 lws_is_ssl(struct lws *wsi);
4622 /**
4623  * lws_is_cgi() - find out if this wsi is running a cgi process
4624  * \param wsi: lws connection
4625  */
4626 LWS_VISIBLE LWS_EXTERN int
4627 lws_is_cgi(struct lws *wsi);
4628
4629 #ifdef LWS_OPENSSL_SUPPORT
4630 /**
4631  * lws_get_ssl() - Return wsi's SSL context structure
4632  * \param wsi:  websocket connection
4633  *
4634  * Returns pointer to the SSL library's context structure
4635  */
4636 LWS_VISIBLE LWS_EXTERN SSL*
4637 lws_get_ssl(struct lws *wsi);
4638 #endif
4639 ///@}
4640
4641
4642 /** \defgroup sha SHA and B64 helpers
4643  * ##SHA and B64 helpers
4644  *
4645  * These provide SHA-1 and B64 helper apis
4646  */
4647 ///@{
4648 #ifdef LWS_SHA1_USE_OPENSSL_NAME
4649 #define lws_SHA1 SHA1
4650 #else
4651 /**
4652  * lws_SHA1(): make a SHA-1 digest of a buffer
4653  *
4654  * \param d: incoming buffer
4655  * \param n: length of incoming buffer
4656  * \param md: buffer for message digest (must be >= 20 bytes)
4657  *
4658  * Reduces any size buffer into a 20-byte SHA-1 hash.
4659  */
4660 LWS_VISIBLE LWS_EXTERN unsigned char *
4661 lws_SHA1(const unsigned char *d, size_t n, unsigned char *md);
4662 #endif
4663 /**
4664  * lws_b64_encode_string(): encode a string into base 64
4665  *
4666  * \param in: incoming buffer
4667  * \param in_len: length of incoming buffer
4668  * \param out: result buffer
4669  * \param out_size: length of result buffer
4670  *
4671  * Encodes a string using b64
4672  */
4673 LWS_VISIBLE LWS_EXTERN int
4674 lws_b64_encode_string(const char *in, int in_len, char *out, int out_size);
4675 /**
4676  * lws_b64_decode_string(): decode a string from base 64
4677  *
4678  * \param in: incoming buffer
4679  * \param out: result buffer
4680  * \param out_size: length of result buffer
4681  *
4682  * Decodes a string using b64
4683  */
4684 LWS_VISIBLE LWS_EXTERN int
4685 lws_b64_decode_string(const char *in, char *out, int out_size);
4686 ///@}
4687
4688
4689 /*! \defgroup cgi cgi handling
4690  *
4691  * ##CGI handling
4692  *
4693  * These functions allow low-level control over stdin/out/err of the cgi.
4694  *
4695  * However for most cases, binding the cgi to http in and out, the default
4696  * lws implementation already does the right thing.
4697  */
4698 #ifdef LWS_WITH_CGI
4699 enum lws_enum_stdinouterr {
4700         LWS_STDIN = 0,
4701         LWS_STDOUT = 1,
4702         LWS_STDERR = 2,
4703 };
4704
4705 enum lws_cgi_hdr_state {
4706         LCHS_HEADER,
4707         LCHS_CR1,
4708         LCHS_LF1,
4709         LCHS_CR2,
4710         LCHS_LF2,
4711         LHCS_RESPONSE,
4712         LHCS_DUMP_HEADERS,
4713         LHCS_PAYLOAD,
4714         LCHS_SINGLE_0A,
4715 };
4716
4717 struct lws_cgi_args {
4718         struct lws **stdwsi; /**< get fd with lws_get_socket_fd() */
4719         enum lws_enum_stdinouterr ch; /**< channel index */
4720         unsigned char *data; /**< for messages with payload */
4721         enum lws_cgi_hdr_state hdr_state; /**< track where we are in cgi headers */
4722         int len; /**< length */
4723 };
4724
4725
4726 /**
4727  * lws_cgi: spawn network-connected cgi process
4728  *
4729  * \param wsi: connection to own the process
4730  * \param exec_array: array of "exec-name" "arg1" ... "argn" NULL
4731  * \param script_uri_path_len: how many chars on the left of the uri are the path to the cgi
4732  * \param timeout_secs: seconds script should be allowed to run
4733  * \param mp_cgienv: pvo list with per-vhost cgi options to put in env
4734  */
4735 LWS_VISIBLE LWS_EXTERN int
4736 lws_cgi(struct lws *wsi, const char * const *exec_array,
4737         int script_uri_path_len, int timeout_secs,
4738         const struct lws_protocol_vhost_options *mp_cgienv);
4739
4740 /**
4741  * lws_cgi_write_split_stdout_headers: write cgi output accounting for header part
4742  *
4743  * \param wsi: connection to own the process
4744  */
4745 LWS_VISIBLE LWS_EXTERN int
4746 lws_cgi_write_split_stdout_headers(struct lws *wsi);
4747
4748 /**
4749  * lws_cgi_kill: terminate cgi process associated with wsi
4750  *
4751  * \param wsi: connection to own the process
4752  */
4753 LWS_VISIBLE LWS_EXTERN int
4754 lws_cgi_kill(struct lws *wsi);
4755 #endif
4756 ///@}
4757
4758
4759 /*! \defgroup fops file operation wrapping
4760  *
4761  * ##File operation wrapping
4762  *
4763  * Use these helper functions if you want to access a file from the perspective
4764  * of a specific wsi, which is usually the case.  If you just want contextless
4765  * file access, use the fops callbacks directly with NULL wsi instead of these
4766  * helpers.
4767  *
4768  * If so, then it calls the platform handler or user overrides where present
4769  * (as defined in info->fops)
4770  *
4771  * The advantage from all this is user code can be portable for file operations
4772  * without having to deal with differences between platforms.
4773  */
4774 //@{
4775
4776 /** struct lws_plat_file_ops - Platform-specific file operations
4777  *
4778  * These provide platform-agnostic ways to deal with filesystem access in the
4779  * library and in the user code.
4780  */
4781
4782 #if defined(LWS_WITH_ESP32)
4783 /* sdk preprocessor defs? compiler issue? gets confused with member names */
4784 #define LWS_FOP_OPEN            _open
4785 #define LWS_FOP_CLOSE           _close
4786 #define LWS_FOP_SEEK_CUR        _seek_cur
4787 #define LWS_FOP_READ            _read
4788 #define LWS_FOP_WRITE           _write
4789 #else
4790 #define LWS_FOP_OPEN            open
4791 #define LWS_FOP_CLOSE           close
4792 #define LWS_FOP_SEEK_CUR        seek_cur
4793 #define LWS_FOP_READ            read
4794 #define LWS_FOP_WRITE           write
4795 #endif
4796
4797 #define LWS_FOP_FLAGS_MASK                 ((1 << 23) - 1)
4798 #define LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP (1 << 24)
4799 #define LWS_FOP_FLAG_COMPR_IS_GZIP         (1 << 25)
4800 #define LWS_FOP_FLAG_MOD_TIME_VALID        (1 << 26)
4801 #define LWS_FOP_FLAG_VIRTUAL               (1 << 27)
4802
4803 struct lws_plat_file_ops;
4804
4805 struct lws_fop_fd {
4806         lws_filefd_type                 fd;
4807         /**< real file descriptor related to the file... */
4808         const struct lws_plat_file_ops  *fops;
4809         /**< fops that apply to this fop_fd */
4810         void                            *filesystem_priv;
4811         /**< ignored by lws; owned by the fops handlers */
4812         lws_filepos_t                   pos;
4813         /**< generic "position in file" */
4814         lws_filepos_t                   len;
4815         /**< generic "length of file" */
4816         lws_fop_flags_t                 flags;
4817         /**< copy of the returned flags */
4818         uint32_t                        mod_time;
4819         /**< optional "modification time of file", only valid if .open()
4820          * set the LWS_FOP_FLAG_MOD_TIME_VALID flag */
4821 };
4822 typedef struct lws_fop_fd *lws_fop_fd_t;
4823
4824 struct lws_fops_index {
4825         const char *sig;        /* NULL or vfs signature, eg, ".zip/" */
4826         uint8_t len;            /* length of above string */
4827 };
4828
4829 struct lws_plat_file_ops {
4830         lws_fop_fd_t (*LWS_FOP_OPEN)(const struct lws_plat_file_ops *fops,
4831                                      const char *filename, const char *vpath,
4832                                      lws_fop_flags_t *flags);
4833         /**< Open file (always binary access if plat supports it)
4834          * vpath may be NULL, or if the fops understands it, the point at which
4835          * the filename's virtual part starts.
4836          * *flags & LWS_FOP_FLAGS_MASK should be set to O_RDONLY or O_RDWR.
4837          * If the file may be gzip-compressed,
4838          * LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP is set.  If it actually is
4839          * gzip-compressed, then the open handler should OR
4840          * LWS_FOP_FLAG_COMPR_IS_GZIP on to *flags before returning.
4841          */
4842         int (*LWS_FOP_CLOSE)(lws_fop_fd_t *fop_fd);
4843         /**< close file AND set the pointer to NULL */
4844         lws_fileofs_t (*LWS_FOP_SEEK_CUR)(lws_fop_fd_t fop_fd,
4845                                           lws_fileofs_t offset_from_cur_pos);
4846         /**< seek from current position */
4847         int (*LWS_FOP_READ)(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4848                             uint8_t *buf, lws_filepos_t len);
4849         /**< Read from file, on exit *amount is set to amount actually read */
4850         int (*LWS_FOP_WRITE)(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4851                              uint8_t *buf, lws_filepos_t len);
4852         /**< Write to file, on exit *amount is set to amount actually written */
4853
4854         struct lws_fops_index fi[3];
4855         /**< vfs path signatures implying use of this fops */
4856
4857         const struct lws_plat_file_ops *next;
4858         /**< NULL or next fops in list */
4859
4860         /* Add new things just above here ---^
4861          * This is part of the ABI, don't needlessly break compatibility */
4862 };
4863
4864 /**
4865  * lws_get_fops() - get current file ops
4866  *
4867  * \param context: context
4868  */
4869 LWS_VISIBLE LWS_EXTERN struct lws_plat_file_ops * LWS_WARN_UNUSED_RESULT
4870 lws_get_fops(struct lws_context *context);
4871 LWS_VISIBLE LWS_EXTERN void
4872 lws_set_fops(struct lws_context *context, const struct lws_plat_file_ops *fops);
4873 /**
4874  * lws_vfs_tell() - get current file position
4875  *
4876  * \param fop_fd: fop_fd we are asking about
4877  */
4878 LWS_VISIBLE LWS_EXTERN lws_filepos_t LWS_WARN_UNUSED_RESULT
4879 lws_vfs_tell(lws_fop_fd_t fop_fd);
4880 /**
4881  * lws_vfs_get_length() - get current file total length in bytes
4882  *
4883  * \param fop_fd: fop_fd we are asking about
4884  */
4885 LWS_VISIBLE LWS_EXTERN lws_filepos_t LWS_WARN_UNUSED_RESULT
4886 lws_vfs_get_length(lws_fop_fd_t fop_fd);
4887 /**
4888  * lws_vfs_get_mod_time() - get time file last modified
4889  *
4890  * \param fop_fd: fop_fd we are asking about
4891  */
4892 LWS_VISIBLE LWS_EXTERN uint32_t LWS_WARN_UNUSED_RESULT
4893 lws_vfs_get_mod_time(lws_fop_fd_t fop_fd);
4894 /**
4895  * lws_vfs_file_seek_set() - seek relative to start of file
4896  *
4897  * \param fop_fd: fop_fd we are seeking in
4898  * \param offset: offset from start of file
4899  */
4900 LWS_VISIBLE LWS_EXTERN lws_fileofs_t
4901 lws_vfs_file_seek_set(lws_fop_fd_t fop_fd, lws_fileofs_t offset);
4902 /**
4903  * lws_vfs_file_seek_end() - seek relative to end of file
4904  *
4905  * \param fop_fd: fop_fd we are seeking in
4906  * \param offset: offset from start of file
4907  */
4908 LWS_VISIBLE LWS_EXTERN lws_fileofs_t
4909 lws_vfs_file_seek_end(lws_fop_fd_t fop_fd, lws_fileofs_t offset);
4910
4911 extern struct lws_plat_file_ops fops_zip;
4912
4913 /**
4914  * lws_plat_file_open() - open vfs filepath
4915  *
4916  * \param fops: file ops struct that applies to this descriptor
4917  * \param vfs_path: filename to open
4918  * \param flags: pointer to open flags
4919  *
4920  * The vfs_path is scanned for known fops signatures, and the open directed
4921  * to any matching fops open.
4922  *
4923  * User code should use this api to perform vfs opens.
4924  *
4925  * returns semi-opaque handle
4926  */
4927 LWS_VISIBLE LWS_EXTERN lws_fop_fd_t LWS_WARN_UNUSED_RESULT
4928 lws_vfs_file_open(const struct lws_plat_file_ops *fops, const char *vfs_path,
4929                   lws_fop_flags_t *flags);
4930
4931 /**
4932  * lws_plat_file_close() - close file
4933  *
4934  * \param fop_fd: file handle to close
4935  */
4936 static LWS_INLINE int
4937 lws_vfs_file_close(lws_fop_fd_t *fop_fd)
4938 {
4939         return (*fop_fd)->fops->LWS_FOP_CLOSE(fop_fd);
4940 }
4941
4942 /**
4943  * lws_plat_file_seek_cur() - close file
4944  *
4945  *
4946  * \param fop_fd: file handle
4947  * \param offset: position to seek to
4948  */
4949 static LWS_INLINE lws_fileofs_t
4950 lws_vfs_file_seek_cur(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
4951 {
4952         return fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, offset);
4953 }
4954 /**
4955  * lws_plat_file_read() - read from file
4956  *
4957  * \param fop_fd: file handle
4958  * \param amount: how much to read (rewritten by call)
4959  * \param buf: buffer to write to
4960  * \param len: max length
4961  */
4962 static LWS_INLINE int LWS_WARN_UNUSED_RESULT
4963 lws_vfs_file_read(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4964                    uint8_t *buf, lws_filepos_t len)
4965 {
4966         return fop_fd->fops->LWS_FOP_READ(fop_fd, amount, buf, len);
4967 }
4968 /**
4969  * lws_plat_file_write() - write from file
4970  *
4971  * \param fop_fd: file handle
4972  * \param amount: how much to write (rewritten by call)
4973  * \param buf: buffer to read from
4974  * \param len: max length
4975  */
4976 static LWS_INLINE int LWS_WARN_UNUSED_RESULT
4977 lws_vfs_file_write(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4978                     uint8_t *buf, lws_filepos_t len)
4979 {
4980         return fop_fd->fops->LWS_FOP_WRITE(fop_fd, amount, buf, len);
4981 }
4982
4983 /* these are the platform file operations implementations... they can
4984  * be called directly and used in fops arrays
4985  */
4986
4987 LWS_VISIBLE LWS_EXTERN lws_fop_fd_t
4988 _lws_plat_file_open(const struct lws_plat_file_ops *fops, const char *filename,
4989                     const char *vpath, lws_fop_flags_t *flags);
4990 LWS_VISIBLE LWS_EXTERN int
4991 _lws_plat_file_close(lws_fop_fd_t *fop_fd);
4992 LWS_VISIBLE LWS_EXTERN lws_fileofs_t
4993 _lws_plat_file_seek_cur(lws_fop_fd_t fop_fd, lws_fileofs_t offset);
4994 LWS_VISIBLE LWS_EXTERN int
4995 _lws_plat_file_read(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4996                     uint8_t *buf, lws_filepos_t len);
4997 LWS_VISIBLE LWS_EXTERN int
4998 _lws_plat_file_write(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4999                      uint8_t *buf, lws_filepos_t len);
5000
5001 LWS_VISIBLE LWS_EXTERN int
5002 lws_alloc_vfs_file(struct lws_context *context, const char *filename, uint8_t **buf,
5003                 lws_filepos_t *amount);
5004 //@}
5005
5006 /** \defgroup smtp
5007  * \ingroup lwsapi
5008  * ##SMTP related functions
5009  *
5010  * These apis let you communicate with a local SMTP server to send email from
5011  * lws.  It handles all the SMTP sequencing and protocol actions.
5012  *
5013  * Your system should have postfix, sendmail or another MTA listening on port
5014  * 25 and able to send email using the "mail" commandline app.  Usually distro
5015  * MTAs are configured for this by default.
5016  *
5017  * It runs via its own libuv events if initialized (which requires giving it
5018  * a libuv loop to attach to).
5019  *
5020  * It operates using three callbacks, on_next() queries if there is a new email
5021  * to send, on_get_body() asks for the body of the email, and on_sent() is
5022  * called after the email is successfully sent.
5023  *
5024  * To use it
5025  *
5026  *  - create an lws_email struct
5027  *
5028  *  - initialize data, loop, the email_* strings, max_content_size and
5029  *    the callbacks
5030  *
5031  *  - call lws_email_init()
5032  *
5033  *  When you have at least one email to send, call lws_email_check() to
5034  *  schedule starting to send it.
5035  */
5036 //@{
5037 #ifdef LWS_WITH_SMTP
5038
5039 /** enum lwsgs_smtp_states - where we are in SMTP protocol sequence */
5040 enum lwsgs_smtp_states {
5041         LGSSMTP_IDLE, /**< awaiting new email */
5042         LGSSMTP_CONNECTING, /**< opening tcp connection to MTA */
5043         LGSSMTP_CONNECTED, /**< tcp connection to MTA is connected */
5044         LGSSMTP_SENT_HELO, /**< sent the HELO */
5045         LGSSMTP_SENT_FROM, /**< sent FROM */
5046         LGSSMTP_SENT_TO, /**< sent TO */
5047         LGSSMTP_SENT_DATA, /**< sent DATA request */
5048         LGSSMTP_SENT_BODY, /**< sent the email body */
5049         LGSSMTP_SENT_QUIT, /**< sent the session quit */
5050 };
5051
5052 /** struct lws_email - abstract context for performing SMTP operations */
5053 struct lws_email {
5054         void *data;
5055         /**< opaque pointer set by user code and available to the callbacks */
5056         uv_loop_t *loop;
5057         /**< the libuv loop we will work on */
5058
5059         char email_smtp_ip[32]; /**< Fill before init, eg, "127.0.0.1" */
5060         char email_helo[32];    /**< Fill before init, eg, "myserver.com" */
5061         char email_from[100];   /**< Fill before init or on_next */
5062         char email_to[100];     /**< Fill before init or on_next */
5063
5064         unsigned int max_content_size;
5065         /**< largest possible email body size */
5066
5067         /* Fill all the callbacks before init */
5068
5069         int (*on_next)(struct lws_email *email);
5070         /**< (Fill in before calling lws_email_init)
5071          * called when idle, 0 = another email to send, nonzero is idle.
5072          * If you return 0, all of the email_* char arrays must be set
5073          * to something useful. */
5074         int (*on_sent)(struct lws_email *email);
5075         /**< (Fill in before calling lws_email_init)
5076          * called when transfer of the email to the SMTP server was
5077          * successful, your callback would remove the current email
5078          * from its queue */
5079         int (*on_get_body)(struct lws_email *email, char *buf, int len);
5080         /**< (Fill in before calling lws_email_init)
5081          * called when the body part of the queued email is about to be
5082          * sent to the SMTP server. */
5083
5084
5085         /* private things */
5086         uv_timer_t timeout_email; /**< private */
5087         enum lwsgs_smtp_states estate; /**< private */
5088         uv_connect_t email_connect_req; /**< private */
5089         uv_tcp_t email_client; /**< private */
5090         time_t email_connect_started; /**< private */
5091         char email_buf[256]; /**< private */
5092         char *content; /**< private */
5093 };
5094
5095 /**
5096  * lws_email_init() - Initialize a struct lws_email
5097  *
5098  * \param email: struct lws_email to init
5099  * \param loop: libuv loop to use
5100  * \param max_content: max email content size
5101  *
5102  * Prepares a struct lws_email for use ending SMTP
5103  */
5104 LWS_VISIBLE LWS_EXTERN int
5105 lws_email_init(struct lws_email *email, uv_loop_t *loop, int max_content);
5106
5107 /**
5108  * lws_email_check() - Request check for new email
5109  *
5110  * \param email: struct lws_email context to check
5111  *
5112  * Schedules a check for new emails in 1s... call this when you have queued an
5113  * email for send.
5114  */
5115 LWS_VISIBLE LWS_EXTERN void
5116 lws_email_check(struct lws_email *email);
5117 /**
5118  * lws_email_destroy() - stop using the struct lws_email
5119  *
5120  * \param email: the struct lws_email context
5121  *
5122  * Stop sending email using email and free allocations
5123  */
5124 LWS_VISIBLE LWS_EXTERN void
5125 lws_email_destroy(struct lws_email *email);
5126
5127 #endif
5128 //@}
5129
5130 /*
5131  * Stats are all uint64_t numbers that start at 0.
5132  * Index names here have the convention
5133  *
5134  *  _C_ counter
5135  *  _B_ byte count
5136  *  _MS_ millisecond count
5137  */
5138
5139 enum {
5140         LWSSTATS_C_CONNECTIONS, /**< count incoming connections */
5141         LWSSTATS_C_API_CLOSE, /**< count calls to close api */
5142         LWSSTATS_C_API_READ, /**< count calls to read from socket api */
5143         LWSSTATS_C_API_LWS_WRITE, /**< count calls to lws_write API */
5144         LWSSTATS_C_API_WRITE, /**< count calls to write API */
5145         LWSSTATS_C_WRITE_PARTIALS, /**< count of partial writes */
5146         LWSSTATS_C_WRITEABLE_CB_REQ, /**< count of writable callback requests */
5147         LWSSTATS_C_WRITEABLE_CB_EFF_REQ, /**< count of effective writable callback requests */
5148         LWSSTATS_C_WRITEABLE_CB, /**< count of writable callbacks */
5149         LWSSTATS_C_SSL_CONNECTIONS_FAILED, /**< count of failed SSL connections */
5150         LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED, /**< count of accepted SSL connections */
5151         LWSSTATS_C_SSL_CONNS_HAD_RX, /**< count of accepted SSL conns that have had some RX */
5152         LWSSTATS_C_TIMEOUTS, /**< count of timed-out connections */
5153         LWSSTATS_C_SERVICE_ENTRY, /**< count of entries to lws service loop */
5154         LWSSTATS_B_READ, /**< aggregate bytes read */
5155         LWSSTATS_B_WRITE, /**< aggregate bytes written */
5156         LWSSTATS_B_PARTIALS_ACCEPTED_PARTS, /**< aggreate of size of accepted write data from new partials */
5157         LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY, /**< aggregate delay in accepting connection */
5158         LWSSTATS_MS_WRITABLE_DELAY, /**< aggregate delay between asking for writable and getting cb */
5159         LWSSTATS_MS_WORST_WRITABLE_DELAY, /**< single worst delay between asking for writable and getting cb */
5160         LWSSTATS_MS_SSL_RX_DELAY, /**< aggregate delay between ssl accept complete and first RX */
5161
5162         /* Add new things just above here ---^
5163          * This is part of the ABI, don't needlessly break compatibility */
5164         LWSSTATS_SIZE
5165 };
5166
5167 #if defined(LWS_WITH_STATS)
5168
5169 LWS_VISIBLE LWS_EXTERN uint64_t
5170 lws_stats_get(struct lws_context *context, int index);
5171 LWS_VISIBLE LWS_EXTERN void
5172 lws_stats_log_dump(struct lws_context *context);
5173 #else
5174 static LWS_INLINE uint64_t
5175 lws_stats_get(struct lws_context *context, int index) { return 0; }
5176 static LWS_INLINE void
5177 lws_stats_log_dump(struct lws_context *context) { }
5178 #endif
5179
5180 #ifdef __cplusplus
5181 }
5182 #endif
5183
5184 #endif