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