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