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