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