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