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