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