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