2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010 Andy Green <andy@warmcat.com>
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.
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.
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,
22 #ifndef __LIBWEBSOCKET_H__
23 #define __LIBWEBSOCKET_H__
27 #ifndef WIN32_LEAN_AND_MEAN
28 #define WIN32_LEAN_AND_MEAN
32 #include "websock-w32.h"
36 #include "gettimeofday.h"
42 #define CONTEXT_PORT_NO_LISTEN 0
45 enum libwebsocket_context_options {
46 LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK = 1,
47 LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT = 2,
50 enum libwebsocket_callback_reasons {
51 LWS_CALLBACK_ESTABLISHED,
52 LWS_CALLBACK_CLIENT_ESTABLISHED,
55 LWS_CALLBACK_CLIENT_RECEIVE,
56 LWS_CALLBACK_CLIENT_RECEIVE_PONG,
57 LWS_CALLBACK_CLIENT_WRITEABLE,
58 LWS_CALLBACK_SERVER_WRITEABLE,
60 LWS_CALLBACK_BROADCAST,
61 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
62 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
63 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
64 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
65 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
66 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
67 LWS_CALLBACK_CONFIRM_EXTENSION_OKAY,
68 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
69 /* external poll() management support */
70 LWS_CALLBACK_ADD_POLL_FD,
71 LWS_CALLBACK_DEL_POLL_FD,
72 LWS_CALLBACK_SET_MODE_POLL_FD,
73 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
76 enum libwebsocket_extension_callback_reasons {
77 LWS_EXT_CALLBACK_CONSTRUCT,
78 LWS_EXT_CALLBACK_CLIENT_CONSTRUCT,
79 LWS_EXT_CALLBACK_DESTROY,
80 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE,
81 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
82 LWS_EXT_CALLBACK_FLUSH_PENDING_TX,
85 enum libwebsocket_write_protocol {
88 LWS_WRITE_CONTINUATION,
91 /* special 04+ opcodes */
99 LWS_WRITE_NO_FIN = 0x40,
101 * client packet payload goes out on wire unmunged
102 * only useful for security tests since normal servers cannot
103 * decode the content if used
105 LWS_WRITE_CLIENT_IGNORE_XOR_MASK = 0x80
109 * you need these to look at headers that have been parsed if using the
110 * LWS_CALLBACK_FILTER_CONNECTION callback. If a header from the enum
111 * list below is absent, .token = NULL and token_len = 0. Otherwise .token
112 * points to .token_len chars containing that header content.
120 enum lws_token_indexes {
123 WSI_TOKEN_CONNECTION,
138 WSI_TOKEN_EXTENSIONS,
140 /* client receives these */
145 /* always last real token index*/
147 /* parser state additions */
150 WSI_TOKEN_SKIPPING_SAW_CR,
158 1000 indicates a normal closure, meaning whatever purpose the
159 connection was established for has been fulfilled.
163 1001 indicates that an endpoint is "going away", such as a server
164 going down, or a browser having navigated away from a page.
168 1002 indicates that an endpoint is terminating the connection due
173 1003 indicates that an endpoint is terminating the connection
174 because it has received a type of data it cannot accept (e.g. an
175 endpoint that understands only text data may send this if it
176 receives a binary message.)
180 1004 indicates that an endpoint is terminating the connection
181 because it has received a message that is too large.
184 enum lws_close_status {
185 LWS_CLOSE_STATUS_NOSTATUS = 0,
186 LWS_CLOSE_STATUS_NORMAL = 1000,
187 LWS_CLOSE_STATUS_GOINGAWAY = 1001,
188 LWS_CLOSE_STATUS_PROTOCOL_ERR = 1002,
189 LWS_CLOSE_STATUS_UNACCEPTABLE_OPCODE = 1003,
190 LWS_CLOSE_STATUS_PAYLOAD_TOO_LARGE = 1004,
194 struct libwebsocket_context;
195 struct libwebsocket_extension;
197 /* document the generic callback (it's a fake prototype under this) */
199 * callback() - User server actions
200 * @context: Websockets context
201 * @wsi: Opaque websocket instance pointer
202 * @reason: The reason for the call
203 * @user: Pointer to per-session user data allocated by library
204 * @in: Pointer used for some callback reasons
205 * @len: Length set for some callback reasons
207 * This callback is the way the user controls what is served. All the
208 * protocol detail is hidden and handled by the library.
210 * For each connection / session there is user data allocated that is
211 * pointed to by "user". You set the size of this user data area when
212 * the library is initialized with libwebsocket_create_server.
214 * You get an opportunity to initialize user data when called back with
215 * LWS_CALLBACK_ESTABLISHED reason.
217 * LWS_CALLBACK_ESTABLISHED: after the server completes a handshake with
220 * LWS_CALLBACK_CLIENT_ESTABLISHED: after your client connection completed
221 * a handshake with the remote server
223 * LWS_CALLBACK_CLOSED: when the websocket session ends
225 * LWS_CALLBACK_BROADCAST: signal to send to client (you would use
226 * libwebsocket_write() taking care about the
227 * special buffer requirements
229 * LWS_CALLBACK_RECEIVE: data has appeared for this server endpoint from a
230 * remote client, it can be found at *in and is
233 * LWS_CALLBACK_CLIENT_RECEIVE_PONG: if you elected to see PONG packets,
234 * they appear with this callback reason. PONG
235 * packets only exist in 04+ protocol
237 * LWS_CALLBACK_CLIENT_RECEIVE: data has appeared from the server for the
238 * client connection, it can be found at *in and
241 * LWS_CALLBACK_HTTP: an http request has come from a client that is not
242 * asking to upgrade the connection to a websocket
243 * one. This is a chance to serve http content,
244 * for example, to send a script to the client
245 * which will then open the websockets connection.
246 * @in points to the URI path requested and
247 * libwebsockets_serve_http_file() makes it very
248 * simple to send back a file to the client.
250 * LWS_CALLBACK_CLIENT_WRITEABLE:
251 * LWS_CALLBACK_SERVER_WRITEABLE: If you call
252 * libwebsocket_callback_on_writable() on a connection, you will
253 * get one of these callbacks coming when the connection socket
254 * is able to accept another write packet without blocking.
255 * If it already was able to take another packet without blocking,
256 * you'll get this callback at the next call to the service loop
257 * function. Notice that CLIENTs get LWS_CALLBACK_CLIENT_WRITEABLE
258 * and servers get LWS_CALLBACK_SERVER_WRITEABLE.
260 * LWS_CALLBACK_FILTER_NETWORK_CONNECTION: called when a client connects to
261 * the server at network level; the connection is accepted but then
262 * passed to this callback to decide whether to hang up immediately
263 * or not, based on the client IP. @user contains the connection
264 * socket's descriptor. Return non-zero to terminate
265 * the connection before sending or receiving anything.
266 * Because this happens immediately after the network connection
267 * from the client, there's no websocket protocol selected yet so
268 * this callback is issued only to protocol 0.
270 * LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION: called when the handshake has
271 * been received and parsed from the client, but the response is
272 * not sent yet. Return non-zero to disallow the connection.
273 * @user is a pointer to an array of struct lws_tokens, you can
274 * use the header enums lws_token_indexes from libwebsockets.h
275 * to check for and read the supported header presence and
276 * content before deciding to allow the handshake to proceed or
277 * to kill the connection.
279 * LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS: if configured for
280 * including OpenSSL support, this callback allows your user code
281 * to perform extra SSL_CTX_load_verify_locations() or similar
282 * calls to direct OpenSSL where to find certificates the client
283 * can use to confirm the remote server identity. @user is the
286 * LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS: if configured for
287 * including OpenSSL support, this callback allows your user code
288 * to load extra certifcates into the server which allow it to
289 * verify the validity of certificates returned by clients. @user
290 * is the server's OpenSSL SSL_CTX*
292 * LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION: if the
293 * libwebsockets context was created with the option
294 * LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT, then this
295 * callback is generated during OpenSSL verification of the cert
296 * sent from the client. It is sent to protocol[0] callback as
297 * no protocol has been negotiated on the connection yet.
298 * Notice that the libwebsockets context and wsi are both NULL
299 * during this callback. See
300 * http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html
301 * to understand more detail about the OpenSSL callback that
302 * generates this libwebsockets callback and the meanings of the
303 * arguments passed. In this callback, @user is the x509_ctx,
304 * @in is the ssl pointer and @len is preverify_ok
305 * Notice that this callback maintains libwebsocket return
306 * conventions, return 0 to mean the cert is OK or 1 to fail it.
307 * This also means that if you don't handle this callback then
308 * the default callback action of returning 0 allows the client
311 * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER: this callback happens
312 * when a client handshake is being compiled. @user is NULL,
313 * @in is a char **, it's pointing to a char * which holds the
314 * next location in the header buffer where you can add
315 * headers, and @len is the remaining space in the header buffer,
316 * which is typically some hundreds of bytes. So, to add a canned
317 * cookie, your handler code might look similar to:
319 * char **p = (char **)in;
324 * *p += sprintf(*p, "Cookie: a=b\x0d\x0a");
328 * Notice if you add anything, you just have to take care about
329 * the CRLF on the line you added. Obviously this callback is
330 * optional, if you don't handle it everything is fine.
332 * Notice the callback is coming to protocols[0] all the time,
333 * because there is no specific protocol handshook yet.
335 * LWS_CALLBACK_CONFIRM_EXTENSION_OKAY: When the server handshake code
336 * sees that it does support a requested extension, before
337 * accepting the extension by additing to the list sent back to
338 * the client it gives this callback just to check that it's okay
339 * to use that extension. It calls back to the requested protocol
340 * and with @in being the extension name, @len is 0 and @user is
341 * valid. Note though at this time the ESTABLISHED callback hasn't
342 * happened yet so if you initialize @user content there, @user
343 * content during this callback might not be useful for anything.
344 * Notice this callback comes to protocols[0].
346 * LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED: When a client
347 * connection is being prepared to start a handshake to a server,
348 * each supported extension is checked with protocols[0] callback
349 * with this reason, giving the user code a chance to suppress the
350 * claim to support that extension by returning non-zero. If
351 * unhandled, by default 0 will be returned and the extension
352 * support included in the header to the server. Notice this
353 * callback comes to protocols[0].
355 * The next four reasons are optional and only need taking care of if you
356 * will be integrating libwebsockets sockets into an external polling
359 * LWS_CALLBACK_ADD_POLL_FD: libwebsocket deals with its poll() loop
360 * internally, but in the case you are integrating with another
361 * server you will need to have libwebsocket sockets share a
362 * polling array with the other server. This and the other
363 * POLL_FD related callbacks let you put your specialized
364 * poll array interface code in the callback for protocol 0, the
365 * first protocol you support, usually the HTTP protocol in the
366 * serving case. This callback happens when a socket needs to be
367 * added to the polling loop: @user contains the fd, and
368 * @len is the events bitmap (like, POLLIN). If you are using the
369 * internal polling loop (the "service" callback), you can just
370 * ignore these callbacks.
372 * LWS_CALLBACK_DEL_POLL_FD: This callback happens when a socket descriptor
373 * needs to be removed from an external polling array. @user is
374 * the socket desricptor. If you are using the internal polling
375 * loop, you can just ignore it.
377 * LWS_CALLBACK_SET_MODE_POLL_FD: This callback happens when libwebsockets
378 * wants to modify the events for the socket descriptor in @user.
379 * The handler should OR @len on to the events member of the pollfd
380 * struct for this socket descriptor. If you are using the
381 * internal polling loop, you can just ignore it.
383 * LWS_CALLBACK_CLEAR_MODE_POLL_FD: This callback occurs when libwebsockets
384 * wants to modify the events for the socket descriptor in @user.
385 * The handler should AND ~@len on to the events member of the
386 * pollfd struct for this socket descriptor. If you are using the
387 * internal polling loop, you can just ignore it.
389 extern int callback(struct libwebsocket_context * context,
390 struct libwebsocket *wsi,
391 enum libwebsocket_callback_reasons reason, void *user,
392 void *in, size_t len);
394 /* document the generic extension callback (it's a fake prototype under this) */
396 * extension_callback() - Hooks to allow extensions to operate
397 * @context: Websockets context
398 * @ext: This extension
399 * @wsi: Opaque websocket instance pointer
400 * @reason: The reason for the call
401 * @user: Pointer to per-session user data allocated by library
402 * @in: Pointer used for some callback reasons
403 * @len: Length set for some callback reasons
405 * Each extension that is active on a particular connection receives
406 * callbacks during the connection lifetime to allow the extension to
407 * operate on websocket data and manage itself.
409 * Libwebsockets takes care of allocating and freeing "user" memory for
410 * each active extension on each connection. That is what is pointed to
411 * by the @user parameter.
413 * LWS_EXT_CALLBACK_CONSTRUCT: called when the server has decided to
414 * select this extension from the list provided by the client,
415 * just before the server will send back the handshake accepting
416 * the connection with this extension active. This gives the
417 * extension a chance to initialize its connection context found
420 * LWS_EXT_CALLBACK_CLIENT_CONSTRUCT: same as LWS_EXT_CALLBACK_CONSTRUCT
421 * but called when client is instantiating this extension. Some
422 * extensions will work the same on client and server side and then
423 * you can just merge handlers for both CONSTRUCTS.
425 * LWS_EXT_CALLBACK_DESTROY: called when the connection the extension was
426 * being used on is about to be closed and deallocated. It's the
427 * last chance for the extension to deallocate anything it has
428 * allocated in the user data (pointed to by @user) before the
429 * user data is deleted. This same callback is used whether you
430 * are in client or server instantiation context.
432 * LWS_EXT_CALLBACK_PACKET_RX_PREPARSE: when this extension was active on
433 * a connection, and a packet of data arrived at the connection,
434 * it is passed to this callback to give the extension a chance to
435 * change the data, eg, decompress it. @user is pointing to the
436 * extension's private connection context data, @in is pointing
437 * to an lws_tokens struct, it consists of a char * pointer called
438 * token, and an int called token_len. At entry, these are
439 * set to point to the received buffer and set to the content
440 * length. If the extension will grow the content, it should use
441 * a new buffer allocated in its private user context data and
442 * set the pointed-to lws_tokens members to point to its buffer.
444 * LWS_EXT_CALLBACK_PACKET_TX_PRESEND: this works the same way as
445 * LWS_EXT_CALLBACK_PACKET_RX_PREPARSE above, except it gives the
446 * extension a chance to change websocket data just before it will
447 * be sent out. Using the same lws_token pointer scheme in @in,
448 * the extension can change the buffer and the length to be
449 * transmitted how it likes. Again if it wants to grow the
450 * buffer safely, it should copy the data into its own buffer and
451 * set the lws_tokens token pointer to it.
454 extern int extension_callback(struct libwebsocket_context * context,
455 struct libwebsocket_extension *ext,
456 struct libwebsocket *wsi,
457 enum libwebsocket_callback_reasons reason, void *user,
458 void *in, size_t len);
462 * struct libwebsocket_protocols - List of protocols and handlers server
464 * @name: Protocol name that must match the one given in the client
465 * Javascript new WebSocket(url, 'protocol') name
466 * @callback: The service callback used for this protocol. It allows the
467 * service action for an entire protocol to be encapsulated in
468 * the protocol-specific callback
469 * @per_session_data_size: Each new connection using this protocol gets
470 * this much memory allocated on connection establishment and
471 * freed on connection takedown. A pointer to this per-connection
472 * allocation is passed into the callback in the 'user' parameter
473 * @owning_server: the server init call fills in this opaque pointer when
474 * registering this protocol with the server.
475 * @broadcast_socket_port: the server init call fills this in with the
476 * localhost port number used to forward broadcasts for this
478 * @broadcast_socket_user_fd: the server init call fills this in ... the main()
479 * process context can write to this socket to perform broadcasts
480 * (use the libwebsockets_broadcast() api to do this instead,
481 * it works from any process context)
482 * @protocol_index: which protocol we are starting from zero
484 * This structure represents one protocol supported by the server. An
485 * array of these structures is passed to libwebsocket_create_server()
486 * allows as many protocols as you like to be handled by one server.
489 struct libwebsocket_protocols {
491 int (*callback)(struct libwebsocket_context * context,
492 struct libwebsocket *wsi,
493 enum libwebsocket_callback_reasons reason, void *user,
494 void *in, size_t len);
495 size_t per_session_data_size;
498 * below are filled in on server init and can be left uninitialized,
499 * no need for user to use them directly either
502 struct libwebsocket_context *owning_server;
503 int broadcast_socket_port;
504 int broadcast_socket_user_fd;
509 * struct libwebsocket_extension - An extension we know how to cope with
511 * @name: Formal extension name, eg, "deflate-stream"
512 * @callback: Service callback
513 * @per_session_data_size: Libwebsockets will auto-malloc this much
514 * memory for the use of the extension, a pointer
515 * to it comes in the @user callback parameter
518 struct libwebsocket_extension {
520 int (*callback)(struct libwebsocket_context *context,
521 struct libwebsocket_extension *ext,
522 struct libwebsocket *wsi,
523 enum libwebsocket_extension_callback_reasons reason,
524 void *user, void *in, size_t len);
525 size_t per_session_data_size;
530 extern struct libwebsocket_context *
531 libwebsocket_create_context(int port, const char * interf,
532 struct libwebsocket_protocols *protocols,
533 struct libwebsocket_extension *extensions,
534 const char *ssl_cert_filepath,
535 const char *ssl_private_key_filepath, int gid, int uid,
536 unsigned int options);
539 libwebsocket_context_destroy(struct libwebsocket_context *context);
542 libwebsockets_fork_service_loop(struct libwebsocket_context *context);
545 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms);
548 libwebsocket_service_fd(struct libwebsocket_context *context,
549 struct pollfd *pollfd);
554 * When sending with websocket protocol (LWS_WRITE_TEXT or LWS_WRITE_BINARY)
555 * the send buffer has to have LWS_SEND_BUFFER_PRE_PADDING bytes valid BEFORE
556 * buf, and LWS_SEND_BUFFER_POST_PADDING bytes valid AFTER (buf + len).
558 * This allows us to add protocol info before and after the data, and send as
559 * one packet on the network without payload copying, for maximum efficiency.
561 * So for example you need this kind of code to use libwebsocket_write with a
564 * char buf[LWS_SEND_BUFFER_PRE_PADDING + 128 + LWS_SEND_BUFFER_POST_PADDING];
566 * // fill your part of the buffer... for example here it's all zeros
567 * memset(&buf[LWS_SEND_BUFFER_PRE_PADDING], 0, 128);
569 * libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 128);
571 * When sending LWS_WRITE_HTTP, there is no protocol addition and you can just
572 * use the whole buffer without taking care of the above.
576 * this is the frame nonce plus two header plus 8 length
577 * 2 byte prepend on close will already fit because control frames cannot use
578 * the big length style
581 #define LWS_SEND_BUFFER_PRE_PADDING (4 + 10)
582 #define LWS_SEND_BUFFER_POST_PADDING 1
585 libwebsocket_write(struct libwebsocket *wsi, unsigned char *buf, size_t len,
586 enum libwebsocket_write_protocol protocol);
589 libwebsockets_serve_http_file(struct libwebsocket *wsi, const char *file,
590 const char *content_type);
592 /* notice - you need the pre- and post- padding allocation for buf below */
595 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
596 unsigned char *buf, size_t len);
598 extern const struct libwebsocket_protocols *
599 libwebsockets_get_protocol(struct libwebsocket *wsi);
602 libwebsocket_callback_on_writable(struct libwebsocket_context *context,
603 struct libwebsocket *wsi);
606 libwebsocket_callback_on_writable_all_protocol(
607 const struct libwebsocket_protocols *protocol);
610 libwebsocket_get_socket_fd(struct libwebsocket *wsi);
613 libwebsocket_is_final_fragment(struct libwebsocket *wsi);
616 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable);
619 libwebsockets_remaining_packet_payload(struct libwebsocket *wsi);
621 extern struct libwebsocket *
622 libwebsocket_client_connect(struct libwebsocket_context *clients,
629 const char *protocol,
630 int ietf_version_or_minus_one);
633 libwebsocket_canonical_hostname(struct libwebsocket_context *context);
637 libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
638 char *rip, int rip_len);
641 libwebsockets_hangup_on_client(struct libwebsocket_context *context, int fd);
644 libwebsocket_close_and_free_session(struct libwebsocket_context *context,
645 struct libwebsocket *wsi, enum lws_close_status);
648 libwebsockets_get_random(struct libwebsocket_context *context,
652 lws_send_pipe_choked(struct libwebsocket *wsi);
654 extern unsigned char *
655 libwebsockets_SHA1(const unsigned char *d, size_t n, unsigned char *md);
658 lws_b64_encode_string(const char *in, int in_len, char *out, int out_size);
661 lws_b64_decode_string(const char *in, char *out, int out_size);
663 extern struct libwebsocket_extension libwebsocket_internal_extensions[];