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