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