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