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