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