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