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