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