13d8bccc859f52debba57e47dc72bdca2dd7901f
[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 #ifndef LIBWEBSOCKET_H_3060898B846849FF9F88F5DB59B5950C
23 #define LIBWEBSOCKET_H_3060898B846849FF9F88F5DB59B5950C
24
25 #ifdef __cplusplus
26 #include <cstddef>
27 #include <cstdarg>
28 #ifdef MBED_OPERATORS
29 #include "mbed-drivers/mbed.h"
30 #include "sal-iface-eth/EthernetInterface.h"
31 #include "sockets/TCPListener.h"
32 #include "sal-stack-lwip/lwipv4_init.h"
33
34 namespace {
35 }
36 using namespace mbed::Sockets::v0;
37
38
39 struct sockaddr_in;
40 struct lws;
41
42 class lws_conn {
43         public:
44         lws_conn():
45                 ts(NULL),
46                 wsi(NULL),
47                 writeable(1),
48                 awaiting_on_writeable(0)
49         {
50         }
51
52 public:
53         void set_wsi(struct lws *_wsi) { wsi = _wsi; }
54         int actual_onRX(Socket *s);
55         void onRX(Socket *s);
56         void onError(Socket *s, socket_error_t err);
57         void onDisconnect(TCPStream *s);
58         void onSent(Socket *s, uint16_t len);
59         void serialized_writeable(struct lws *wsi);
60
61 public:
62         TCPStream *ts;
63
64 public:
65         struct lws *wsi;
66         char writeable;
67         char awaiting_on_writeable;
68 };
69
70 class lws_conn_listener : lws_conn {
71 public:
72         lws_conn_listener():
73                 srv(SOCKET_STACK_LWIP_IPV4)
74         {
75                 srv.setOnError(TCPStream::ErrorHandler_t(this,
76                                 &lws_conn_listener::onError));
77         }
78
79         void start(const uint16_t port);
80
81 protected:
82         void onRX(Socket *s);
83         void onError(Socket *s, socket_error_t err);
84         void onIncoming(TCPListener *s, void *impl);
85         void onDisconnect(TCPStream *s);
86
87 public:
88         TCPListener srv;
89 };
90
91 #endif
92
93 extern "C" {
94 #else
95 #include <stdarg.h>
96 #endif
97
98 #ifdef MBED_OPERATORS
99 struct sockaddr_in;
100 #define LWS_POSIX 0
101 #else
102 #define LWS_POSIX 1
103 #endif
104
105 #include "lws_config.h"
106
107 #if defined(WIN32) || defined(_WIN32)
108 #ifndef WIN32_LEAN_AND_MEAN
109 #define WIN32_LEAN_AND_MEAN
110 #endif
111
112 #include <winsock2.h>
113 #include <ws2tcpip.h>
114 #include <stddef.h>
115 #include <stdint.h>
116 #include <basetsd.h>
117 #ifndef _WIN32_WCE
118 #include <fcntl.h>
119 #else
120 #define _O_RDONLY       0x0000
121 #define O_RDONLY        _O_RDONLY
122 #endif
123
124 #ifdef _WIN32_WCE
125 #define strcasecmp _stricmp
126 #else
127 #define strcasecmp stricmp
128 #endif
129 #define getdtablesize() 30000
130
131 #define LWS_INLINE __inline
132 #define LWS_VISIBLE
133 #define LWS_WARN_UNUSED_RESULT
134 #define LWS_WARN_DEPRECATED
135
136 #ifdef LWS_DLL
137 #ifdef LWS_INTERNAL
138 #define LWS_EXTERN extern __declspec(dllexport)
139 #else
140 #define LWS_EXTERN extern __declspec(dllimport)
141 #endif
142 #else
143 #define LWS_EXTERN
144 #endif
145
146 #define LWS_INVALID_FILE INVALID_HANDLE_VALUE
147 #define LWS_O_RDONLY _O_RDONLY
148
149 #define snprintf _snprintf
150
151 #else /* NOT WIN32 */
152 #include <unistd.h>
153
154 #if defined(__NetBSD__)
155 #include <netinet/in.h>
156 #endif
157
158 #define LWS_INLINE inline
159 #define LWS_O_RDONLY O_RDONLY
160
161 #ifndef MBED_OPERATORS
162 #include <poll.h>
163 #include <netdb.h>
164 #define LWS_INVALID_FILE -1
165 #else
166 #define getdtablesize() (20)
167 #define LWS_INVALID_FILE NULL
168 #endif
169
170 #if defined(__GNUC__)
171 #define LWS_VISIBLE __attribute__((visibility("default")))
172 #define LWS_WARN_UNUSED_RESULT __attribute__ ((warn_unused_result))
173 #define LWS_WARN_DEPRECATED __attribute__ ((deprecated))
174 #else
175 #define LWS_VISIBLE
176 #define LWS_WARN_UNUSED_RESULT
177 #define LWS_WARN_DEPRECATED
178 #endif
179
180 #if defined(__ANDROID__)
181 #include <unistd.h>
182 #define getdtablesize() sysconf(_SC_OPEN_MAX)
183 #endif
184
185 #endif
186
187 #ifdef LWS_USE_LIBEV
188 #include <ev.h>
189 #endif /* LWS_USE_LIBEV */
190 #ifdef LWS_USE_LIBUV
191 #include <uv.h>
192 #endif /* LWS_USE_LIBUV */
193
194 #ifndef LWS_EXTERN
195 #define LWS_EXTERN extern
196 #endif
197
198 #ifdef _WIN32
199 #define random rand
200 #else
201 #include <sys/time.h>
202 #include <unistd.h>
203 #endif
204
205 #ifdef LWS_OPENSSL_SUPPORT
206
207 #ifdef USE_WOLFSSL
208 #ifdef USE_OLD_CYASSL
209 #include <cyassl/openssl/ssl.h>
210 #include <cyassl/error-ssl.h>
211 #else
212 #include <wolfssl/openssl/ssl.h>
213 #include <wolfssl/error-ssl.h>
214 #endif /* not USE_OLD_CYASSL */
215 #else
216 #if defined(LWS_USE_POLARSSL)
217 #include <polarssl/ssl.h>
218 #define SSL_CTX ssl_context
219 #define SSL ssl_session
220 #else
221 #if defined(LWS_USE_MBEDTLS)
222 #include <mbedtls/ssl.h>
223 #else
224 #include <openssl/ssl.h>
225 #endif /* not USE_MBEDTLS */
226 #endif /* not USE_POLARSSL */
227 #endif /* not USE_WOLFSSL */
228 #endif
229
230
231 #define CONTEXT_PORT_NO_LISTEN -1
232
233 enum lws_log_levels {
234         LLL_ERR = 1 << 0,
235         LLL_WARN = 1 << 1,
236         LLL_NOTICE = 1 << 2,
237         LLL_INFO = 1 << 3,
238         LLL_DEBUG = 1 << 4,
239         LLL_PARSER = 1 << 5,
240         LLL_HEADER = 1 << 6,
241         LLL_EXT = 1 << 7,
242         LLL_CLIENT = 1 << 8,
243         LLL_LATENCY = 1 << 9,
244
245         LLL_COUNT = 10 /* set to count of valid flags */
246 };
247
248 LWS_VISIBLE LWS_EXTERN void _lws_log(int filter, const char *format, ...);
249 LWS_VISIBLE LWS_EXTERN void _lws_logv(int filter, const char *format, va_list vl);
250 LWS_VISIBLE LWS_EXTERN int
251 lwsl_timestamp(int level, char *p, int len);
252
253 /* notice, warn and log are always compiled in */
254 #define lwsl_notice(...) _lws_log(LLL_NOTICE, __VA_ARGS__)
255 #define lwsl_warn(...) _lws_log(LLL_WARN, __VA_ARGS__)
256 #define lwsl_err(...) _lws_log(LLL_ERR, __VA_ARGS__)
257 /*
258  *  weaker logging can be deselected at configure time using --disable-debug
259  *  that gets rid of the overhead of checking while keeping _warn and _err
260  *  active
261  */
262 #ifdef _DEBUG
263
264 #define lwsl_info(...) _lws_log(LLL_INFO, __VA_ARGS__)
265 #define lwsl_debug(...) _lws_log(LLL_DEBUG, __VA_ARGS__)
266 #define lwsl_parser(...) _lws_log(LLL_PARSER, __VA_ARGS__)
267 #define lwsl_header(...)  _lws_log(LLL_HEADER, __VA_ARGS__)
268 #define lwsl_ext(...)  _lws_log(LLL_EXT, __VA_ARGS__)
269 #define lwsl_client(...) _lws_log(LLL_CLIENT, __VA_ARGS__)
270 #define lwsl_latency(...) _lws_log(LLL_LATENCY, __VA_ARGS__)
271 LWS_VISIBLE LWS_EXTERN void lwsl_hexdump(void *buf, size_t len);
272
273 #else /* no debug */
274
275 #define lwsl_info(...) {}
276 #define lwsl_debug(...) {}
277 #define lwsl_parser(...) {}
278 #define lwsl_header(...) {}
279 #define lwsl_ext(...) {}
280 #define lwsl_client(...) {}
281 #define lwsl_latency(...) {}
282 #define lwsl_hexdump(a, b)
283
284 #endif
285
286 #include <stddef.h>
287
288 #ifndef lws_container_of
289 #define lws_container_of(P,T,M) ((T *)((char *)(P) - offsetof(T, M)))
290 #endif
291
292
293 struct lws;
294 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
295
296 /* api change list for user code to test against */
297
298 #define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_ARG
299
300 /* the struct lws_protocols has the id field present */
301 #define LWS_FEATURE_PROTOCOLS_HAS_ID_FIELD
302
303 /* you can call lws_get_peer_write_allowance */
304 #define LWS_FEATURE_PROTOCOLS_HAS_PEER_WRITE_ALLOWANCE
305
306 /* extra parameter introduced in 917f43ab821 */
307 #define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_LEN
308
309 /* File operations stuff exists */
310 #define LWS_FEATURE_FOPS
311
312 /*
313  * NOTE: These public enums are part of the abi.  If you want to add one,
314  * add it at where specified so existing users are unaffected.
315  */
316 enum lws_context_options {
317         LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT     = (1 << 1) |
318                                                                   (1 << 12),
319         LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME            = (1 << 2),
320         LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT             = (1 << 3) |
321                                                                   (1 << 12),
322         LWS_SERVER_OPTION_LIBEV                                 = (1 << 4),
323         LWS_SERVER_OPTION_DISABLE_IPV6                          = (1 << 5),
324         LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS                   = (1 << 6),
325         LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED                = (1 << 7),
326         LWS_SERVER_OPTION_VALIDATE_UTF8                         = (1 << 8),
327         LWS_SERVER_OPTION_SSL_ECDH                              = (1 << 9) |
328                                                                   (1 << 12),
329         LWS_SERVER_OPTION_LIBUV                                 = (1 << 10),
330         LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS                = (1 << 11) |
331                                                                   (1 << 3) |
332                                                                   (1 << 12),
333         LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT                    = (1 << 12),
334         LWS_SERVER_OPTION_EXPLICIT_VHOSTS                       = (1 << 13),
335
336         /****** add new things just above ---^ ******/
337 };
338
339 #define lws_check_opt(c, f) (((c) & (f)) == (f))
340
341 /*
342  * NOTE: These public enums are part of the abi.  If you want to add one,
343  * add it at where specified so existing users are unaffected.
344  */
345 enum lws_callback_reasons {
346         LWS_CALLBACK_ESTABLISHED                                =  0,
347         LWS_CALLBACK_CLIENT_CONNECTION_ERROR                    =  1,
348         LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH                =  2,
349         LWS_CALLBACK_CLIENT_ESTABLISHED                         =  3,
350         LWS_CALLBACK_CLOSED                                     =  4,
351         LWS_CALLBACK_CLOSED_HTTP                                =  5,
352         LWS_CALLBACK_RECEIVE                                    =  6,
353         LWS_CALLBACK_RECEIVE_PONG                               =  7,
354         LWS_CALLBACK_CLIENT_RECEIVE                             =  8,
355         LWS_CALLBACK_CLIENT_RECEIVE_PONG                        =  9,
356         LWS_CALLBACK_CLIENT_WRITEABLE                           = 10,
357         LWS_CALLBACK_SERVER_WRITEABLE                           = 11,
358         LWS_CALLBACK_HTTP                                       = 12,
359         LWS_CALLBACK_HTTP_BODY                                  = 13,
360         LWS_CALLBACK_HTTP_BODY_COMPLETION                       = 14,
361         LWS_CALLBACK_HTTP_FILE_COMPLETION                       = 15,
362         LWS_CALLBACK_HTTP_WRITEABLE                             = 16,
363         LWS_CALLBACK_FILTER_NETWORK_CONNECTION                  = 17,
364         LWS_CALLBACK_FILTER_HTTP_CONNECTION                     = 18,
365         LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED             = 19,
366         LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION                 = 20,
367         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS     = 21,
368         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS     = 22,
369         LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION   = 23,
370         LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER             = 24,
371         LWS_CALLBACK_CONFIRM_EXTENSION_OKAY                     = 25,
372         LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED         = 26,
373         LWS_CALLBACK_PROTOCOL_INIT                              = 27,
374         LWS_CALLBACK_PROTOCOL_DESTROY                           = 28,
375         LWS_CALLBACK_WSI_CREATE /* always protocol[0] */        = 29,
376         LWS_CALLBACK_WSI_DESTROY /* always protocol[0] */       = 30,
377         LWS_CALLBACK_GET_THREAD_ID                              = 31,
378
379         /* external poll() management support */
380         LWS_CALLBACK_ADD_POLL_FD                                = 32,
381         LWS_CALLBACK_DEL_POLL_FD                                = 33,
382         LWS_CALLBACK_CHANGE_MODE_POLL_FD                        = 34,
383         LWS_CALLBACK_LOCK_POLL                                  = 35,
384         LWS_CALLBACK_UNLOCK_POLL                                = 36,
385
386         LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY       = 37,
387         LWS_CALLBACK_WS_PEER_INITIATED_CLOSE                    = 38,
388
389         LWS_CALLBACK_WS_EXT_DEFAULTS                            = 39,
390
391         LWS_CALLBACK_CGI                                        = 40,
392         LWS_CALLBACK_CGI_TERMINATED                             = 41,
393         LWS_CALLBACK_CGI_STDIN_DATA                             = 42,
394         LWS_CALLBACK_CGI_STDIN_COMPLETED                        = 43,
395         LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP                    = 44,
396         LWS_CALLBACK_CLOSED_CLIENT_HTTP                         = 45,
397         LWS_CALLBACK_RECEIVE_CLIENT_HTTP                        = 46,
398         LWS_CALLBACK_COMPLETED_CLIENT_HTTP                      = 47,
399         LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ                   = 48,
400
401         /****** add new things just above ---^ ******/
402
403         LWS_CALLBACK_USER = 1000, /* user code can use any including / above */
404 };
405
406
407 #if defined(_WIN32)
408 typedef SOCKET lws_sockfd_type;
409 typedef HANDLE lws_filefd_type;
410 #define lws_sockfd_valid(sfd) (!!sfd)
411 struct lws_pollfd {
412         lws_sockfd_type fd;
413         SHORT events;
414         SHORT revents;
415 };
416 #else
417
418 #if defined(MBED_OPERATORS)
419 /* it's a class lws_conn * */
420 typedef void * lws_sockfd_type;
421 typedef void * lws_filefd_type;
422 #define lws_sockfd_valid(sfd) (!!sfd)
423 struct pollfd {
424         lws_sockfd_type fd;
425         short events;
426         short revents;
427 };
428 #define POLLIN          0x0001
429 #define POLLPRI         0x0002
430 #define POLLOUT         0x0004
431 #define POLLERR         0x0008
432 #define POLLHUP         0x0010
433 #define POLLNVAL        0x0020
434
435 struct lws;
436
437 void * mbed3_create_tcp_stream_socket(void);
438 void mbed3_delete_tcp_stream_socket(void *sockfd);
439 void mbed3_tcp_stream_bind(void *sock, int port, struct lws *);
440 void mbed3_tcp_stream_accept(void *sock, struct lws *);
441 #else
442 typedef int lws_sockfd_type;
443 typedef int lws_filefd_type;
444 #define lws_sockfd_valid(sfd) (sfd >= 0)
445 #endif
446
447 #define lws_pollfd pollfd
448 #endif
449
450 /* argument structure for all external poll related calls
451  * passed in via 'in'
452  */
453 struct lws_pollargs {
454         lws_sockfd_type fd;             /* applicable socket descriptor */
455         int events;                     /* the new event mask */
456         int prev_events;                /* the previous event mask */
457 };
458
459 /**
460  * struct lws_plat_file_ops - Platform-specific file operations
461  *
462  * These provide platform-agnostic ways to deal with filesystem access in the
463  * library and in the user code.
464  *
465  * @open:               Open file (always binary access if plat supports it)
466  *                       filelen is filled on exit to be the length of the file
467  *                       flags should be set to O_RDONLY or O_RDWR
468  * @close:              Close file
469  * @seek_cur:           Seek from current position
470  * @read:               Read fron file *amount is set on exit to amount read
471  * @write:              Write to file *amount is set on exit as amount written
472  */
473 struct lws_plat_file_ops {
474         lws_filefd_type (*open)(struct lws *wsi, const char *filename,
475                                 unsigned long *filelen, int flags);
476         int (*close)(struct lws *wsi, lws_filefd_type fd);
477         unsigned long (*seek_cur)(struct lws *wsi, lws_filefd_type fd,
478                                   long offset_from_cur_pos);
479         int (*read)(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
480                     unsigned char *buf, unsigned long len);
481         int (*write)(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
482                      unsigned char *buf, unsigned long len);
483
484         /* Add new things just above here ---^
485          * This is part of the ABI, don't needlessly break compatibility */
486 };
487
488 /*
489  * NOTE: These public enums are part of the abi.  If you want to add one,
490  * add it at where specified so existing users are unaffected.
491  */
492 enum lws_extension_callback_reasons {
493         LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT             =  0,
494         LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT             =  1,
495         LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT              =  2,
496         LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT              =  3,
497         LWS_EXT_CB_CONSTRUCT                            =  4,
498         LWS_EXT_CB_CLIENT_CONSTRUCT                     =  5,
499         LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE             =  6,
500         LWS_EXT_CB_CHECK_OK_TO_PROPOSE_EXTENSION        =  7,
501         LWS_EXT_CB_DESTROY                              =  8,
502         LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING              =  9,
503         LWS_EXT_CB_ANY_WSI_ESTABLISHED                  = 10,
504         LWS_EXT_CB_PACKET_RX_PREPARSE                   = 11,
505         LWS_EXT_CB_PACKET_TX_PRESEND                    = 12,
506         LWS_EXT_CB_PACKET_TX_DO_SEND                    = 13,
507         LWS_EXT_CB_HANDSHAKE_REPLY_TX                   = 14,
508         LWS_EXT_CB_FLUSH_PENDING_TX                     = 15,
509         LWS_EXT_CB_EXTENDED_PAYLOAD_RX                  = 16,
510         LWS_EXT_CB_CAN_PROXY_CLIENT_CONNECTION          = 17,
511         LWS_EXT_CB_1HZ                                  = 18,
512         LWS_EXT_CB_REQUEST_ON_WRITEABLE                 = 19,
513         LWS_EXT_CB_IS_WRITEABLE                         = 20,
514         LWS_EXT_CB_PAYLOAD_TX                           = 21,
515         LWS_EXT_CB_PAYLOAD_RX                           = 22,
516         LWS_EXT_CB_OPTION_DEFAULT                       = 23,
517         LWS_EXT_CB_OPTION_SET                           = 24,
518         LWS_EXT_CB_OPTION_CONFIRM                       = 25,
519         LWS_EXT_CB_NAMED_OPTION_SET                     = 26,
520
521         /****** add new things just above ---^ ******/
522 };
523
524 /*
525  * NOTE: These public enums are part of the abi.  If you want to add one,
526  * add it at where specified so existing users are unaffected.
527  */
528 enum lws_write_protocol {
529         LWS_WRITE_TEXT                                          = 0,
530         LWS_WRITE_BINARY                                        = 1,
531         LWS_WRITE_CONTINUATION                                  = 2,
532         LWS_WRITE_HTTP                                          = 3,
533
534         /* special 04+ opcodes */
535
536         /* LWS_WRITE_CLOSE is handled by lws_close_reason() */
537         LWS_WRITE_PING                                          = 5,
538         LWS_WRITE_PONG                                          = 6,
539
540         /* Same as write_http but we know this write ends the transaction */
541         LWS_WRITE_HTTP_FINAL                                    = 7,
542
543         /* HTTP2 */
544
545         LWS_WRITE_HTTP_HEADERS                                  = 8,
546
547         /****** add new things just above ---^ ******/
548
549         /* flags */
550
551         LWS_WRITE_NO_FIN = 0x40,
552         /*
553          * client packet payload goes out on wire unmunged
554          * only useful for security tests since normal servers cannot
555          * decode the content if used
556          */
557         LWS_WRITE_CLIENT_IGNORE_XOR_MASK = 0x80
558 };
559
560 /*
561  * you need these to look at headers that have been parsed if using the
562  * LWS_CALLBACK_FILTER_CONNECTION callback.  If a header from the enum
563  * list below is absent, .token = NULL and token_len = 0.  Otherwise .token
564  * points to .token_len chars containing that header content.
565  */
566
567 struct lws_tokens {
568         char *token;
569         int token_len;
570 };
571
572 /*
573  * these have to be kept in sync with lextable.h / minilex.c
574  *
575  * NOTE: These public enums are part of the abi.  If you want to add one,
576  * add it at where specified so existing users are unaffected.
577  */
578 enum lws_token_indexes {
579         WSI_TOKEN_GET_URI                                       =  0,
580         WSI_TOKEN_POST_URI                                      =  1,
581         WSI_TOKEN_OPTIONS_URI                                   =  2,
582         WSI_TOKEN_HOST                                          =  3,
583         WSI_TOKEN_CONNECTION                                    =  4,
584         WSI_TOKEN_UPGRADE                                       =  5,
585         WSI_TOKEN_ORIGIN                                        =  6,
586         WSI_TOKEN_DRAFT                                         =  7,
587         WSI_TOKEN_CHALLENGE                                     =  8,
588         WSI_TOKEN_EXTENSIONS                                    =  9,
589         WSI_TOKEN_KEY1                                          = 10,
590         WSI_TOKEN_KEY2                                          = 11,
591         WSI_TOKEN_PROTOCOL                                      = 12,
592         WSI_TOKEN_ACCEPT                                        = 13,
593         WSI_TOKEN_NONCE                                         = 14,
594         WSI_TOKEN_HTTP                                          = 15,
595         WSI_TOKEN_HTTP2_SETTINGS                                = 16,
596         WSI_TOKEN_HTTP_ACCEPT                                   = 17,
597         WSI_TOKEN_HTTP_AC_REQUEST_HEADERS                       = 18,
598         WSI_TOKEN_HTTP_IF_MODIFIED_SINCE                        = 19,
599         WSI_TOKEN_HTTP_IF_NONE_MATCH                            = 20,
600         WSI_TOKEN_HTTP_ACCEPT_ENCODING                          = 21,
601         WSI_TOKEN_HTTP_ACCEPT_LANGUAGE                          = 22,
602         WSI_TOKEN_HTTP_PRAGMA                                   = 23,
603         WSI_TOKEN_HTTP_CACHE_CONTROL                            = 24,
604         WSI_TOKEN_HTTP_AUTHORIZATION                            = 25,
605         WSI_TOKEN_HTTP_COOKIE                                   = 26,
606         WSI_TOKEN_HTTP_CONTENT_LENGTH                           = 27,
607         WSI_TOKEN_HTTP_CONTENT_TYPE                             = 28,
608         WSI_TOKEN_HTTP_DATE                                     = 29,
609         WSI_TOKEN_HTTP_RANGE                                    = 30,
610         WSI_TOKEN_HTTP_REFERER                                  = 31,
611         WSI_TOKEN_KEY                                           = 32,
612         WSI_TOKEN_VERSION                                       = 33,
613         WSI_TOKEN_SWORIGIN                                      = 34,
614
615         WSI_TOKEN_HTTP_COLON_AUTHORITY                          = 35,
616         WSI_TOKEN_HTTP_COLON_METHOD                             = 36,
617         WSI_TOKEN_HTTP_COLON_PATH                               = 37,
618         WSI_TOKEN_HTTP_COLON_SCHEME                             = 38,
619         WSI_TOKEN_HTTP_COLON_STATUS                             = 39,
620
621         WSI_TOKEN_HTTP_ACCEPT_CHARSET                           = 40,
622         WSI_TOKEN_HTTP_ACCEPT_RANGES                            = 41,
623         WSI_TOKEN_HTTP_ACCESS_CONTROL_ALLOW_ORIGIN              = 42,
624         WSI_TOKEN_HTTP_AGE                                      = 43,
625         WSI_TOKEN_HTTP_ALLOW                                    = 44,
626         WSI_TOKEN_HTTP_CONTENT_DISPOSITION                      = 45,
627         WSI_TOKEN_HTTP_CONTENT_ENCODING                         = 46,
628         WSI_TOKEN_HTTP_CONTENT_LANGUAGE                         = 47,
629         WSI_TOKEN_HTTP_CONTENT_LOCATION                         = 48,
630         WSI_TOKEN_HTTP_CONTENT_RANGE                            = 49,
631         WSI_TOKEN_HTTP_ETAG                                     = 50,
632         WSI_TOKEN_HTTP_EXPECT                                   = 51,
633         WSI_TOKEN_HTTP_EXPIRES                                  = 52,
634         WSI_TOKEN_HTTP_FROM                                     = 53,
635         WSI_TOKEN_HTTP_IF_MATCH                                 = 54,
636         WSI_TOKEN_HTTP_IF_RANGE                                 = 55,
637         WSI_TOKEN_HTTP_IF_UNMODIFIED_SINCE                      = 56,
638         WSI_TOKEN_HTTP_LAST_MODIFIED                            = 57,
639         WSI_TOKEN_HTTP_LINK                                     = 58,
640         WSI_TOKEN_HTTP_LOCATION                                 = 59,
641         WSI_TOKEN_HTTP_MAX_FORWARDS                             = 60,
642         WSI_TOKEN_HTTP_PROXY_AUTHENTICATE                       = 61,
643         WSI_TOKEN_HTTP_PROXY_AUTHORIZATION                      = 62,
644         WSI_TOKEN_HTTP_REFRESH                                  = 63,
645         WSI_TOKEN_HTTP_RETRY_AFTER                              = 64,
646         WSI_TOKEN_HTTP_SERVER                                   = 65,
647         WSI_TOKEN_HTTP_SET_COOKIE                               = 66,
648         WSI_TOKEN_HTTP_STRICT_TRANSPORT_SECURITY                = 67,
649         WSI_TOKEN_HTTP_TRANSFER_ENCODING                        = 68,
650         WSI_TOKEN_HTTP_USER_AGENT                               = 69,
651         WSI_TOKEN_HTTP_VARY                                     = 70,
652         WSI_TOKEN_HTTP_VIA                                      = 71,
653         WSI_TOKEN_HTTP_WWW_AUTHENTICATE                         = 72,
654
655         WSI_TOKEN_PATCH_URI                                     = 73,
656         WSI_TOKEN_PUT_URI                                       = 74,
657         WSI_TOKEN_DELETE_URI                                    = 75,
658
659         WSI_TOKEN_HTTP_URI_ARGS                                 = 76,
660         WSI_TOKEN_PROXY                                         = 77,
661         WSI_TOKEN_HTTP_X_REAL_IP                                = 78,
662         WSI_TOKEN_HTTP1_0                                       = 79,
663
664         /****** add new things just above ---^ ******/
665
666         /* use token storage to stash these internally, not for
667          * user use */
668
669         _WSI_TOKEN_CLIENT_SENT_PROTOCOLS,
670         _WSI_TOKEN_CLIENT_PEER_ADDRESS,
671         _WSI_TOKEN_CLIENT_URI,
672         _WSI_TOKEN_CLIENT_HOST,
673         _WSI_TOKEN_CLIENT_ORIGIN,
674         _WSI_TOKEN_CLIENT_METHOD,
675
676         /* always last real token index*/
677         WSI_TOKEN_COUNT,
678
679         /* parser state additions, no storage associated */
680         WSI_TOKEN_NAME_PART,
681         WSI_TOKEN_SKIPPING,
682         WSI_TOKEN_SKIPPING_SAW_CR,
683         WSI_PARSING_COMPLETE,
684         WSI_INIT_TOKEN_MUXURL,
685 };
686
687 struct lws_token_limits {
688         unsigned short token_limit[WSI_TOKEN_COUNT];
689 };
690
691 /*
692  * From RFC 6455
693    1000
694
695       1000 indicates a normal closure, meaning that the purpose for
696       which the connection was established has been fulfilled.
697
698    1001
699
700       1001 indicates that an endpoint is "going away", such as a server
701       going down or a browser having navigated away from a page.
702
703    1002
704
705       1002 indicates that an endpoint is terminating the connection due
706       to a protocol error.
707
708    1003
709
710       1003 indicates that an endpoint is terminating the connection
711       because it has received a type of data it cannot accept (e.g., an
712       endpoint that understands only text data MAY send this if it
713       receives a binary message).
714
715    1004
716
717       Reserved.  The specific meaning might be defined in the future.
718
719    1005
720
721       1005 is a reserved value and MUST NOT be set as a status code in a
722       Close control frame by an endpoint.  It is designated for use in
723       applications expecting a status code to indicate that no status
724       code was actually present.
725
726    1006
727
728       1006 is a reserved value and MUST NOT be set as a status code in a
729       Close control frame by an endpoint.  It is designated for use in
730       applications expecting a status code to indicate that the
731       connection was closed abnormally, e.g., without sending or
732       receiving a Close control frame.
733
734    1007
735
736       1007 indicates that an endpoint is terminating the connection
737       because it has received data within a message that was not
738       consistent with the type of the message (e.g., non-UTF-8 [RFC3629]
739       data within a text message).
740
741    1008
742
743       1008 indicates that an endpoint is terminating the connection
744       because it has received a message that violates its policy.  This
745       is a generic status code that can be returned when there is no
746       other more suitable status code (e.g., 1003 or 1009) or if there
747       is a need to hide specific details about the policy.
748
749    1009
750
751       1009 indicates that an endpoint is terminating the connection
752       because it has received a message that is too big for it to
753       process.
754
755    1010
756
757       1010 indicates that an endpoint (client) is terminating the
758       connection because it has expected the server to negotiate one or
759       more extension, but the server didn't return them in the response
760       message of the WebSocket handshake.  The list of extensions that
761       are needed SHOULD appear in the /reason/ part of the Close frame.
762       Note that this status code is not used by the server, because it
763       can fail the WebSocket handshake instead.
764
765    1011
766
767       1011 indicates that a server is terminating the connection because
768       it encountered an unexpected condition that prevented it from
769       fulfilling the request.
770
771    1015
772
773       1015 is a reserved value and MUST NOT be set as a status code in a
774       Close control frame by an endpoint.  It is designated for use in
775       applications expecting a status code to indicate that the
776       connection was closed due to a failure to perform a TLS handshake
777       (e.g., the server certificate can't be verified).
778 */
779
780 /*
781  * NOTE: These public enums are part of the abi.  If you want to add one,
782  * add it at where specified so existing users are unaffected.
783  */
784 enum lws_close_status {
785         LWS_CLOSE_STATUS_NOSTATUS                               =    0,
786         LWS_CLOSE_STATUS_NORMAL                                 = 1000,
787         LWS_CLOSE_STATUS_GOINGAWAY                              = 1001,
788         LWS_CLOSE_STATUS_PROTOCOL_ERR                           = 1002,
789         LWS_CLOSE_STATUS_UNACCEPTABLE_OPCODE                    = 1003,
790         LWS_CLOSE_STATUS_RESERVED                               = 1004,
791         LWS_CLOSE_STATUS_NO_STATUS                              = 1005,
792         LWS_CLOSE_STATUS_ABNORMAL_CLOSE                         = 1006,
793         LWS_CLOSE_STATUS_INVALID_PAYLOAD                        = 1007,
794         LWS_CLOSE_STATUS_POLICY_VIOLATION                       = 1008,
795         LWS_CLOSE_STATUS_MESSAGE_TOO_LARGE                      = 1009,
796         LWS_CLOSE_STATUS_EXTENSION_REQUIRED                     = 1010,
797         LWS_CLOSE_STATUS_UNEXPECTED_CONDITION                   = 1011,
798         LWS_CLOSE_STATUS_TLS_FAILURE                            = 1015,
799
800         /****** add new things just above ---^ ******/
801
802         LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY               = 9999,
803 };
804
805 enum http_status {
806         HTTP_STATUS_OK                                          = 200,
807         HTTP_STATUS_NO_CONTENT                                  = 204,
808
809         HTTP_STATUS_BAD_REQUEST                                 = 400,
810         HTTP_STATUS_UNAUTHORIZED,
811         HTTP_STATUS_PAYMENT_REQUIRED,
812         HTTP_STATUS_FORBIDDEN,
813         HTTP_STATUS_NOT_FOUND,
814         HTTP_STATUS_METHOD_NOT_ALLOWED,
815         HTTP_STATUS_NOT_ACCEPTABLE,
816         HTTP_STATUS_PROXY_AUTH_REQUIRED,
817         HTTP_STATUS_REQUEST_TIMEOUT,
818         HTTP_STATUS_CONFLICT,
819         HTTP_STATUS_GONE,
820         HTTP_STATUS_LENGTH_REQUIRED,
821         HTTP_STATUS_PRECONDITION_FAILED,
822         HTTP_STATUS_REQ_ENTITY_TOO_LARGE,
823         HTTP_STATUS_REQ_URI_TOO_LONG,
824         HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE,
825         HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE,
826         HTTP_STATUS_EXPECTATION_FAILED,
827
828         HTTP_STATUS_INTERNAL_SERVER_ERROR                       = 500,
829         HTTP_STATUS_NOT_IMPLEMENTED,
830         HTTP_STATUS_BAD_GATEWAY,
831         HTTP_STATUS_SERVICE_UNAVAILABLE,
832         HTTP_STATUS_GATEWAY_TIMEOUT,
833         HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED,
834 };
835
836 struct lws;
837 struct lws_context;
838 /* needed even with extensions disabled for create context */
839 struct lws_extension;
840
841 /**
842  * typedef lws_callback_function() - User server actions
843  * @wsi:        Opaque websocket instance pointer
844  * @reason:     The reason for the call
845  * @user:       Pointer to per-session user data allocated by library
846  * @in:         Pointer used for some callback reasons
847  * @len:        Length set for some callback reasons
848  *
849  *      This callback is the way the user controls what is served.  All the
850  *      protocol detail is hidden and handled by the library.
851  *
852  *      For each connection / session there is user data allocated that is
853  *      pointed to by "user".  You set the size of this user data area when
854  *      the library is initialized with lws_create_server.
855  *
856  *      You get an opportunity to initialize user data when called back with
857  *      LWS_CALLBACK_ESTABLISHED reason.
858  *
859  *  LWS_CALLBACK_ESTABLISHED:  after the server completes a handshake with
860  *                              an incoming client.  If you built the library
861  *                              with ssl support, @in is a pointer to the
862  *                              ssl struct associated with the connection or
863  *                              NULL.
864  *
865  *  LWS_CALLBACK_CLIENT_CONNECTION_ERROR: the request client connection has
866  *        been unable to complete a handshake with the remote server.  If
867  *        in is non-NULL, you can find an error string of length len where
868  *        it points to.
869  *
870  *  LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH: this is the last chance for the
871  *                              client user code to examine the http headers
872  *                              and decide to reject the connection.  If the
873  *                              content in the headers is interesting to the
874  *                              client (url, etc) it needs to copy it out at
875  *                              this point since it will be destroyed before
876  *                              the CLIENT_ESTABLISHED call
877  *
878  *  LWS_CALLBACK_CLIENT_ESTABLISHED: after your client connection completed
879  *                              a handshake with the remote server
880  *
881  *      LWS_CALLBACK_CLOSED: when the websocket session ends
882  *
883  *      LWS_CALLBACK_CLOSED_HTTP: when a HTTP (non-websocket) session ends
884  *
885  *      LWS_CALLBACK_RECEIVE: data has appeared for this server endpoint from a
886  *                              remote client, it can be found at *in and is
887  *                              len bytes long
888  *
889  *      LWS_CALLBACK_CLIENT_RECEIVE_PONG: if you elected to see PONG packets,
890  *                              they appear with this callback reason.  PONG
891  *                              packets only exist in 04+ protocol
892  *
893  *      LWS_CALLBACK_CLIENT_RECEIVE: data has appeared from the server for the
894  *                              client connection, it can be found at *in and
895  *                              is len bytes long
896  *
897  *      LWS_CALLBACK_HTTP: an http request has come from a client that is not
898  *                              asking to upgrade the connection to a websocket
899  *                              one.  This is a chance to serve http content,
900  *                              for example, to send a script to the client
901  *                              which will then open the websockets connection.
902  *                              @in points to the URI path requested and
903  *                              lws_serve_http_file() makes it very
904  *                              simple to send back a file to the client.
905  *                              Normally after sending the file you are done
906  *                              with the http connection, since the rest of the
907  *                              activity will come by websockets from the script
908  *                              that was delivered by http, so you will want to
909  *                              return 1; to close and free up the connection.
910  *                              That's important because it uses a slot in the
911  *                              total number of client connections allowed set
912  *                              by MAX_CLIENTS.
913  *
914  *      LWS_CALLBACK_HTTP_BODY: the next @len bytes data from the http
915  *              request body HTTP connection is now available in @in.
916  *
917  *      LWS_CALLBACK_HTTP_BODY_COMPLETION: the expected amount of http request
918  *              body has been delivered
919  *
920  *      LWS_CALLBACK_HTTP_WRITEABLE: you can write more down the http protocol
921  *              link now.
922  *
923  *      LWS_CALLBACK_HTTP_FILE_COMPLETION: a file requested to be send down
924  *                              http link has completed.
925  *
926  *      LWS_CALLBACK_CLIENT_WRITEABLE:
927  *      LWS_CALLBACK_SERVER_WRITEABLE:   If you call
928  *              lws_callback_on_writable() on a connection, you will
929  *              get one of these callbacks coming when the connection socket
930  *              is able to accept another write packet without blocking.
931  *              If it already was able to take another packet without blocking,
932  *              you'll get this callback at the next call to the service loop
933  *              function.  Notice that CLIENTs get LWS_CALLBACK_CLIENT_WRITEABLE
934  *              and servers get LWS_CALLBACK_SERVER_WRITEABLE.
935  *
936  *      LWS_CALLBACK_FILTER_NETWORK_CONNECTION: called when a client connects to
937  *              the server at network level; the connection is accepted but then
938  *              passed to this callback to decide whether to hang up immediately
939  *              or not, based on the client IP.  @in contains the connection
940  *              socket's descriptor. Since the client connection information is
941  *              not available yet, @wsi still pointing to the main server socket.
942  *              Return non-zero to terminate the connection before sending or
943  *              receiving anything. Because this happens immediately after the
944  *              network connection from the client, there's no websocket protocol
945  *              selected yet so this callback is issued only to protocol 0.
946  *
947  *      LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED: A new client just had
948  *              been connected, accepted, and instantiated into the pool. This
949  *              callback allows setting any relevant property to it. Because this
950  *              happens immediately after the instantiation of a new client,
951  *              there's no websocket protocol selected yet so this callback is
952  *              issued only to protocol 0. Only @wsi is defined, pointing to the
953  *              new client, and the return value is ignored.
954  *
955  *      LWS_CALLBACK_FILTER_HTTP_CONNECTION: called when the request has
956  *              been received and parsed from the client, but the response is
957  *              not sent yet.  Return non-zero to disallow the connection.
958  *              @user is a pointer to the connection user space allocation,
959  *              @in is the URI, eg, "/"
960  *              In your handler you can use the public APIs
961  *              lws_hdr_total_length() / lws_hdr_copy() to access all of the
962  *              headers using the header enums lws_token_indexes from
963  *              libwebsockets.h to check for and read the supported header
964  *              presence and content before deciding to allow the http
965  *              connection to proceed or to kill the connection.
966  *
967  *      LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION: called when the handshake has
968  *              been received and parsed from the client, but the response is
969  *              not sent yet.  Return non-zero to disallow the connection.
970  *              @user is a pointer to the connection user space allocation,
971  *              @in is the requested protocol name
972  *              In your handler you can use the public APIs
973  *              lws_hdr_total_length() / lws_hdr_copy() to access all of the
974  *              headers using the header enums lws_token_indexes from
975  *              libwebsockets.h to check for and read the supported header
976  *              presence and content before deciding to allow the handshake
977  *              to proceed or to kill the connection.
978  *
979  *      LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS: if configured for
980  *              including OpenSSL support, this callback allows your user code
981  *              to perform extra SSL_CTX_load_verify_locations() or similar
982  *              calls to direct OpenSSL where to find certificates the client
983  *              can use to confirm the remote server identity.  @user is the
984  *              OpenSSL SSL_CTX*
985  *
986  *      LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS: if configured for
987  *              including OpenSSL support, this callback allows your user code
988  *              to load extra certifcates into the server which allow it to
989  *              verify the validity of certificates returned by clients.  @user
990  *              is the server's OpenSSL SSL_CTX*
991  *
992  *      LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY: if configured for
993  *              including OpenSSL support but no private key file has been
994  *              specified (ssl_private_key_filepath is NULL), this is called to
995  *              allow the user to set the private key directly via libopenssl
996  *              and perform further operations if required; this might be useful
997  *              in situations where the private key is not directly accessible
998  *              by the OS, for example if it is stored on a smartcard
999  *              @user is the server's OpenSSL SSL_CTX*
1000  *
1001  *      LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION: if the
1002  *              libwebsockets context was created with the option
1003  *              LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT, then this
1004  *              callback is generated during OpenSSL verification of the cert
1005  *              sent from the client.  It is sent to protocol[0] callback as
1006  *              no protocol has been negotiated on the connection yet.
1007  *              Notice that the libwebsockets context and wsi are both NULL
1008  *              during this callback.  See
1009  *               http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html
1010  *              to understand more detail about the OpenSSL callback that
1011  *              generates this libwebsockets callback and the meanings of the
1012  *              arguments passed.  In this callback, @user is the x509_ctx,
1013  *              @in is the ssl pointer and @len is preverify_ok
1014  *              Notice that this callback maintains libwebsocket return
1015  *              conventions, return 0 to mean the cert is OK or 1 to fail it.
1016  *              This also means that if you don't handle this callback then
1017  *              the default callback action of returning 0 allows the client
1018  *              certificates.
1019  *
1020  *      LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER: this callback happens
1021  *              when a client handshake is being compiled.  @user is NULL,
1022  *              @in is a char **, it's pointing to a char * which holds the
1023  *              next location in the header buffer where you can add
1024  *              headers, and @len is the remaining space in the header buffer,
1025  *              which is typically some hundreds of bytes.  So, to add a canned
1026  *              cookie, your handler code might look similar to:
1027  *
1028  *              char **p = (char **)in;
1029  *
1030  *              if (len < 100)
1031  *                      return 1;
1032  *
1033  *              *p += sprintf(*p, "Cookie: a=b\x0d\x0a");
1034  *
1035  *              return 0;
1036  *
1037  *              Notice if you add anything, you just have to take care about
1038  *              the CRLF on the line you added.  Obviously this callback is
1039  *              optional, if you don't handle it everything is fine.
1040  *
1041  *              Notice the callback is coming to protocols[0] all the time,
1042  *              because there is no specific protocol handshook yet.
1043  *
1044  *      LWS_CALLBACK_CONFIRM_EXTENSION_OKAY: When the server handshake code
1045  *              sees that it does support a requested extension, before
1046  *              accepting the extension by additing to the list sent back to
1047  *              the client it gives this callback just to check that it's okay
1048  *              to use that extension.  It calls back to the requested protocol
1049  *              and with @in being the extension name, @len is 0 and @user is
1050  *              valid.  Note though at this time the ESTABLISHED callback hasn't
1051  *              happened yet so if you initialize @user content there, @user
1052  *              content during this callback might not be useful for anything.
1053  *              Notice this callback comes to protocols[0].
1054  *
1055  *      LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED:        When a client
1056  *              connection is being prepared to start a handshake to a server,
1057  *              each supported extension is checked with protocols[0] callback
1058  *              with this reason, giving the user code a chance to suppress the
1059  *              claim to support that extension by returning non-zero.  If
1060  *              unhandled, by default 0 will be returned and the extension
1061  *              support included in the header to the server.  Notice this
1062  *              callback comes to protocols[0].
1063  *
1064  *      LWS_CALLBACK_PROTOCOL_INIT:     One-time call per protocol so it can
1065  *              do initial setup / allocations etc
1066  *
1067  *      LWS_CALLBACK_PROTOCOL_DESTROY:  One-time call per protocol indicating
1068  *              this protocol won't get used at all after this callback, the
1069  *              context is getting destroyed.  Take the opportunity to
1070  *              deallocate everything that was allocated by the protocol.
1071  *
1072  *      LWS_CALLBACK_WSI_CREATE: outermost (earliest) wsi create notification
1073  *
1074  *      LWS_CALLBACK_WSI_DESTROY: outermost (latest) wsi destroy notification
1075  *
1076  *      The next five reasons are optional and only need taking care of if you
1077  *      will be integrating libwebsockets sockets into an external polling
1078  *      array.
1079  *
1080  *      For these calls, @in points to a struct lws_pollargs that
1081  *      contains @fd, @events and @prev_events members
1082  *
1083  *      LWS_CALLBACK_ADD_POLL_FD: libwebsocket deals with its poll() loop
1084  *              internally, but in the case you are integrating with another
1085  *              server you will need to have libwebsocket sockets share a
1086  *              polling array with the other server.  This and the other
1087  *              POLL_FD related callbacks let you put your specialized
1088  *              poll array interface code in the callback for protocol 0, the
1089  *              first protocol you support, usually the HTTP protocol in the
1090  *              serving case.
1091  *              This callback happens when a socket needs to be
1092  *              added to the polling loop: @in points to a struct
1093  *              lws_pollargs; the @fd member of the struct is the file
1094  *              descriptor, and @events contains the active events.
1095  *
1096  *              If you are using the internal polling loop (the "service"
1097  *              callback), you can just ignore these callbacks.
1098  *
1099  *      LWS_CALLBACK_DEL_POLL_FD: This callback happens when a socket descriptor
1100  *              needs to be removed from an external polling array.  @in is
1101  *              again the struct lws_pollargs containing the @fd member
1102  *              to be removed.  If you are using the internal polling
1103  *              loop, you can just ignore it.
1104  *
1105  *      LWS_CALLBACK_CHANGE_MODE_POLL_FD: This callback happens when
1106  *              libwebsockets wants to modify the events for a connectiion.
1107  *              @in is the struct lws_pollargs with the @fd to change.
1108  *              The new event mask is in @events member and the old mask is in
1109  *              the @prev_events member.
1110  *              If you are using the internal polling loop, you can just ignore
1111  *              it.
1112  *
1113  *      LWS_CALLBACK_LOCK_POLL:
1114  *      LWS_CALLBACK_UNLOCK_POLL: These allow the external poll changes driven
1115  *              by libwebsockets to participate in an external thread locking
1116  *              scheme around the changes, so the whole thing is threadsafe.
1117  *              These are called around three activities in the library,
1118  *                      - inserting a new wsi in the wsi / fd table (len=1)
1119  *                      - deleting a wsi from the wsi / fd table (len=1)
1120  *                      - changing a wsi's POLLIN/OUT state (len=0)
1121  *              Locking and unlocking external synchronization objects when
1122  *              len == 1 allows external threads to be synchronized against
1123  *              wsi lifecycle changes if it acquires the same lock for the
1124  *              duration of wsi dereference from the other thread context.
1125  *
1126  *      LWS_CALLBACK_WS_PEER_INITIATED_CLOSE:
1127  *              The peer has sent an unsolicited Close WS packet.  @in and
1128  *              @len are the optional close code (first 2 bytes, network
1129  *              order) and the optional additional information which is not
1130  *              defined in the standard, and may be a string or non-human-
1131  *              readble data.
1132  *              If you return 0 lws will echo the close and then close the
1133  *              connection.  If you return nonzero lws will just close the
1134  *              connection.
1135  */
1136 typedef int
1137 lws_callback_function(struct lws *wsi, enum lws_callback_reasons reason,
1138                     void *user, void *in, size_t len);
1139
1140 /**
1141  * typedef lws_extension_callback_function() - Hooks to allow extensions to operate
1142  * @context:    Websockets context
1143  * @ext:        This extension
1144  * @wsi:        Opaque websocket instance pointer
1145  * @reason:     The reason for the call
1146  * @user:       Pointer to ptr to per-session user data allocated by library
1147  * @in:         Pointer used for some callback reasons
1148  * @len:        Length set for some callback reasons
1149  *
1150  *      Each extension that is active on a particular connection receives
1151  *      callbacks during the connection lifetime to allow the extension to
1152  *      operate on websocket data and manage itself.
1153  *
1154  *      Libwebsockets takes care of allocating and freeing "user" memory for
1155  *      each active extension on each connection.  That is what is pointed to
1156  *      by the @user parameter.
1157  *
1158  *      LWS_EXT_CB_CONSTRUCT:  called when the server has decided to
1159  *              select this extension from the list provided by the client,
1160  *              just before the server will send back the handshake accepting
1161  *              the connection with this extension active.  This gives the
1162  *              extension a chance to initialize its connection context found
1163  *              in @user.
1164  *
1165  *      LWS_EXT_CB_CLIENT_CONSTRUCT: same as LWS_EXT_CB_CONSTRUCT
1166  *              but called when client is instantiating this extension.  Some
1167  *              extensions will work the same on client and server side and then
1168  *              you can just merge handlers for both CONSTRUCTS.
1169  *
1170  *      LWS_EXT_CB_DESTROY:  called when the connection the extension was
1171  *              being used on is about to be closed and deallocated.  It's the
1172  *              last chance for the extension to deallocate anything it has
1173  *              allocated in the user data (pointed to by @user) before the
1174  *              user data is deleted.  This same callback is used whether you
1175  *              are in client or server instantiation context.
1176  *
1177  *      LWS_EXT_CB_PACKET_RX_PREPARSE: when this extension was active on
1178  *              a connection, and a packet of data arrived at the connection,
1179  *              it is passed to this callback to give the extension a chance to
1180  *              change the data, eg, decompress it.  @user is pointing to the
1181  *              extension's private connection context data, @in is pointing
1182  *              to an lws_tokens struct, it consists of a char * pointer called
1183  *              token, and an int called token_len.  At entry, these are
1184  *              set to point to the received buffer and set to the content
1185  *              length.  If the extension will grow the content, it should use
1186  *              a new buffer allocated in its private user context data and
1187  *              set the pointed-to lws_tokens members to point to its buffer.
1188  *
1189  *      LWS_EXT_CB_PACKET_TX_PRESEND: this works the same way as
1190  *              LWS_EXT_CB_PACKET_RX_PREPARSE above, except it gives the
1191  *              extension a chance to change websocket data just before it will
1192  *              be sent out.  Using the same lws_token pointer scheme in @in,
1193  *              the extension can change the buffer and the length to be
1194  *              transmitted how it likes.  Again if it wants to grow the
1195  *              buffer safely, it should copy the data into its own buffer and
1196  *              set the lws_tokens token pointer to it.
1197  *
1198  *      LWS_EXT_CB_ARGS_VALIDATE:
1199  */
1200 typedef int
1201 lws_extension_callback_function(struct lws_context *context,
1202                               const struct lws_extension *ext, struct lws *wsi,
1203                               enum lws_extension_callback_reasons reason,
1204                               void *user, void *in, size_t len);
1205
1206 /**
1207  * struct lws_protocols -       List of protocols and handlers server
1208  *                                      supports.
1209  * @name:       Protocol name that must match the one given in the client
1210  *              Javascript new WebSocket(url, 'protocol') name.
1211  * @callback:   The service callback used for this protocol.  It allows the
1212  *              service action for an entire protocol to be encapsulated in
1213  *              the protocol-specific callback
1214  * @per_session_data_size:      Each new connection using this protocol gets
1215  *              this much memory allocated on connection establishment and
1216  *              freed on connection takedown.  A pointer to this per-connection
1217  *              allocation is passed into the callback in the 'user' parameter
1218  * @rx_buffer_size: if you want atomic frames delivered to the callback, you
1219  *              should set this to the size of the biggest legal frame that
1220  *              you support.  If the frame size is exceeded, there is no
1221  *              error, but the buffer will spill to the user callback when
1222  *              full, which you can detect by using
1223  *              lws_remaining_packet_payload().  Notice that you
1224  *              just talk about frame size here, the LWS_PRE
1225  *              and post-padding are automatically also allocated on top.
1226  * @id:         ignored by lws, but useful to contain user information bound
1227  *              to the selected protocol.  For example if this protocol was
1228  *              called "myprotocol-v2", you might set id to 2, and the user
1229  *              code that acts differently according to the version can do so by
1230  *              switch (wsi->protocol->id), user code might use some bits as
1231  *              capability flags based on selected protocol version, etc.
1232  * @user:       User provided context data at the protocol level.
1233  *              Accessible via lws_get_protocol(wsi)->user
1234  *              This should not be confused with wsi->user, it is not the same.
1235  *              The library completely ignores any value in here.
1236  *
1237  *      This structure represents one protocol supported by the server.  An
1238  *      array of these structures is passed to lws_create_server()
1239  *      allows as many protocols as you like to be handled by one server.
1240  *
1241  *      The first protocol given has its callback used for user callbacks when
1242  *      there is no agreed protocol name, that's true during HTTP part of the
1243  *      connection and true if the client did not send a Protocol: header.
1244  */
1245
1246 struct lws_protocols {
1247         const char *name;
1248         lws_callback_function *callback;
1249         size_t per_session_data_size;
1250         size_t rx_buffer_size;
1251         unsigned int id;
1252         void *user;
1253
1254         /* Add new things just above here ---^
1255          * This is part of the ABI, don't needlessly break compatibility */
1256 };
1257
1258 enum lws_ext_options_types {
1259         EXTARG_NONE,
1260         EXTARG_DEC,
1261         EXTARG_OPT_DEC
1262
1263         /* Add new things just above here ---^
1264          * This is part of the ABI, don't needlessly break compatibility */
1265 };
1266
1267 /**
1268  * struct lws_ext_options -     Option arguments to the extension.  These are
1269  *                              used in the negotiation at ws upgrade time.
1270  *                              The helper function lws_ext_parse_options()
1271  *                              uses these to generate callbacks
1272  *
1273  * @name:                       Option name, eg, "server_no_context_takeover"
1274  * @type:                       What kind of args the option can take
1275  */
1276 struct lws_ext_options {
1277         const char *name;
1278         enum lws_ext_options_types type;
1279
1280         /* Add new things just above here ---^
1281          * This is part of the ABI, don't needlessly break compatibility */
1282 };
1283
1284 struct lws_ext_option_arg {
1285         const char *option_name; /* may be NULL, option_index used then */
1286         int option_index;
1287         const char *start;
1288         int len;
1289 };
1290
1291 /**
1292  * struct lws_extension -       An extension we know how to cope with
1293  *
1294  * @name:                       Formal extension name, eg, "permessage-deflate"
1295  * @callback:                   Service callback
1296  * @client_offer:               String containing exts and options client offers
1297  */
1298
1299 struct lws_extension {
1300         const char *name;
1301         lws_extension_callback_function *callback;
1302         const char *client_offer;
1303
1304         /* Add new things just above here ---^
1305          * This is part of the ABI, don't needlessly break compatibility */
1306 };
1307
1308
1309 #ifdef LWS_WITH_PLUGINS
1310
1311 /* PLUGINS implies LIBUV */
1312
1313 #define LWS_PLUGIN_API_MAGIC 180
1314
1315 struct lws_plugin_capability {
1316         unsigned int api_magic; /* caller fills this in, plugin fills rest */
1317         const struct lws_protocols *protocols;
1318         int count_protocols;
1319         const struct lws_extension *extensions;
1320         int count_extensions;
1321 };
1322
1323 typedef int (*lws_plugin_init_func)(struct lws_context *,
1324                                     struct lws_plugin_capability *);
1325 typedef int (*lws_plugin_destroy_func)(struct lws_context *);
1326 struct lws_plugin {
1327         struct lws_plugin *list;
1328 #if (UV_VERSION_MAJOR > 0)
1329         uv_lib_t lib;
1330 #else
1331         void *l;
1332 #endif
1333         char name[64];
1334         struct lws_plugin_capability caps;
1335 };
1336
1337 #endif
1338
1339 /*
1340  * The internal exts are part of the public abi
1341  * If we add more extensions, publish the callback here  ------v
1342  */
1343
1344 extern int lws_extension_callback_pm_deflate(
1345         struct lws_context *context, const struct lws_extension *ext,
1346         struct lws *wsi, enum lws_extension_callback_reasons reason,
1347         void *user, void *in, size_t len);
1348
1349 LWS_EXTERN int
1350 lws_set_extension_option(struct lws *wsi, const char *ext_name,
1351                          const char *opt_name, const char *opt_val);
1352
1353 struct lws_protocol_vhost_options {
1354         struct lws_protocol_vhost_options *next;
1355         struct lws_protocol_vhost_options *options;
1356         const char *name;
1357         const char *value;
1358 };
1359
1360 /**
1361  * struct lws_context_creation_info - parameters to create context with
1362  *
1363  * This is also used to create vhosts.... if LWS_SERVER_OPTION_EXPLICIT_VHOSTS
1364  * is not given, then for backwards compatibility one vhost is created at
1365  * context-creation time using the info from this struct.
1366  *
1367  * If LWS_SERVER_OPTION_EXPLICIT_VHOSTS is given, then no vhosts are created
1368  * at the same time as the context, they are expected to be created afterwards.
1369  *
1370  * @port:       Port to listen on... you can use CONTEXT_PORT_NO_LISTEN to
1371  *              suppress listening on any port, that's what you want if you are
1372  *              not running a websocket server at all but just using it as a
1373  *              client
1374  * @iface:      NULL to bind the listen socket to all interfaces, or the
1375  *              interface name, eg, "eth2"
1376  * @protocols:  Array of structures listing supported protocols and a protocol-
1377  *              specific callback for each one.  The list is ended with an
1378  *              entry that has a NULL callback pointer.
1379  *              It's not const because we write the owning_server member
1380  * @extensions: NULL or array of lws_extension structs listing the
1381  *              extensions this context supports.  If you configured with
1382  *              --without-extensions, you should give NULL here.
1383  * @token_limits: NULL or struct lws_token_limits pointer which is initialized
1384  *              with a token length limit for each possible WSI_TOKEN_***
1385  * @ssl_cert_filepath:  If libwebsockets was compiled to use ssl, and you want
1386  *                      to listen using SSL, set to the filepath to fetch the
1387  *                      server cert from, otherwise NULL for unencrypted
1388  * @ssl_private_key_filepath: filepath to private key if wanting SSL mode;
1389  *                      if this is set to NULL but sll_cert_filepath is set, the
1390  *                      OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY callback is called
1391  *                      to allow setting of the private key directly via openSSL
1392  *                      library calls
1393  * @ssl_ca_filepath: CA certificate filepath or NULL
1394  * @ssl_cipher_list:    List of valid ciphers to use (eg,
1395  *                      "RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL"
1396  *                      or you can leave it as NULL to get "DEFAULT"
1397  * @http_proxy_address: If non-NULL, attempts to proxy via the given address.
1398  *                      If proxy auth is required, use format
1399  *                      "username:password@server:port"
1400  * @http_proxy_port:    If http_proxy_address was non-NULL, uses this port at
1401  *                      the address
1402  * @gid:        group id to change to after setting listen socket, or -1.
1403  * @uid:        user id to change to after setting listen socket, or -1.
1404  * @options:    0, or LWS_SERVER_OPTION_... bitfields
1405  * @user:       optional user pointer that can be recovered via the context
1406  *              pointer using lws_context_user
1407  * @ka_time:    0 for no keepalive, otherwise apply this keepalive timeout to
1408  *              all libwebsocket sockets, client or server
1409  * @ka_probes:  if ka_time was nonzero, after the timeout expires how many
1410  *              times to try to get a response from the peer before giving up
1411  *              and killing the connection
1412  * @ka_interval: if ka_time was nonzero, how long to wait before each ka_probes
1413  *              attempt
1414  * @provided_client_ssl_ctx: If non-null, swap out libwebsockets ssl
1415  *              implementation for the one provided by provided_ssl_ctx.
1416  *              Libwebsockets no longer is responsible for freeing the context
1417  *              if this option is selected.
1418  * @max_http_header_data: The max amount of header payload that can be handled
1419  *              in an http request (unrecognized header payload is dropped)
1420  * @max_http_header_pool: The max number of connections with http headers that
1421  *              can be processed simultaneously (the corresponding memory is
1422  *              allocated for the lifetime of the context).  If the pool is
1423  *              busy new incoming connections must wait for accept until one
1424  *              becomes free.
1425  * @count_threads: how many contexts to create in an array, 0 = 1
1426  * @fd_limit_per_thread: nonzero means restrict each service thread to this
1427  *              many fds, 0 means the default which is divide the process fd
1428  *              limit by the number of threads.
1429  * @timeout_secs: various processes involving network roundtrips in the
1430  *              library are protected from hanging forever by timeouts.  If
1431  *              nonzero, this member lets you set the timeout used in seconds.
1432  *              Otherwise a default timeout is used.
1433  * @ecdh_curve: if NULL, defaults to initializing server with "prime256v1"
1434  */
1435
1436 struct lws_context_creation_info {
1437         int port;                                       /* VH */
1438         const char *iface;                              /* VH */
1439         const struct lws_protocols *protocols;          /* VH */
1440         const struct lws_extension *extensions;         /* VH */
1441         const struct lws_token_limits *token_limits;
1442         const char *ssl_private_key_password;           /* VH */
1443         const char *ssl_cert_filepath;                  /* VH */
1444         const char *ssl_private_key_filepath;           /* VH */
1445         const char *ssl_ca_filepath;                    /* VH */
1446         const char *ssl_cipher_list;                    /* VH */
1447         const char *http_proxy_address;                 /* VH */
1448         unsigned int http_proxy_port;                   /* VH */
1449         int gid;                                        /* context */
1450         int uid;                                        /* context */
1451         unsigned int options;                           /* context */
1452         void *user;                                     /* context */
1453         int ka_time;
1454         int ka_probes;
1455         int ka_interval;
1456 #ifdef LWS_OPENSSL_SUPPORT
1457         SSL_CTX *provided_client_ssl_ctx;
1458 #else /* maintain structure layout either way */
1459         void *provided_client_ssl_ctx;
1460 #endif
1461
1462         short max_http_header_data;
1463         short max_http_header_pool;
1464
1465         unsigned int count_threads;                     /* context */
1466         unsigned int fd_limit_per_thread;               /* context */
1467         unsigned int timeout_secs;                      /* VH */
1468         const char *ecdh_curve;                         /* VH */
1469         const char *vhost_name;                         /* VH */
1470         const char *plugins_dir;                        /* context */
1471         struct lws_protocol_vhost_options *pvo;         /* VH */
1472
1473         /* Add new things just above here ---^
1474          * This is part of the ABI, don't needlessly break compatibility
1475          *
1476          * The below is to ensure later library versions with new
1477          * members added above will see 0 (default) even if the app
1478          * was not built against the newer headers.
1479          */
1480
1481         void *_unused[8];
1482 };
1483
1484 /**
1485  * struct lws_client_connect_info - parameters to connect with when using
1486  *                                  lws_client_connect_via_info()
1487  *
1488  * @context:    lws context to create connection in
1489  * @address:    remote address to connect to
1490  * @port:       remote port to connect to
1491  * @ssl_connection: nonzero for ssl
1492  * @path:       uri path
1493  * @host:       content of host header
1494  * @origin:     content of origin header
1495  * @protocol:   list of ws protocols
1496  * @ietf_version_or_minus_one: currently leave at 0 or -1
1497  * @userdata:   if non-NULL, use this as wsi user_data instead of malloc it
1498  * @client_exts: array of extensions that may be used on connection
1499  * @method:     if non-NULL, do this http method instead of ws[s] upgrade.
1500  *              use "GET" to be a simple http client connection
1501  * @parent_wsi: if another wsi is responsible for this connection, give it here.
1502  *              this is used to make sure if the parent closes so do any
1503  *              child connections first.
1504  * @uri_replace_from: if non-NULL, when this string is found in URIs in
1505  *              text/html content-encoding, it's replaced with @uri_replace_to
1506  * @uri_replace_to: see above
1507  * @vhost:      vhost to bind to (used to determine related SSL_CTX)
1508  */
1509
1510 struct lws_client_connect_info {
1511         struct lws_context *context;
1512         const char *address;
1513         int port;
1514         int ssl_connection;
1515         const char *path;
1516         const char *host;
1517         const char *origin;
1518         const char *protocol;
1519         int ietf_version_or_minus_one;
1520         void *userdata;
1521         const struct lws_extension *client_exts;
1522         const char *method;
1523         struct lws *parent_wsi;
1524         const char *uri_replace_from;
1525         const char *uri_replace_to;
1526         struct lws_vhost *vhost;
1527
1528         /* Add new things just above here ---^
1529          * This is part of the ABI, don't needlessly break compatibility
1530          *
1531          * The below is to ensure later library versions with new
1532          * members added above will see 0 (default) even if the app
1533          * was not built against the newer headers.
1534          */
1535
1536         void *_unused[4];
1537 };
1538
1539 struct lws_http_mount;
1540
1541 LWS_VISIBLE LWS_EXTERN int
1542 lws_write_http_mount(struct lws_http_mount *next, struct lws_http_mount **res,
1543                      void *store, const char *mountpoint, const char *origin,
1544                      const char *def);
1545
1546 LWS_VISIBLE LWS_EXTERN void
1547 lws_set_log_level(int level,
1548                   void (*log_emit_function)(int level, const char *line));
1549
1550 LWS_VISIBLE LWS_EXTERN void
1551 lwsl_emit_syslog(int level, const char *line);
1552
1553 LWS_VISIBLE LWS_EXTERN struct lws_context *
1554 lws_create_context(struct lws_context_creation_info *info);
1555
1556 struct lws_vhost;
1557
1558 LWS_VISIBLE struct lws_vhost *
1559 lws_create_vhost(struct lws_context *context,
1560                  struct lws_context_creation_info *info,
1561                  struct lws_http_mount *mounts);
1562
1563 LWS_VISIBLE struct lws_vhost *
1564 lws_vhost_get(struct lws *wsi);
1565
1566 LWS_VISIBLE const struct lws_protocols *
1567 lws_protocol_get(struct lws *wsi);
1568
1569 LWS_VISIBLE void *
1570 lws_protocol_vh_priv_zalloc(struct lws_vhost *vhost, const struct lws_protocols *prot,
1571                             int size);
1572 LWS_VISIBLE void *
1573 lws_protocol_vh_priv_get(struct lws_vhost *vhost, const struct lws_protocols *prot);
1574
1575 LWS_VISIBLE LWS_EXTERN int
1576 lws_finalize_startup(struct lws_context *context);
1577
1578 LWS_VISIBLE LWS_EXTERN int
1579 lws_set_proxy(struct lws_vhost *vhost, const char *proxy);
1580
1581 LWS_VISIBLE LWS_EXTERN void
1582 lws_context_destroy(struct lws_context *context);
1583
1584 LWS_VISIBLE LWS_EXTERN int
1585 lws_service(struct lws_context *context, int timeout_ms);
1586
1587 LWS_VISIBLE LWS_EXTERN int
1588 lws_service_tsi(struct lws_context *context, int timeout_ms, int tsi);
1589
1590 LWS_VISIBLE LWS_EXTERN void
1591 lws_cancel_service_pt(struct lws *wsi);
1592
1593 LWS_VISIBLE LWS_EXTERN void
1594 lws_cancel_service(struct lws_context *context);
1595
1596 LWS_VISIBLE LWS_EXTERN int
1597 lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr,
1598                     size_t addrlen);
1599
1600 LWS_VISIBLE LWS_EXTERN const unsigned char *
1601 lws_token_to_string(enum lws_token_indexes token);
1602
1603 LWS_VISIBLE LWS_EXTERN int
1604 lws_add_http_header_by_name(struct lws *wsi, const unsigned char *name,
1605                             const unsigned char *value, int length,
1606                             unsigned char **p, unsigned char *end);
1607 LWS_VISIBLE LWS_EXTERN int
1608 lws_finalize_http_header(struct lws *wsi, unsigned char **p,
1609                          unsigned char *end);
1610 LWS_VISIBLE LWS_EXTERN int
1611 lws_add_http_header_by_token(struct lws *wsi, enum lws_token_indexes token,
1612                              const unsigned char *value, int length,
1613                              unsigned char **p, unsigned char *end);
1614 LWS_VISIBLE LWS_EXTERN int
1615 lws_add_http_header_content_length(struct lws *wsi,
1616                                    unsigned long content_length,
1617                                    unsigned char **p, unsigned char *end);
1618 LWS_VISIBLE LWS_EXTERN int
1619 lws_add_http_header_status(struct lws *wsi,
1620                            unsigned int code, unsigned char **p,
1621                            unsigned char *end);
1622
1623 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
1624 lws_http_transaction_completed(struct lws *wsi);
1625
1626 #ifdef LWS_USE_LIBEV
1627 typedef void (lws_ev_signal_cb_t)(EV_P_ struct ev_signal *w, int revents);
1628
1629 LWS_VISIBLE LWS_EXTERN int
1630 lws_ev_sigint_cfg(struct lws_context *context, int use_ev_sigint,
1631                   lws_ev_signal_cb_t *cb);
1632
1633 LWS_VISIBLE LWS_EXTERN int
1634 lws_ev_initloop(struct lws_context *context, struct ev_loop *loop, int tsi);
1635
1636 LWS_VISIBLE void
1637 lws_ev_sigint_cb(struct ev_loop *loop, struct ev_signal *watcher, int revents);
1638 #endif /* LWS_USE_LIBEV */
1639
1640 #ifdef LWS_USE_LIBUV
1641 LWS_VISIBLE LWS_EXTERN int
1642 lws_uv_sigint_cfg(struct lws_context *context, int use_uv_sigint,
1643                   uv_signal_cb cb);
1644
1645 LWS_VISIBLE LWS_EXTERN void
1646 lws_libuv_run(const struct lws_context *context, int tsi);
1647
1648 LWS_VISIBLE void
1649 lws_libuv_stop(struct lws_context *context);
1650
1651 LWS_VISIBLE LWS_EXTERN int
1652 lws_uv_initloop(struct lws_context *context, uv_loop_t *loop, int tsi);
1653
1654 LWS_VISIBLE LWS_EXTERN uv_loop_t *
1655 lws_uv_getloop(struct lws_context *context, int tsi);
1656
1657 LWS_VISIBLE void
1658 lws_uv_sigint_cb(uv_signal_t *watcher, int signum);
1659 #endif /* LWS_USE_LIBUV */
1660
1661 LWS_VISIBLE LWS_EXTERN int
1662 lws_service_fd(struct lws_context *context, struct lws_pollfd *pollfd);
1663
1664 LWS_VISIBLE LWS_EXTERN int
1665 lws_service_fd_tsi(struct lws_context *context, struct lws_pollfd *pollfd,
1666                    int tsi);
1667
1668 LWS_VISIBLE LWS_EXTERN void *
1669 lws_context_user(struct lws_context *context);
1670
1671 LWS_VISIBLE LWS_EXTERN void *
1672 lws_wsi_user(struct lws *wsi);
1673
1674 /*
1675  * NOTE: These public enums are part of the abi.  If you want to add one,
1676  * add it at where specified so existing users are unaffected.
1677  */
1678 enum pending_timeout {
1679         NO_PENDING_TIMEOUT                                      =  0,
1680         PENDING_TIMEOUT_AWAITING_PROXY_RESPONSE                 =  1,
1681         PENDING_TIMEOUT_AWAITING_CONNECT_RESPONSE               =  2,
1682         PENDING_TIMEOUT_ESTABLISH_WITH_SERVER                   =  3,
1683         PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE                =  4,
1684         PENDING_TIMEOUT_AWAITING_PING                           =  5,
1685         PENDING_TIMEOUT_CLOSE_ACK                               =  6,
1686         PENDING_TIMEOUT_AWAITING_EXTENSION_CONNECT_RESPONSE     =  7,
1687         PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE                   =  8,
1688         PENDING_TIMEOUT_SSL_ACCEPT                              =  9,
1689         PENDING_TIMEOUT_HTTP_CONTENT                            = 10,
1690         PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND                 = 11,
1691         PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE                  = 12,
1692         PENDING_TIMEOUT_SHUTDOWN_FLUSH                          = 13,
1693         PENDING_TIMEOUT_CGI                                     = 14,
1694
1695         /****** add new things just above ---^ ******/
1696 };
1697
1698 LWS_VISIBLE LWS_EXTERN void
1699 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs);
1700
1701 /*
1702  * IMPORTANT NOTICE!
1703  *
1704  * When sending with websocket protocol
1705  *
1706  * LWS_WRITE_TEXT,
1707  * LWS_WRITE_BINARY,
1708  * LWS_WRITE_CONTINUATION,
1709  * LWS_WRITE_PING,
1710  * LWS_WRITE_PONG
1711  *
1712  * the send buffer has to have LWS_PRE bytes valid BEFORE
1713  * the buffer pointer you pass to lws_write().
1714  *
1715  * This allows us to add protocol info before and after the data, and send as
1716  * one packet on the network without payload copying, for maximum efficiency.
1717  *
1718  * So for example you need this kind of code to use lws_write with a
1719  * 128-byte payload
1720  *
1721  *   char buf[LWS_PRE + 128];
1722  *
1723  *   // fill your part of the buffer... for example here it's all zeros
1724  *   memset(&buf[LWS_PRE], 0, 128);
1725  *
1726  *   lws_write(wsi, &buf[LWS_PRE], 128, LWS_WRITE_TEXT);
1727  *
1728  * When sending HTTP, with
1729  *
1730  * LWS_WRITE_HTTP,
1731  * LWS_WRITE_HTTP_HEADERS
1732  * LWS_WRITE_HTTP_FINAL
1733  *
1734  * there is no protocol data prepended, and don't need to take care about the
1735  * LWS_PRE bytes valid before the buffer pointer.
1736  *
1737  * LWS_PRE is at least the frame nonce + 2 header + 8 length
1738  * LWS_SEND_BUFFER_POST_PADDING is deprecated, it's now 0 and can be left off.
1739  * The example apps no longer use it.
1740  *
1741  * Pad LWS_PRE to the CPU word size, so that word references
1742  * to the address immediately after the padding won't cause an unaligned access
1743  * error. Sometimes for performance reasons the recommended padding is even
1744  * larger than sizeof(void *).
1745  */
1746
1747 #if !defined(LWS_SIZEOFPTR)
1748 #define LWS_SIZEOFPTR (sizeof (void *))
1749 #endif
1750 #if !defined(u_int64_t)
1751 #define u_int64_t unsigned long long
1752 #endif
1753
1754 #if __x86_64__
1755 #define _LWS_PAD_SIZE 16        /* Intel recommended for best performance */
1756 #else
1757 #define _LWS_PAD_SIZE LWS_SIZEOFPTR   /* Size of a pointer on the target arch */
1758 #endif
1759 #define _LWS_PAD(n) (((n) % _LWS_PAD_SIZE) ? \
1760                 ((n) + (_LWS_PAD_SIZE - ((n) % _LWS_PAD_SIZE))) : (n))
1761 #define LWS_PRE _LWS_PAD(4 + 10)
1762 /* used prior to 1.7 and retained for backward compatibility */
1763 #define LWS_SEND_BUFFER_PRE_PADDING LWS_PRE
1764 #define LWS_SEND_BUFFER_POST_PADDING 0
1765
1766 LWS_VISIBLE LWS_EXTERN int
1767 lws_write(struct lws *wsi, unsigned char *buf, size_t len,
1768           enum lws_write_protocol protocol);
1769
1770 /**
1771  * lws_close_reason - Set reason and aux data to send with Close packet
1772  *              If you are going to return nonzero from the callback
1773  *              requesting the connection to close, you can optionally
1774  *              call this to set the reason the peer will be told if
1775  *              possible.
1776  *
1777  * @wsi:        The websocket connection to set the close reason on
1778  * @status:     A valid close status from websocket standard
1779  * @buf:        NULL or buffer containing up to 124 bytes of auxiliary data
1780  * @len:        Length of data in @buf to send
1781  */
1782 LWS_VISIBLE LWS_EXTERN void
1783 lws_close_reason(struct lws *wsi, enum lws_close_status status,
1784                  unsigned char *buf, size_t len);
1785
1786 /* helper for case where buffer may be const */
1787 #define lws_write_http(wsi, buf, len) \
1788         lws_write(wsi, (unsigned char *)(buf), len, LWS_WRITE_HTTP)
1789
1790 LWS_VISIBLE LWS_EXTERN int
1791 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
1792                     const char *other_headers, int other_headers_len);
1793 LWS_VISIBLE LWS_EXTERN int
1794 lws_serve_http_file_fragment(struct lws *wsi);
1795
1796 LWS_VISIBLE LWS_EXTERN int
1797 lws_return_http_status(struct lws *wsi, unsigned int code,
1798                        const char *html_body);
1799
1800 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1801 lws_get_protocol(struct lws *wsi);
1802
1803 LWS_VISIBLE LWS_EXTERN int
1804 lws_callback_on_writable(struct lws *wsi);
1805
1806 LWS_VISIBLE LWS_EXTERN int
1807 lws_callback_on_writable_all_protocol(const struct lws_context *context,
1808                                       const struct lws_protocols *protocol);
1809
1810 LWS_VISIBLE int
1811 lws_callback_on_writable_all_protocol_vhost(const struct lws_vhost *vhost,
1812                                       const struct lws_protocols *protocol);
1813
1814 LWS_VISIBLE LWS_EXTERN int
1815 lws_callback_all_protocol(struct lws_context *context,
1816                           const struct lws_protocols *protocol, int reason);
1817
1818 LWS_VISIBLE int
1819 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
1820                           const struct lws_protocols *protocol, int reason);
1821
1822 LWS_VISIBLE LWS_EXTERN int
1823 lws_get_socket_fd(struct lws *wsi);
1824
1825 LWS_VISIBLE LWS_EXTERN int
1826 lws_is_final_fragment(struct lws *wsi);
1827
1828 LWS_VISIBLE LWS_EXTERN unsigned char
1829 lws_get_reserved_bits(struct lws *wsi);
1830
1831 LWS_VISIBLE LWS_EXTERN int
1832 lws_rx_flow_control(struct lws *wsi, int enable);
1833
1834 LWS_VISIBLE LWS_EXTERN void
1835 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
1836                                const struct lws_protocols *protocol);
1837
1838 LWS_VISIBLE LWS_EXTERN size_t
1839 lws_remaining_packet_payload(struct lws *wsi);
1840
1841 /*
1842  * if the protocol does not have any guidance, returns -1.  Currently only
1843  * http2 connections get send window information from this API.  But your code
1844  * should use it so it can work properly with any protocol.
1845  *
1846  * If nonzero return is the amount of payload data the peer or intermediary has
1847  * reported it has buffer space for.  That has NO relationship with the amount
1848  * of buffer space your OS can accept on this connection for a write action.
1849  *
1850  * This number represents the maximum you could send to the peer or intermediary
1851  * on this connection right now without it complaining.
1852  *
1853  * lws manages accounting for send window updates and payload writes
1854  * automatically, so this number reflects the situation at the peer or
1855  * intermediary dynamically.
1856  */
1857 LWS_VISIBLE LWS_EXTERN size_t
1858 lws_get_peer_write_allowance(struct lws *wsi);
1859
1860 /* deprecated, use lws_client_connect_via_info() */
1861 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
1862 lws_client_connect(struct lws_context *clients, const char *address,
1863                    int port, int ssl_connection, const char *path,
1864                    const char *host, const char *origin, const char *protocol,
1865                    int ietf_version_or_minus_one) LWS_WARN_DEPRECATED;
1866 /* deprecated, use lws_client_connect_via_info() */
1867 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
1868 lws_client_connect_extended(struct lws_context *clients, const char *address,
1869                             int port, int ssl_connection, const char *path,
1870                             const char *host, const char *origin,
1871                             const char *protocol, int ietf_version_or_minus_one,
1872                             void *userdata) LWS_WARN_DEPRECATED;
1873
1874 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
1875 lws_client_connect_via_info(struct lws_client_connect_info * ccinfo);
1876
1877 LWS_VISIBLE LWS_EXTERN struct lws *
1878 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd);
1879 LWS_VISIBLE LWS_EXTERN struct lws *
1880 lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
1881                 const char *readbuf, size_t len);
1882
1883 LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
1884 lws_canonical_hostname(struct lws_context *context);
1885
1886
1887 LWS_VISIBLE LWS_EXTERN void
1888 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
1889                        int name_len, char *rip, int rip_len);
1890
1891 LWS_VISIBLE LWS_EXTERN int
1892 lws_get_random(struct lws_context *context, void *buf, int len);
1893
1894 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
1895 lws_daemonize(const char *_lock_path);
1896
1897 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
1898 lws_send_pipe_choked(struct lws *wsi);
1899
1900 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
1901 lws_partial_buffered(struct lws *wsi);
1902
1903 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
1904 lws_frame_is_binary(struct lws *wsi);
1905
1906 LWS_VISIBLE LWS_EXTERN int
1907 lws_is_ssl(struct lws *wsi);
1908
1909 LWS_VISIBLE LWS_EXTERN int
1910 lws_is_cgi(struct lws *wsi);
1911
1912 #ifdef LWS_SHA1_USE_OPENSSL_NAME
1913 #define lws_SHA1 SHA1
1914 #else
1915 LWS_VISIBLE LWS_EXTERN unsigned char *
1916 lws_SHA1(const unsigned char *d, size_t n, unsigned char *md);
1917 #endif
1918
1919 LWS_VISIBLE LWS_EXTERN int
1920 lws_b64_encode_string(const char *in, int in_len, char *out, int out_size);
1921
1922 LWS_VISIBLE LWS_EXTERN int
1923 lws_b64_decode_string(const char *in, char *out, int out_size);
1924
1925 LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
1926 lws_get_library_version(void);
1927
1928 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
1929 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
1930               const char **path);
1931
1932 /*
1933  *  Access to http headers
1934  *
1935  *  In lws the client http headers are temporarily malloc'd only for the
1936  *  duration of the http part of the handshake.  It's because in most cases,
1937  *  the header content is ignored for the whole rest of the connection lifetime
1938  *  and would then just be taking up space needlessly.
1939  *
1940  *  During LWS_CALLBACK_HTTP when the URI path is delivered is the last time
1941  *  the http headers are still allocated, you can use these apis then to
1942  *  look at and copy out interesting header content (cookies, etc)
1943  *
1944  *  Notice that the header total length reported does not include a terminating
1945  *  '\0', however you must allocate for it when using the _copy apis.  So the
1946  *  length reported for a header containing "123" is 3, but you must provide
1947  *  a buffer of length 4 so that "123\0" may be copied into it, or the copy
1948  *  will fail with a nonzero return code.
1949  */
1950
1951 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
1952 lws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h);
1953
1954 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
1955 lws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx);
1956
1957 /*
1958  * copies the whole, aggregated header, even if it was delivered in
1959  * several actual headers piece by piece
1960  */
1961 LWS_VISIBLE LWS_EXTERN int
1962 lws_hdr_copy(struct lws *wsi, char *dest, int len, enum lws_token_indexes h);
1963
1964 /*
1965  * copies only fragment frag_idx of a header.  Normally this is only useful
1966  * to parse URI arguments like ?x=1&y=2, token index WSI_TOKEN_HTTP_URI_ARGS
1967  * fragment 0 will contain "x=1" and fragment 1 "y=2"
1968  */
1969 LWS_VISIBLE LWS_EXTERN int
1970 lws_hdr_copy_fragment(struct lws *wsi, char *dest, int len,
1971                       enum lws_token_indexes h, int frag_idx);
1972
1973
1974 /* get the active file operations struct */
1975 LWS_VISIBLE LWS_EXTERN struct lws_plat_file_ops * LWS_WARN_UNUSED_RESULT
1976 lws_get_fops(struct lws_context *context);
1977
1978 LWS_VISIBLE LWS_EXTERN struct lws_context * LWS_WARN_UNUSED_RESULT
1979 lws_get_context(const struct lws *wsi);
1980
1981 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
1982 lws_get_count_threads(struct lws_context *context);
1983
1984 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
1985 lws_get_parent(const struct lws *wsi);
1986
1987 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
1988 lws_get_child(const struct lws *wsi);
1989
1990 #ifdef LWS_WITH_CGI
1991 enum lws_enum_stdinouterr {
1992         LWS_STDIN = 0,
1993         LWS_STDOUT = 1,
1994         LWS_STDERR = 2,
1995 };
1996
1997 enum lws_cgi_hdr_state {
1998         LCHS_HEADER,
1999         LCHS_CR1,
2000         LCHS_LF1,
2001         LCHS_CR2,
2002         LCHS_LF2,
2003         LHCS_PAYLOAD,
2004 };
2005
2006 struct lws_cgi_args {
2007         struct lws **stdwsi; /* get fd with lws_get_socket_fd() */
2008         enum lws_enum_stdinouterr ch;
2009         unsigned char *data; /* for messages with payload */
2010         enum lws_cgi_hdr_state hdr_state;
2011         int len;
2012 };
2013
2014 LWS_VISIBLE LWS_EXTERN int
2015 lws_cgi(struct lws *wsi, char * const *exec_array,  int script_uri_path_len,
2016         int timeout_secs);
2017
2018 LWS_VISIBLE LWS_EXTERN int
2019 lws_cgi_write_split_stdout_headers(struct lws *wsi);
2020
2021 LWS_VISIBLE LWS_EXTERN int
2022 lws_cgi_kill(struct lws *wsi);
2023 #endif
2024
2025 LWS_VISIBLE LWS_EXTERN int
2026 lws_http_client_read(struct lws *wsi, char **buf, int *len);
2027
2028 /*
2029  * Wsi-associated File Operations access helpers
2030  *
2031  * Use these helper functions if you want to access a file from the perspective
2032  * of a specific wsi, which is usually the case.  If you just want contextless
2033  * file access, use the fops callbacks directly with NULL wsi instead of these
2034  * helpers.
2035  *
2036  * If so, then it calls the platform handler or user overrides where present
2037  * (as defined in info->fops)
2038  *
2039  * The advantage from all this is user code can be portable for file operations
2040  * without having to deal with differences between platforms.
2041  */
2042
2043 static LWS_INLINE lws_filefd_type LWS_WARN_UNUSED_RESULT
2044 lws_plat_file_open(struct lws *wsi, const char *filename,
2045                    unsigned long *filelen, int flags)
2046 {
2047         return lws_get_fops(lws_get_context(wsi))->open(wsi, filename,
2048                                                     filelen, flags);
2049 }
2050
2051 static LWS_INLINE int
2052 lws_plat_file_close(struct lws *wsi, lws_filefd_type fd)
2053 {
2054         return lws_get_fops(lws_get_context(wsi))->close(wsi, fd);
2055 }
2056
2057 static LWS_INLINE unsigned long
2058 lws_plat_file_seek_cur(struct lws *wsi, lws_filefd_type fd, long offset)
2059 {
2060         return lws_get_fops(lws_get_context(wsi))->seek_cur(wsi, fd, offset);
2061 }
2062
2063 static LWS_INLINE int LWS_WARN_UNUSED_RESULT
2064 lws_plat_file_read(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
2065                    unsigned char *buf, unsigned long len)
2066 {
2067         return lws_get_fops(lws_get_context(wsi))->read(wsi, fd, amount, buf,
2068                                                         len);
2069 }
2070
2071 static LWS_INLINE int LWS_WARN_UNUSED_RESULT
2072 lws_plat_file_write(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
2073                     unsigned char *buf, unsigned long len)
2074 {
2075         return lws_get_fops(lws_get_context(wsi))->write(wsi, fd, amount, buf,
2076                                                          len);
2077 }
2078
2079 /*
2080  * Note: this is not normally needed as a user api.  It's provided in case it is
2081  * useful when integrating with other app poll loop service code.
2082  */
2083 LWS_VISIBLE LWS_EXTERN int
2084 lws_read(struct lws *wsi, unsigned char *buf, size_t len);
2085
2086 #ifndef LWS_NO_EXTENSIONS
2087 /* Deprecated
2088  *
2089  * There is no longer a set internal extensions table.  The table is provided
2090  * by user code along with application-specific settings.  See the test
2091  * client and server for how to do.
2092  */
2093 static LWS_INLINE LWS_WARN_DEPRECATED const struct lws_extension *
2094 lws_get_internal_extensions() { return NULL; }
2095 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2096 lws_ext_parse_options(const struct lws_extension *ext, struct lws *wsi,
2097                        void *ext_user, const struct lws_ext_options *opts,
2098                        const char *o, int len);
2099 #endif
2100
2101 /*
2102  * custom allocator support
2103  */
2104 LWS_VISIBLE LWS_EXTERN void
2105 lws_set_allocator(void *(*realloc)(void *ptr, size_t size));
2106
2107 #ifdef __cplusplus
2108 }
2109 #endif
2110
2111 #endif