absorb README.rst into main README and code
[profile/ivi/libwebsockets.git] / lib / libwebsockets.h
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010 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__
23 #define __LIBWEBSOCKET_H__
24
25 #ifdef __cplusplus
26 extern "C" {
27 #include <cstddef>
28 #endif
29
30 #ifdef WIN32
31
32 #ifndef WIN32_LEAN_AND_MEAN
33 #define WIN32_LEAN_AND_MEAN
34 #endif
35 #include <winsock2.h>
36 #include <ws2tcpip.h>
37 #include <stddef.h>
38 #include "../win32port/win32helpers/websock-w32.h"
39
40 #include "../win32port/win32helpers/gettimeofday.h"
41
42 #define strcasecmp stricmp
43
44 typedef int ssize_t;
45
46 #ifdef LWS_DLL
47 #ifdef LWS_INTERNAL
48 #define LWS_EXTERN extern __declspec(dllexport)
49 #else
50 #define LWS_EXTERN extern __declspec(dllimport)
51 #endif
52 #endif
53
54 #else
55 #include <poll.h>
56 #endif
57
58 #ifndef LWS_EXTERN
59 #define LWS_EXTERN extern
60 #endif
61
62 #define CONTEXT_PORT_NO_LISTEN 0
63 #define MAX_MUX_RECURSION 2
64
65 enum lws_log_levels {
66         LLL_ERR = 1 << 0,
67         LLL_WARN = 1 << 1,
68         LLL_INFO = 1 << 2,
69         LLL_DEBUG = 1 << 3,
70         LLL_PARSER = 1 << 4,
71         LLL_HEADER = 1 << 5,
72         LLL_EXT = 1 << 6,
73         LLL_CLIENT = 1 << 7,
74
75         LLL_COUNT = 8 /* set to count of valid flags */
76 };
77
78 enum libwebsocket_context_options {
79         LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK = 1,
80         LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT = 2,
81         LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME = 4,
82 };
83
84 enum libwebsocket_callback_reasons {
85         LWS_CALLBACK_ESTABLISHED,
86         LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
87         LWS_CALLBACK_CLIENT_ESTABLISHED,
88         LWS_CALLBACK_CLOSED,
89         LWS_CALLBACK_RECEIVE,
90         LWS_CALLBACK_CLIENT_RECEIVE,
91         LWS_CALLBACK_CLIENT_RECEIVE_PONG,
92         LWS_CALLBACK_CLIENT_WRITEABLE,
93         LWS_CALLBACK_SERVER_WRITEABLE,
94         LWS_CALLBACK_HTTP,
95         LWS_CALLBACK_BROADCAST,
96         LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
97         LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
98         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
99         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
100         LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
101         LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
102         LWS_CALLBACK_CONFIRM_EXTENSION_OKAY,
103         LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
104         /* external poll() management support */
105         LWS_CALLBACK_ADD_POLL_FD,
106         LWS_CALLBACK_DEL_POLL_FD,
107         LWS_CALLBACK_SET_MODE_POLL_FD,
108         LWS_CALLBACK_CLEAR_MODE_POLL_FD,
109 };
110
111 enum libwebsocket_extension_callback_reasons {
112         LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT,
113         LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT,
114         LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT,
115         LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT,
116         LWS_EXT_CALLBACK_CONSTRUCT,
117         LWS_EXT_CALLBACK_CLIENT_CONSTRUCT,
118         LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE,
119         LWS_EXT_CALLBACK_CHECK_OK_TO_PROPOSE_EXTENSION,
120         LWS_EXT_CALLBACK_DESTROY,
121         LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING,
122         LWS_EXT_CALLBACK_ANY_WSI_ESTABLISHED,
123         LWS_EXT_CALLBACK_PACKET_RX_PREPARSE,
124         LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
125         LWS_EXT_CALLBACK_PACKET_TX_DO_SEND,
126         LWS_EXT_CALLBACK_HANDSHAKE_REPLY_TX,
127         LWS_EXT_CALLBACK_FLUSH_PENDING_TX,
128         LWS_EXT_CALLBACK_EXTENDED_PAYLOAD_RX,
129         LWS_EXT_CALLBACK_CAN_PROXY_CLIENT_CONNECTION,
130         LWS_EXT_CALLBACK_1HZ,
131         LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE,
132         LWS_EXT_CALLBACK_IS_WRITEABLE,
133         LWS_EXT_CALLBACK_PAYLOAD_TX,
134         LWS_EXT_CALLBACK_PAYLOAD_RX,
135 };
136
137 enum libwebsocket_write_protocol {
138         LWS_WRITE_TEXT,
139         LWS_WRITE_BINARY,
140         LWS_WRITE_CONTINUATION,
141         LWS_WRITE_HTTP,
142
143         /* special 04+ opcodes */
144
145         LWS_WRITE_CLOSE,
146         LWS_WRITE_PING,
147         LWS_WRITE_PONG,
148
149         /* flags */
150
151         LWS_WRITE_NO_FIN = 0x40,
152         /*
153          * client packet payload goes out on wire unmunged
154          * only useful for security tests since normal servers cannot
155          * decode the content if used
156          */
157         LWS_WRITE_CLIENT_IGNORE_XOR_MASK = 0x80
158 };
159
160 /*
161  * you need these to look at headers that have been parsed if using the
162  * LWS_CALLBACK_FILTER_CONNECTION callback.  If a header from the enum
163  * list below is absent, .token = NULL and token_len = 0.  Otherwise .token
164  * points to .token_len chars containing that header content.
165  */
166
167 struct lws_tokens {
168         char *token;
169         int token_len;
170 };
171
172 enum lws_token_indexes {
173         WSI_TOKEN_GET_URI,
174         WSI_TOKEN_HOST,
175         WSI_TOKEN_CONNECTION,
176         WSI_TOKEN_KEY1,
177         WSI_TOKEN_KEY2,
178         WSI_TOKEN_PROTOCOL,
179         WSI_TOKEN_UPGRADE,
180         WSI_TOKEN_ORIGIN,
181         WSI_TOKEN_DRAFT,
182         WSI_TOKEN_CHALLENGE,
183
184         /* new for 04 */
185         WSI_TOKEN_KEY,
186         WSI_TOKEN_VERSION,
187         WSI_TOKEN_SWORIGIN,
188
189         /* new for 05 */
190         WSI_TOKEN_EXTENSIONS,
191
192         /* client receives these */
193         WSI_TOKEN_ACCEPT,
194         WSI_TOKEN_NONCE,
195         WSI_TOKEN_HTTP,
196         WSI_TOKEN_MUXURL,
197
198         /* always last real token index*/
199         WSI_TOKEN_COUNT,
200         /* parser state additions */
201         WSI_TOKEN_NAME_PART,
202         WSI_TOKEN_SKIPPING,
203         WSI_TOKEN_SKIPPING_SAW_CR,
204         WSI_PARSING_COMPLETE,
205         WSI_INIT_TOKEN_MUXURL,
206 };
207
208 /*
209  * From RFC 6455
210    1000
211
212       1000 indicates a normal closure, meaning that the purpose for
213       which the connection was established has been fulfilled.
214
215    1001
216
217       1001 indicates that an endpoint is "going away", such as a server
218       going down or a browser having navigated away from a page.
219
220    1002
221
222       1002 indicates that an endpoint is terminating the connection due
223       to a protocol error.
224
225    1003
226
227       1003 indicates that an endpoint is terminating the connection
228       because it has received a type of data it cannot accept (e.g., an
229       endpoint that understands only text data MAY send this if it
230       receives a binary message).
231
232    1004
233
234       Reserved.  The specific meaning might be defined in the future.
235
236    1005
237
238       1005 is a reserved value and MUST NOT be set as a status code in a
239       Close control frame by an endpoint.  It is designated for use in
240       applications expecting a status code to indicate that no status
241       code was actually present.
242
243    1006
244
245       1006 is a reserved value and MUST NOT be set as a status code in a
246       Close control frame by an endpoint.  It is designated for use in
247       applications expecting a status code to indicate that the
248       connection was closed abnormally, e.g., without sending or
249       receiving a Close control frame.
250
251    1007
252
253       1007 indicates that an endpoint is terminating the connection
254       because it has received data within a message that was not
255       consistent with the type of the message (e.g., non-UTF-8 [RFC3629]
256       data within a text message).
257
258    1008
259
260       1008 indicates that an endpoint is terminating the connection
261       because it has received a message that violates its policy.  This
262       is a generic status code that can be returned when there is no
263       other more suitable status code (e.g., 1003 or 1009) or if there
264       is a need to hide specific details about the policy.
265
266    1009
267
268       1009 indicates that an endpoint is terminating the connection
269       because it has received a message that is too big for it to
270       process.
271
272    1010
273
274       1010 indicates that an endpoint (client) is terminating the
275       connection because it has expected the server to negotiate one or
276       more extension, but the server didn't return them in the response
277       message of the WebSocket handshake.  The list of extensions that
278       are needed SHOULD appear in the /reason/ part of the Close frame.
279       Note that this status code is not used by the server, because it
280       can fail the WebSocket handshake instead.
281
282    1011
283
284       1011 indicates that a server is terminating the connection because
285       it encountered an unexpected condition that prevented it from
286       fulfilling the request.
287
288    1015
289
290       1015 is a reserved value and MUST NOT be set as a status code in a
291       Close control frame by an endpoint.  It is designated for use in
292       applications expecting a status code to indicate that the
293       connection was closed due to a failure to perform a TLS handshake
294       (e.g., the server certificate can't be verified).
295 */
296
297 enum lws_close_status {
298         LWS_CLOSE_STATUS_NOSTATUS = 0,
299         LWS_CLOSE_STATUS_NORMAL = 1000,
300         LWS_CLOSE_STATUS_GOINGAWAY = 1001,
301         LWS_CLOSE_STATUS_PROTOCOL_ERR = 1002,
302         LWS_CLOSE_STATUS_UNACCEPTABLE_OPCODE = 1003,
303         LWS_CLOSE_STATUS_RESERVED = 1004,
304         LWS_CLOSE_STATUS_NO_STATUS = 1005,
305         LWS_CLOSE_STATUS_ABNORMAL_CLOSE = 1006,
306         LWS_CLOSE_STATUS_INVALID_PAYLOAD = 1007,
307         LWS_CLOSE_STATUS_POLICY_VIOLATION = 1008,
308         LWS_CLOSE_STATUS_MESSAGE_TOO_LARGE = 1009,
309         LWS_CLOSE_STATUS_EXTENSION_REQUIRED = 1010,
310     LWS_CLOSE_STATUS_UNEXPECTED_CONDITION = 1011,
311     LWS_CLOSE_STATUS_TLS_FAILURE = 1015,
312 };
313
314 struct libwebsocket;
315 struct libwebsocket_context;
316 struct libwebsocket_extension;
317
318 /**
319  * callback_function() - User server actions
320  * @context:    Websockets context
321  * @wsi:        Opaque websocket instance pointer
322  * @reason:     The reason for the call
323  * @user:       Pointer to per-session user data allocated by library
324  * @in:         Pointer used for some callback reasons
325  * @len:        Length set for some callback reasons
326  *
327  *      This callback is the way the user controls what is served.  All the
328  *      protocol detail is hidden and handled by the library.
329  *
330  *      For each connection / session there is user data allocated that is
331  *      pointed to by "user".  You set the size of this user data area when
332  *      the library is initialized with libwebsocket_create_server.
333  *
334  *      You get an opportunity to initialize user data when called back with
335  *      LWS_CALLBACK_ESTABLISHED reason.
336  *
337  *      LWS_CALLBACK_ESTABLISHED:  after the server completes a handshake with
338  *                              an incoming client
339  *
340  *  LWS_CALLBACK_CLIENT_CONNECTION_ERROR: the request client connection has
341  *        been unable to complete a handshake with the remote server
342  *
343  *  LWS_CALLBACK_CLIENT_ESTABLISHED: after your client connection completed
344  *                              a handshake with the remote server
345  *
346  *      LWS_CALLBACK_CLOSED: when the websocket session ends
347  *
348  *      LWS_CALLBACK_BROADCAST: signal to send to client (you would use
349  *                              libwebsocket_write() taking care about the
350  *                              special buffer requirements
351  *
352  *      LWS_CALLBACK_RECEIVE: data has appeared for this server endpoint from a
353  *                              remote client, it can be found at *in and is
354  *                              len bytes long
355  *
356  *      LWS_CALLBACK_CLIENT_RECEIVE_PONG: if you elected to see PONG packets,
357  *                              they appear with this callback reason.  PONG
358  *                              packets only exist in 04+ protocol
359  *
360  *      LWS_CALLBACK_CLIENT_RECEIVE: data has appeared from the server for the
361  *                              client connection, it can be found at *in and
362  *                              is len bytes long
363  *
364  *      LWS_CALLBACK_HTTP: an http request has come from a client that is not
365  *                              asking to upgrade the connection to a websocket
366  *                              one.  This is a chance to serve http content,
367  *                              for example, to send a script to the client
368  *                              which will then open the websockets connection.
369  *                              @in points to the URI path requested and
370  *                              libwebsockets_serve_http_file() makes it very
371  *                              simple to send back a file to the client.
372  *                              Normally after sending the file you are done
373  *                              with the http connection, since the rest of the
374  *                              activity will come by websockets from the script
375  *                              that was delivered by http, so you will want to
376  *                              return 1; to close and free up the connection.
377  *                              That's important because it uses a slot in the
378  *                              total number of client connections allowed set
379  *                              by MAX_CLIENTS.
380  *
381  *      LWS_CALLBACK_CLIENT_WRITEABLE:
382  *      LWS_CALLBACK_SERVER_WRITEABLE:   If you call
383  *              libwebsocket_callback_on_writable() on a connection, you will
384  *              get one of these callbacks coming when the connection socket
385  *              is able to accept another write packet without blocking.
386  *              If it already was able to take another packet without blocking,
387  *              you'll get this callback at the next call to the service loop
388  *              function.  Notice that CLIENTs get LWS_CALLBACK_CLIENT_WRITEABLE
389  *              and servers get LWS_CALLBACK_SERVER_WRITEABLE.
390  *
391  *      LWS_CALLBACK_FILTER_NETWORK_CONNECTION: called when a client connects to
392  *              the server at network level; the connection is accepted but then
393  *              passed to this callback to decide whether to hang up immediately
394  *              or not, based on the client IP.  @user contains the connection
395  *              socket's descriptor.  Return non-zero to terminate
396  *              the connection before sending or receiving anything.
397  *              Because this happens immediately after the network connection
398  *              from the client, there's no websocket protocol selected yet so
399  *              this callback is issued only to protocol 0.
400  *
401  *      LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION: called when the handshake has
402  *              been received and parsed from the client, but the response is
403  *              not sent yet.  Return non-zero to disallow the connection.
404  *              @user is a pointer to an array of struct lws_tokens, you can
405  *              use the header enums lws_token_indexes from libwebsockets.h
406  *              to check for and read the supported header presence and
407  *              content before deciding to allow the handshake to proceed or
408  *              to kill the connection.
409  *
410  *      LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS: if configured for
411  *              including OpenSSL support, this callback allows your user code
412  *              to perform extra SSL_CTX_load_verify_locations() or similar
413  *              calls to direct OpenSSL where to find certificates the client
414  *              can use to confirm the remote server identity.  @user is the
415  *              OpenSSL SSL_CTX*
416  *
417  *      LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS: if configured for
418  *              including OpenSSL support, this callback allows your user code
419  *              to load extra certifcates into the server which allow it to
420  *              verify the validity of certificates returned by clients.  @user
421  *              is the server's OpenSSL SSL_CTX*
422  *
423  *      LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION: if the
424  *              libwebsockets context was created with the option
425  *              LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT, then this
426  *              callback is generated during OpenSSL verification of the cert
427  *              sent from the client.  It is sent to protocol[0] callback as
428  *              no protocol has been negotiated on the connection yet.
429  *              Notice that the libwebsockets context and wsi are both NULL
430  *              during this callback.  See
431  *               http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html
432  *              to understand more detail about the OpenSSL callback that
433  *              generates this libwebsockets callback and the meanings of the
434  *              arguments passed.  In this callback, @user is the x509_ctx,
435  *              @in is the ssl pointer and @len is preverify_ok
436  *              Notice that this callback maintains libwebsocket return
437  *              conventions, return 0 to mean the cert is OK or 1 to fail it.
438  *              This also means that if you don't handle this callback then
439  *              the default callback action of returning 0 allows the client
440  *              certificates.
441  *
442  *      LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER: this callback happens
443  *              when a client handshake is being compiled.  @user is NULL,
444  *              @in is a char **, it's pointing to a char * which holds the
445  *              next location in the header buffer where you can add
446  *              headers, and @len is the remaining space in the header buffer,
447  *              which is typically some hundreds of bytes.  So, to add a canned
448  *              cookie, your handler code might look similar to:
449  *
450  *              char **p = (char **)in;
451  *
452  *              if (len < 100)
453  *                      return 1;
454  *
455  *              *p += sprintf(*p, "Cookie: a=b\x0d\x0a");
456  *
457  *              return 0;
458  *
459  *              Notice if you add anything, you just have to take care about
460  *              the CRLF on the line you added.  Obviously this callback is
461  *              optional, if you don't handle it everything is fine.
462  *
463  *              Notice the callback is coming to protocols[0] all the time,
464  *              because there is no specific protocol handshook yet.
465  *
466  *      LWS_CALLBACK_CONFIRM_EXTENSION_OKAY: When the server handshake code
467  *              sees that it does support a requested extension, before
468  *              accepting the extension by additing to the list sent back to
469  *              the client it gives this callback just to check that it's okay
470  *              to use that extension.  It calls back to the requested protocol
471  *              and with @in being the extension name, @len is 0 and @user is
472  *              valid.  Note though at this time the ESTABLISHED callback hasn't
473  *              happened yet so if you initialize @user content there, @user
474  *              content during this callback might not be useful for anything.
475  *              Notice this callback comes to protocols[0].
476  *
477  *      LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED:        When a client
478  *              connection is being prepared to start a handshake to a server,
479  *              each supported extension is checked with protocols[0] callback
480  *              with this reason, giving the user code a chance to suppress the
481  *              claim to support that extension by returning non-zero.  If
482  *              unhandled, by default 0 will be returned and the extension
483  *              support included in the header to the server.  Notice this
484  *              callback comes to protocols[0].
485  *
486  *      The next four reasons are optional and only need taking care of if you
487  *      will be integrating libwebsockets sockets into an external polling
488  *      array.
489  * 
490  *      LWS_CALLBACK_ADD_POLL_FD: libwebsocket deals with its poll() loop
491  *              internally, but in the case you are integrating with another
492  *              server you will need to have libwebsocket sockets share a
493  *              polling array with the other server.  This and the other
494  *              POLL_FD related callbacks let you put your specialized
495  *              poll array interface code in the callback for protocol 0, the
496  *              first protocol you support, usually the HTTP protocol in the
497  *              serving case.  This callback happens when a socket needs to be
498  *              added to the polling loop: @user contains the fd, and
499  *              @len is the events bitmap (like, POLLIN).  If you are using the
500  *              internal polling loop (the "service" callback), you can just
501  *              ignore these callbacks.
502  *
503  *      LWS_CALLBACK_DEL_POLL_FD: This callback happens when a socket descriptor
504  *              needs to be removed from an external polling array.  @user is
505  *              the socket desricptor.  If you are using the internal polling
506  *              loop, you can just ignore it.
507  *
508  *      LWS_CALLBACK_SET_MODE_POLL_FD: This callback happens when libwebsockets
509  *              wants to modify the events for the socket descriptor in @user.
510  *              The handler should OR @len on to the events member of the pollfd
511  *              struct for this socket descriptor.  If you are using the
512  *              internal polling loop, you can just ignore it.
513  *
514  *      LWS_CALLBACK_CLEAR_MODE_POLL_FD: This callback occurs when libwebsockets
515  *              wants to modify the events for the socket descriptor in @user.
516  *              The handler should AND ~@len on to the events member of the
517  *              pollfd struct for this socket descriptor.  If you are using the
518  *              internal polling loop, you can just ignore it.
519  */
520 LWS_EXTERN int callback(struct libwebsocket_context * context,
521                         struct libwebsocket *wsi,
522                          enum libwebsocket_callback_reasons reason, void *user,
523                                                           void *in, size_t len);
524
525 typedef int (callback_function)(struct libwebsocket_context * context,
526                         struct libwebsocket *wsi,
527                          enum libwebsocket_callback_reasons reason, void *user,
528                                                           void *in, size_t len);
529
530
531 /**
532  * extension_callback_function() - Hooks to allow extensions to operate
533  * @context:    Websockets context
534  * @ext:        This extension
535  * @wsi:        Opaque websocket instance pointer
536  * @reason:     The reason for the call
537  * @user:       Pointer to per-session user data allocated by library
538  * @in:         Pointer used for some callback reasons
539  * @len:        Length set for some callback reasons
540  *
541  *      Each extension that is active on a particular connection receives
542  *      callbacks during the connection lifetime to allow the extension to
543  *      operate on websocket data and manage itself.
544  *
545  *      Libwebsockets takes care of allocating and freeing "user" memory for
546  *      each active extension on each connection.  That is what is pointed to
547  *      by the @user parameter.
548  *
549  *      LWS_EXT_CALLBACK_CONSTRUCT:  called when the server has decided to
550  *              select this extension from the list provided by the client,
551  *              just before the server will send back the handshake accepting
552  *              the connection with this extension active.  This gives the
553  *              extension a chance to initialize its connection context found
554  *              in @user.
555  *
556  *      LWS_EXT_CALLBACK_CLIENT_CONSTRUCT: same as LWS_EXT_CALLBACK_CONSTRUCT
557  *              but called when client is instantiating this extension.  Some
558  *              extensions will work the same on client and server side and then
559  *              you can just merge handlers for both CONSTRUCTS.
560  *
561  *      LWS_EXT_CALLBACK_DESTROY:  called when the connection the extension was
562  *              being used on is about to be closed and deallocated.  It's the
563  *              last chance for the extension to deallocate anything it has
564  *              allocated in the user data (pointed to by @user) before the
565  *              user data is deleted.  This same callback is used whether you
566  *              are in client or server instantiation context.
567  *
568  *      LWS_EXT_CALLBACK_PACKET_RX_PREPARSE: when this extension was active on
569  *              a connection, and a packet of data arrived at the connection,
570  *              it is passed to this callback to give the extension a chance to
571  *              change the data, eg, decompress it.  @user is pointing to the
572  *              extension's private connection context data, @in is pointing
573  *              to an lws_tokens struct, it consists of a char * pointer called
574  *              token, and an int called token_len.  At entry, these are
575  *              set to point to the received buffer and set to the content
576  *              length.  If the extension will grow the content, it should use
577  *              a new buffer allocated in its private user context data and
578  *              set the pointed-to lws_tokens members to point to its buffer.
579  *
580  *      LWS_EXT_CALLBACK_PACKET_TX_PRESEND: this works the same way as
581  *              LWS_EXT_CALLBACK_PACKET_RX_PREPARSE above, except it gives the
582  *              extension a chance to change websocket data just before it will
583  *              be sent out.  Using the same lws_token pointer scheme in @in,
584  *              the extension can change the buffer and the length to be
585  *              transmitted how it likes.  Again if it wants to grow the
586  *              buffer safely, it should copy the data into its own buffer and
587  *              set the lws_tokens token pointer to it.
588  */
589 LWS_EXTERN int extension_callback(struct libwebsocket_context * context,
590                         struct libwebsocket_extension *ext,
591                         struct libwebsocket *wsi,
592                          enum libwebsocket_extension_callback_reasons reason, void *user,
593                                                           void *in, size_t len);
594
595 typedef int (extension_callback_function)(struct libwebsocket_context * context,
596                         struct libwebsocket_extension *ext,
597                         struct libwebsocket *wsi,
598                          enum libwebsocket_extension_callback_reasons reason, void *user,
599                                                           void *in, size_t len);
600
601 /**
602  * struct libwebsocket_protocols -      List of protocols and handlers server
603  *                                      supports.
604  * @name:       Protocol name that must match the one given in the client
605  *              Javascript new WebSocket(url, 'protocol') name
606  * @callback:   The service callback used for this protocol.  It allows the
607  *              service action for an entire protocol to be encapsulated in
608  *              the protocol-specific callback
609  * @per_session_data_size:      Each new connection using this protocol gets
610  *              this much memory allocated on connection establishment and
611  *              freed on connection takedown.  A pointer to this per-connection
612  *              allocation is passed into the callback in the 'user' parameter
613  * @owning_server:      the server init call fills in this opaque pointer when
614  *              registering this protocol with the server.
615  * @broadcast_socket_port: the server init call fills this in with the
616  *              localhost port number used to forward broadcasts for this
617  *              protocol
618  * @broadcast_socket_user_fd:  the server init call fills this in ... the main()
619  *              process context can write to this socket to perform broadcasts
620  *              (use the libwebsockets_broadcast() api to do this instead,
621  *              it works from any process context)
622  * @protocol_index: which protocol we are starting from zero
623  *
624  *      This structure represents one protocol supported by the server.  An
625  *      array of these structures is passed to libwebsocket_create_server()
626  *      allows as many protocols as you like to be handled by one server.
627  */
628
629 struct libwebsocket_protocols {
630         const char *name;
631         callback_function *callback;
632         size_t per_session_data_size;
633
634         /*
635          * below are filled in on server init and can be left uninitialized,
636          * no need for user to use them directly either
637          */
638
639         struct libwebsocket_context *owning_server;
640         int broadcast_socket_port;
641         int broadcast_socket_user_fd;
642         int protocol_index;
643 };
644
645 /**
646  * struct libwebsocket_extension -      An extension we know how to cope with
647  *
648  * @name:                       Formal extension name, eg, "deflate-stream"
649  * @callback:                   Service callback
650  * @per_session_data_size:      Libwebsockets will auto-malloc this much
651  *                              memory for the use of the extension, a pointer
652  *                              to it comes in the @user callback parameter
653  * @per_context_private_data:   Optional storage for this externsion that
654  *                              is per-context, so it can track stuff across
655  *                              all sessions, etc, if it wants
656  */
657
658 struct libwebsocket_extension {
659         const char *name;
660         extension_callback_function *callback;
661         size_t per_session_data_size;
662         void * per_context_private_data;
663 };
664
665 LWS_EXTERN
666 void lws_set_log_level(int level, void (*log_emit_function)(const char *line));
667
668 LWS_EXTERN struct libwebsocket_context *
669 libwebsocket_create_context(int port, const char * interf,
670                   struct libwebsocket_protocols *protocols,
671                   struct libwebsocket_extension *extensions,
672                   const char *ssl_cert_filepath,
673                   const char *ssl_private_key_filepath,
674                   const char *ssl_ca_filepath,
675                   int gid, int uid,
676                   unsigned int options, void *user);
677
678 LWS_EXTERN void
679 libwebsocket_context_destroy(struct libwebsocket_context *context);
680
681 LWS_EXTERN int
682 libwebsockets_fork_service_loop(struct libwebsocket_context *context);
683
684 LWS_EXTERN int
685 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms);
686
687 LWS_EXTERN int
688 libwebsocket_service_fd(struct libwebsocket_context *context,
689                                                          struct pollfd *pollfd);
690
691 LWS_EXTERN void *
692 libwebsocket_context_user(struct libwebsocket_context *context);
693
694 /*
695  * IMPORTANT NOTICE!
696  *
697  * When sending with websocket protocol (LWS_WRITE_TEXT or LWS_WRITE_BINARY)
698  * the send buffer has to have LWS_SEND_BUFFER_PRE_PADDING bytes valid BEFORE
699  * buf, and LWS_SEND_BUFFER_POST_PADDING bytes valid AFTER (buf + len).
700  *
701  * This allows us to add protocol info before and after the data, and send as
702  * one packet on the network without payload copying, for maximum efficiency.
703  *
704  * So for example you need this kind of code to use libwebsocket_write with a
705  * 128-byte payload
706  *
707  *   char buf[LWS_SEND_BUFFER_PRE_PADDING + 128 + LWS_SEND_BUFFER_POST_PADDING];
708  *
709  *   // fill your part of the buffer... for example here it's all zeros
710  *   memset(&buf[LWS_SEND_BUFFER_PRE_PADDING], 0, 128);
711  *
712  *   libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 128);
713  *
714  * When sending LWS_WRITE_HTTP, there is no protocol addition and you can just
715  * use the whole buffer without taking care of the above.
716  */
717
718 /*
719  * this is the frame nonce plus two header plus 8 length
720  *   there's an additional two for mux extension per mux nesting level
721  * 2 byte prepend on close will already fit because control frames cannot use
722  * the big length style
723  */
724
725 #define LWS_SEND_BUFFER_PRE_PADDING (4 + 10 + (2 * MAX_MUX_RECURSION))
726 #define LWS_SEND_BUFFER_POST_PADDING 4
727
728 LWS_EXTERN int
729 libwebsocket_write(struct libwebsocket *wsi, unsigned char *buf, size_t len,
730                                      enum libwebsocket_write_protocol protocol);
731
732 LWS_EXTERN int
733 libwebsockets_serve_http_file(struct libwebsocket *wsi, const char *file,
734                                                      const char *content_type);
735
736 /* notice - you need the pre- and post- padding allocation for buf below */
737
738 LWS_EXTERN int
739 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
740                                                 unsigned char *buf, size_t len);
741
742 LWS_EXTERN const struct libwebsocket_protocols *
743 libwebsockets_get_protocol(struct libwebsocket *wsi);
744
745 LWS_EXTERN int
746 libwebsocket_callback_on_writable(struct libwebsocket_context *context,
747                                                       struct libwebsocket *wsi);
748
749 LWS_EXTERN int
750 libwebsocket_callback_on_writable_all_protocol(
751                                  const struct libwebsocket_protocols *protocol);
752
753 LWS_EXTERN int
754 libwebsocket_get_socket_fd(struct libwebsocket *wsi);
755
756 LWS_EXTERN int
757 libwebsocket_is_final_fragment(struct libwebsocket *wsi);
758
759 LWS_EXTERN unsigned char
760 libwebsocket_get_reserved_bits(struct libwebsocket *wsi);
761
762 LWS_EXTERN void *
763 libwebsocket_ensure_user_space(struct libwebsocket *wsi);
764
765 LWS_EXTERN int
766 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable);
767
768 LWS_EXTERN size_t
769 libwebsockets_remaining_packet_payload(struct libwebsocket *wsi);
770
771 LWS_EXTERN struct libwebsocket *
772 libwebsocket_client_connect(struct libwebsocket_context *clients,
773                               const char *address,
774                               int port,
775                               int ssl_connection,
776                               const char *path,
777                               const char *host,
778                               const char *origin,
779                               const char *protocol,
780                               int ietf_version_or_minus_one);
781
782 LWS_EXTERN struct libwebsocket *
783 libwebsocket_client_connect_extended(struct libwebsocket_context *clients,
784                               const char *address,
785                               int port,
786                               int ssl_connection,
787                               const char *path,
788                               const char *host,
789                               const char *origin,
790                               const char *protocol,
791                               int ietf_version_or_minus_one,
792                               void *userdata);
793
794 LWS_EXTERN const char *
795 libwebsocket_canonical_hostname(struct libwebsocket_context *context);
796
797
798 LWS_EXTERN void
799 libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
800                                         char *rip, int rip_len);
801
802 LWS_EXTERN void
803 libwebsockets_hangup_on_client(struct libwebsocket_context *context, int fd);
804
805 LWS_EXTERN void
806 libwebsocket_close_and_free_session(struct libwebsocket_context *context,
807                                struct libwebsocket *wsi, enum lws_close_status);
808
809 LWS_EXTERN int
810 libwebsockets_get_random(struct libwebsocket_context *context,
811                                                             void *buf, int len);
812
813 LWS_EXTERN int
814 lws_send_pipe_choked(struct libwebsocket *wsi);
815
816 LWS_EXTERN unsigned char *
817 libwebsockets_SHA1(const unsigned char *d, size_t n, unsigned char *md);
818
819 LWS_EXTERN int
820 lws_b64_encode_string(const char *in, int in_len, char *out, int out_size);
821
822 LWS_EXTERN int
823 lws_b64_decode_string(const char *in, char *out, int out_size);
824
825 LWS_EXTERN struct libwebsocket_extension libwebsocket_internal_extensions[];
826
827 #ifdef __cplusplus
828 }
829 #endif
830
831 #endif