2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010-2013 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_3060898B846849FF9F88F5DB59B5950C
23 #define LIBWEBSOCKET_H_3060898B846849FF9F88F5DB59B5950C
30 #if defined(WIN32) || defined(_WIN32)
32 #ifndef WIN32_LEAN_AND_MEAN
33 #define WIN32_LEAN_AND_MEAN
39 #include "websock-w32.h"
41 #include "gettimeofday.h"
43 #define strcasecmp stricmp
44 #define getdtablesize() 30000
49 typedef SSIZE_T ssize_t;
57 #define LWS_EXTERN extern __declspec(dllexport)
59 #define LWS_EXTERN extern __declspec(dllimport)
70 #define LWS_VISIBLE __attribute__((visibility("default")))
80 #define LWS_EXTERN extern
83 #define CONTEXT_PORT_NO_LISTEN 0
84 #define MAX_MUX_RECURSION 2
98 LLL_COUNT = 10 /* set to count of valid flags */
101 LWS_VISIBLE LWS_EXTERN void _lws_log(int filter, const char *format, ...);
103 /* notice, warn and log are always compiled in */
104 #define lwsl_notice(...) _lws_log(LLL_NOTICE, __VA_ARGS__)
105 #define lwsl_warn(...) _lws_log(LLL_WARN, __VA_ARGS__)
106 #define lwsl_err(...) _lws_log(LLL_ERR, __VA_ARGS__)
108 * weaker logging can be deselected at configure time using --disable-debug
109 * that gets rid of the overhead of checking while keeping _warn and _err
114 #define lwsl_info(...) _lws_log(LLL_INFO, __VA_ARGS__)
115 #define lwsl_debug(...) _lws_log(LLL_DEBUG, __VA_ARGS__)
116 #define lwsl_parser(...) _lws_log(LLL_PARSER, __VA_ARGS__)
117 #define lwsl_header(...) _lws_log(LLL_HEADER, __VA_ARGS__)
118 #define lwsl_ext(...) _lws_log(LLL_EXT, __VA_ARGS__)
119 #define lwsl_client(...) _lws_log(LLL_CLIENT, __VA_ARGS__)
120 #define lwsl_latency(...) _lws_log(LLL_LATENCY, __VA_ARGS__)
121 LWS_VISIBLE LWS_EXTERN void lwsl_hexdump(void *buf, size_t len);
125 #define lwsl_info(...)
126 #define lwsl_debug(...)
127 #define lwsl_parser(...)
128 #define lwsl_header(...)
129 #define lwsl_ext(...)
130 #define lwsl_client(...)
131 #define lwsl_latency(...)
132 #define lwsl_hexdump(a, b)
136 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
138 enum libwebsocket_context_options {
139 LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT = 2,
140 LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME = 4,
141 LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT = 8
144 enum libwebsocket_callback_reasons {
145 LWS_CALLBACK_ESTABLISHED,
146 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
147 LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH,
148 LWS_CALLBACK_CLIENT_ESTABLISHED,
150 LWS_CALLBACK_CLOSED_HTTP,
151 LWS_CALLBACK_RECEIVE,
152 LWS_CALLBACK_CLIENT_RECEIVE,
153 LWS_CALLBACK_CLIENT_RECEIVE_PONG,
154 LWS_CALLBACK_CLIENT_WRITEABLE,
155 LWS_CALLBACK_SERVER_WRITEABLE,
157 LWS_CALLBACK_HTTP_BODY,
158 LWS_CALLBACK_HTTP_BODY_COMPLETION,
159 LWS_CALLBACK_HTTP_FILE_COMPLETION,
160 LWS_CALLBACK_HTTP_WRITEABLE,
161 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
162 LWS_CALLBACK_FILTER_HTTP_CONNECTION,
163 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
164 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
165 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
166 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
167 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
168 LWS_CALLBACK_CONFIRM_EXTENSION_OKAY,
169 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
170 LWS_CALLBACK_PROTOCOL_INIT,
171 LWS_CALLBACK_PROTOCOL_DESTROY,
172 /* external poll() management support */
173 LWS_CALLBACK_ADD_POLL_FD,
174 LWS_CALLBACK_DEL_POLL_FD,
175 LWS_CALLBACK_SET_MODE_POLL_FD,
176 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
179 #ifndef LWS_NO_EXTENSIONS
180 enum libwebsocket_extension_callback_reasons {
181 LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT,
182 LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT,
183 LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT,
184 LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT,
185 LWS_EXT_CALLBACK_CONSTRUCT,
186 LWS_EXT_CALLBACK_CLIENT_CONSTRUCT,
187 LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE,
188 LWS_EXT_CALLBACK_CHECK_OK_TO_PROPOSE_EXTENSION,
189 LWS_EXT_CALLBACK_DESTROY,
190 LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING,
191 LWS_EXT_CALLBACK_ANY_WSI_ESTABLISHED,
192 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE,
193 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
194 LWS_EXT_CALLBACK_PACKET_TX_DO_SEND,
195 LWS_EXT_CALLBACK_HANDSHAKE_REPLY_TX,
196 LWS_EXT_CALLBACK_FLUSH_PENDING_TX,
197 LWS_EXT_CALLBACK_EXTENDED_PAYLOAD_RX,
198 LWS_EXT_CALLBACK_CAN_PROXY_CLIENT_CONNECTION,
199 LWS_EXT_CALLBACK_1HZ,
200 LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE,
201 LWS_EXT_CALLBACK_IS_WRITEABLE,
202 LWS_EXT_CALLBACK_PAYLOAD_TX,
203 LWS_EXT_CALLBACK_PAYLOAD_RX,
207 enum libwebsocket_write_protocol {
210 LWS_WRITE_CONTINUATION,
213 /* special 04+ opcodes */
221 LWS_WRITE_NO_FIN = 0x40,
223 * client packet payload goes out on wire unmunged
224 * only useful for security tests since normal servers cannot
225 * decode the content if used
227 LWS_WRITE_CLIENT_IGNORE_XOR_MASK = 0x80
231 * you need these to look at headers that have been parsed if using the
232 * LWS_CALLBACK_FILTER_CONNECTION callback. If a header from the enum
233 * list below is absent, .token = NULL and token_len = 0. Otherwise .token
234 * points to .token_len chars containing that header content.
242 enum lws_token_indexes {
246 WSI_TOKEN_CONNECTION,
261 WSI_TOKEN_EXTENSIONS,
263 /* client receives these */
269 WSI_TOKEN_HTTP_ACCEPT,
270 WSI_TOKEN_HTTP_IF_MODIFIED_SINCE,
271 WSI_TOKEN_HTTP_ACCEPT_ENCODING,
272 WSI_TOKEN_HTTP_ACCEPT_LANGUAGE,
273 WSI_TOKEN_HTTP_PRAGMA,
274 WSI_TOKEN_HTTP_CACHE_CONTROL,
275 WSI_TOKEN_HTTP_AUTHORIZATION,
276 WSI_TOKEN_HTTP_COOKIE,
277 WSI_TOKEN_HTTP_CONTENT_LENGTH,
278 WSI_TOKEN_HTTP_CONTENT_TYPE,
280 WSI_TOKEN_HTTP_RANGE,
281 WSI_TOKEN_HTTP_REFERER,
282 WSI_TOKEN_HTTP_URI_ARGS,
287 /* use token storage to stash these */
289 _WSI_TOKEN_CLIENT_SENT_PROTOCOLS,
290 _WSI_TOKEN_CLIENT_PEER_ADDRESS,
291 _WSI_TOKEN_CLIENT_URI,
292 _WSI_TOKEN_CLIENT_HOST,
293 _WSI_TOKEN_CLIENT_ORIGIN,
295 /* always last real token index*/
297 /* parser state additions */
300 WSI_TOKEN_SKIPPING_SAW_CR,
301 WSI_PARSING_COMPLETE,
302 WSI_INIT_TOKEN_MUXURL,
309 1000 indicates a normal closure, meaning that the purpose for
310 which the connection was established has been fulfilled.
314 1001 indicates that an endpoint is "going away", such as a server
315 going down or a browser having navigated away from a page.
319 1002 indicates that an endpoint is terminating the connection due
324 1003 indicates that an endpoint is terminating the connection
325 because it has received a type of data it cannot accept (e.g., an
326 endpoint that understands only text data MAY send this if it
327 receives a binary message).
331 Reserved. The specific meaning might be defined in the future.
335 1005 is a reserved value and MUST NOT be set as a status code in a
336 Close control frame by an endpoint. It is designated for use in
337 applications expecting a status code to indicate that no status
338 code was actually present.
342 1006 is a reserved value and MUST NOT be set as a status code in a
343 Close control frame by an endpoint. It is designated for use in
344 applications expecting a status code to indicate that the
345 connection was closed abnormally, e.g., without sending or
346 receiving a Close control frame.
350 1007 indicates that an endpoint is terminating the connection
351 because it has received data within a message that was not
352 consistent with the type of the message (e.g., non-UTF-8 [RFC3629]
353 data within a text message).
357 1008 indicates that an endpoint is terminating the connection
358 because it has received a message that violates its policy. This
359 is a generic status code that can be returned when there is no
360 other more suitable status code (e.g., 1003 or 1009) or if there
361 is a need to hide specific details about the policy.
365 1009 indicates that an endpoint is terminating the connection
366 because it has received a message that is too big for it to
371 1010 indicates that an endpoint (client) is terminating the
372 connection because it has expected the server to negotiate one or
373 more extension, but the server didn't return them in the response
374 message of the WebSocket handshake. The list of extensions that
375 are needed SHOULD appear in the /reason/ part of the Close frame.
376 Note that this status code is not used by the server, because it
377 can fail the WebSocket handshake instead.
381 1011 indicates that a server is terminating the connection because
382 it encountered an unexpected condition that prevented it from
383 fulfilling the request.
387 1015 is a reserved value and MUST NOT be set as a status code in a
388 Close control frame by an endpoint. It is designated for use in
389 applications expecting a status code to indicate that the
390 connection was closed due to a failure to perform a TLS handshake
391 (e.g., the server certificate can't be verified).
394 enum lws_close_status {
395 LWS_CLOSE_STATUS_NOSTATUS = 0,
396 LWS_CLOSE_STATUS_NORMAL = 1000,
397 LWS_CLOSE_STATUS_GOINGAWAY = 1001,
398 LWS_CLOSE_STATUS_PROTOCOL_ERR = 1002,
399 LWS_CLOSE_STATUS_UNACCEPTABLE_OPCODE = 1003,
400 LWS_CLOSE_STATUS_RESERVED = 1004,
401 LWS_CLOSE_STATUS_NO_STATUS = 1005,
402 LWS_CLOSE_STATUS_ABNORMAL_CLOSE = 1006,
403 LWS_CLOSE_STATUS_INVALID_PAYLOAD = 1007,
404 LWS_CLOSE_STATUS_POLICY_VIOLATION = 1008,
405 LWS_CLOSE_STATUS_MESSAGE_TOO_LARGE = 1009,
406 LWS_CLOSE_STATUS_EXTENSION_REQUIRED = 1010,
407 LWS_CLOSE_STATUS_UNEXPECTED_CONDITION = 1011,
408 LWS_CLOSE_STATUS_TLS_FAILURE = 1015,
412 HTTP_STATUS_OK = 200,
414 HTTP_STATUS_BAD_REQUEST = 400,
415 HTTP_STATUS_UNAUTHORIZED,
416 HTTP_STATUS_PAYMENT_REQUIRED,
417 HTTP_STATUS_FORBIDDEN,
418 HTTP_STATUS_NOT_FOUND,
419 HTTP_STATUS_METHOD_NOT_ALLOWED,
420 HTTP_STATUS_NOT_ACCEPTABLE,
421 HTTP_STATUS_PROXY_AUTH_REQUIRED,
422 HTTP_STATUS_REQUEST_TIMEOUT,
423 HTTP_STATUS_CONFLICT,
425 HTTP_STATUS_LENGTH_REQUIRED,
426 HTTP_STATUS_PRECONDITION_FAILED,
427 HTTP_STATUS_REQ_ENTITY_TOO_LARGE,
428 HTTP_STATUS_REQ_URI_TOO_LONG,
429 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE,
430 HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE,
431 HTTP_STATUS_EXPECTATION_FAILED,
433 HTTP_STATUS_INTERNAL_SERVER_ERROR = 500,
434 HTTP_STATUS_NOT_IMPLEMENTED,
435 HTTP_STATUS_BAD_GATEWAY,
436 HTTP_STATUS_SERVICE_UNAVAILABLE,
437 HTTP_STATUS_GATEWAY_TIMEOUT,
438 HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED,
442 struct libwebsocket_context;
443 /* needed even with extensions disabled for create context */
444 struct libwebsocket_extension;
447 * callback_function() - User server actions
448 * @context: Websockets context
449 * @wsi: Opaque websocket instance pointer
450 * @reason: The reason for the call
451 * @user: Pointer to per-session user data allocated by library
452 * @in: Pointer used for some callback reasons
453 * @len: Length set for some callback reasons
455 * This callback is the way the user controls what is served. All the
456 * protocol detail is hidden and handled by the library.
458 * For each connection / session there is user data allocated that is
459 * pointed to by "user". You set the size of this user data area when
460 * the library is initialized with libwebsocket_create_server.
462 * You get an opportunity to initialize user data when called back with
463 * LWS_CALLBACK_ESTABLISHED reason.
465 * LWS_CALLBACK_ESTABLISHED: after the server completes a handshake with
468 * LWS_CALLBACK_CLIENT_CONNECTION_ERROR: the request client connection has
469 * been unable to complete a handshake with the remote server
471 * LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH: this is the last chance for the
472 * client user code to examine the http headers
473 * and decide to reject the connection. If the
474 * content in the headers is interesting to the
475 * client (url, etc) it needs to copy it out at
476 * this point since it will be destroyed before
477 * the CLIENT_ESTABLISHED call
479 * LWS_CALLBACK_CLIENT_ESTABLISHED: after your client connection completed
480 * a handshake with the remote server
482 * LWS_CALLBACK_CLOSED: when the websocket session ends
484 * LWS_CALLBACK_CLOSED_HTTP: when a HTTP (non-websocket) session ends
486 * LWS_CALLBACK_RECEIVE: data has appeared for this server endpoint from a
487 * remote client, it can be found at *in and is
490 * LWS_CALLBACK_CLIENT_RECEIVE_PONG: if you elected to see PONG packets,
491 * they appear with this callback reason. PONG
492 * packets only exist in 04+ protocol
494 * LWS_CALLBACK_CLIENT_RECEIVE: data has appeared from the server for the
495 * client connection, it can be found at *in and
498 * LWS_CALLBACK_HTTP: an http request has come from a client that is not
499 * asking to upgrade the connection to a websocket
500 * one. This is a chance to serve http content,
501 * for example, to send a script to the client
502 * which will then open the websockets connection.
503 * @in points to the URI path requested and
504 * libwebsockets_serve_http_file() makes it very
505 * simple to send back a file to the client.
506 * Normally after sending the file you are done
507 * with the http connection, since the rest of the
508 * activity will come by websockets from the script
509 * that was delivered by http, so you will want to
510 * return 1; to close and free up the connection.
511 * That's important because it uses a slot in the
512 * total number of client connections allowed set
515 * LWS_CALLBACK_HTTP_BODY: the next @len bytes data from the http
516 * request body HTTP connection is now available in @in.
518 * LWS_CALLBACK_HTTP_BODY_COMPLETION: the expected amount of http request
519 * body has been delivered
521 * LWS_CALLBACK_HTTP_WRITEABLE: you can write more down the http protocol
524 * LWS_CALLBACK_HTTP_FILE_COMPLETION: a file requested to be send down
525 * http link has completed.
527 * LWS_CALLBACK_CLIENT_WRITEABLE:
528 * LWS_CALLBACK_SERVER_WRITEABLE: If you call
529 * libwebsocket_callback_on_writable() on a connection, you will
530 * get one of these callbacks coming when the connection socket
531 * is able to accept another write packet without blocking.
532 * If it already was able to take another packet without blocking,
533 * you'll get this callback at the next call to the service loop
534 * function. Notice that CLIENTs get LWS_CALLBACK_CLIENT_WRITEABLE
535 * and servers get LWS_CALLBACK_SERVER_WRITEABLE.
537 * LWS_CALLBACK_FILTER_NETWORK_CONNECTION: called when a client connects to
538 * the server at network level; the connection is accepted but then
539 * passed to this callback to decide whether to hang up immediately
540 * or not, based on the client IP. @in contains the connection
541 * socket's descriptor. Return non-zero to terminate
542 * the connection before sending or receiving anything.
543 * Because this happens immediately after the network connection
544 * from the client, there's no websocket protocol selected yet so
545 * this callback is issued only to protocol 0.
547 * LWS_CALLBACK_FILTER_HTTP_CONNECTION: called when the request has
548 * been received and parsed from the client, but the response is
549 * not sent yet. Return non-zero to disallow the connection.
550 * @user is a pointer to the connection user space allocation,
551 * @in is the URI, eg, "/"
552 * In your handler you can use the public APIs
553 * lws_hdr_total_length() / lws_hdr_copy() to access all of the
554 * headers using the header enums lws_token_indexes from
555 * libwebsockets.h to check for and read the supported header
556 * presence and content before deciding to allow the http
557 * connection to proceed or to kill the connection.
559 * LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION: called when the handshake has
560 * been received and parsed from the client, but the response is
561 * not sent yet. Return non-zero to disallow the connection.
562 * @user is a pointer to the connection user space allocation,
563 * @in is the requested protocol name
564 * In your handler you can use the public APIs
565 * lws_hdr_total_length() / lws_hdr_copy() to access all of the
566 * headers using the header enums lws_token_indexes from
567 * libwebsockets.h to check for and read the supported header
568 * presence and content before deciding to allow the handshake
569 * to proceed or to kill the connection.
571 * LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS: if configured for
572 * including OpenSSL support, this callback allows your user code
573 * to perform extra SSL_CTX_load_verify_locations() or similar
574 * calls to direct OpenSSL where to find certificates the client
575 * can use to confirm the remote server identity. @user is the
578 * LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS: if configured for
579 * including OpenSSL support, this callback allows your user code
580 * to load extra certifcates into the server which allow it to
581 * verify the validity of certificates returned by clients. @user
582 * is the server's OpenSSL SSL_CTX*
584 * LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION: if the
585 * libwebsockets context was created with the option
586 * LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT, then this
587 * callback is generated during OpenSSL verification of the cert
588 * sent from the client. It is sent to protocol[0] callback as
589 * no protocol has been negotiated on the connection yet.
590 * Notice that the libwebsockets context and wsi are both NULL
591 * during this callback. See
592 * http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html
593 * to understand more detail about the OpenSSL callback that
594 * generates this libwebsockets callback and the meanings of the
595 * arguments passed. In this callback, @user is the x509_ctx,
596 * @in is the ssl pointer and @len is preverify_ok
597 * Notice that this callback maintains libwebsocket return
598 * conventions, return 0 to mean the cert is OK or 1 to fail it.
599 * This also means that if you don't handle this callback then
600 * the default callback action of returning 0 allows the client
603 * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER: this callback happens
604 * when a client handshake is being compiled. @user is NULL,
605 * @in is a char **, it's pointing to a char * which holds the
606 * next location in the header buffer where you can add
607 * headers, and @len is the remaining space in the header buffer,
608 * which is typically some hundreds of bytes. So, to add a canned
609 * cookie, your handler code might look similar to:
611 * char **p = (char **)in;
616 * *p += sprintf(*p, "Cookie: a=b\x0d\x0a");
620 * Notice if you add anything, you just have to take care about
621 * the CRLF on the line you added. Obviously this callback is
622 * optional, if you don't handle it everything is fine.
624 * Notice the callback is coming to protocols[0] all the time,
625 * because there is no specific protocol handshook yet.
627 * LWS_CALLBACK_CONFIRM_EXTENSION_OKAY: When the server handshake code
628 * sees that it does support a requested extension, before
629 * accepting the extension by additing to the list sent back to
630 * the client it gives this callback just to check that it's okay
631 * to use that extension. It calls back to the requested protocol
632 * and with @in being the extension name, @len is 0 and @user is
633 * valid. Note though at this time the ESTABLISHED callback hasn't
634 * happened yet so if you initialize @user content there, @user
635 * content during this callback might not be useful for anything.
636 * Notice this callback comes to protocols[0].
638 * LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED: When a client
639 * connection is being prepared to start a handshake to a server,
640 * each supported extension is checked with protocols[0] callback
641 * with this reason, giving the user code a chance to suppress the
642 * claim to support that extension by returning non-zero. If
643 * unhandled, by default 0 will be returned and the extension
644 * support included in the header to the server. Notice this
645 * callback comes to protocols[0].
647 * LWS_CALLBACK_PROTOCOL_INIT: One-time call per protocol so it can
648 * do initial setup / allocations etc
650 * LWS_CALLBACK_PROTOCOL_DESTROY: One-time call per protocol indicating
651 * this protocol won't get used at all after this callback, the
652 * context is getting destroyed. Take the opportunity to
653 * deallocate everything that was allocated by the protocol.
655 * The next four reasons are optional and only need taking care of if you
656 * will be integrating libwebsockets sockets into an external polling
659 * LWS_CALLBACK_ADD_POLL_FD: libwebsocket deals with its poll() loop
660 * internally, but in the case you are integrating with another
661 * server you will need to have libwebsocket sockets share a
662 * polling array with the other server. This and the other
663 * POLL_FD related callbacks let you put your specialized
664 * poll array interface code in the callback for protocol 0, the
665 * first protocol you support, usually the HTTP protocol in the
666 * serving case. This callback happens when a socket needs to be
667 * added to the polling loop: @in contains the fd, and
668 * @len is the events bitmap (like, POLLIN). If you are using the
669 * internal polling loop (the "service" callback), you can just
670 * ignore these callbacks.
672 * LWS_CALLBACK_DEL_POLL_FD: This callback happens when a socket descriptor
673 * needs to be removed from an external polling array. @in is
674 * the socket desricptor. If you are using the internal polling
675 * loop, you can just ignore it.
677 * LWS_CALLBACK_SET_MODE_POLL_FD: This callback happens when libwebsockets
678 * wants to modify the events for the socket descriptor in @in.
679 * The handler should OR @len on to the events member of the pollfd
680 * struct for this socket descriptor. If you are using the
681 * internal polling loop, you can just ignore it.
683 * LWS_CALLBACK_CLEAR_MODE_POLL_FD: This callback occurs when libwebsockets
684 * wants to modify the events for the socket descriptor in @in.
685 * The handler should AND ~@len on to the events member of the
686 * pollfd struct for this socket descriptor. If you are using the
687 * internal polling loop, you can just ignore it.
689 LWS_VISIBLE LWS_EXTERN int callback(struct libwebsocket_context *context,
690 struct libwebsocket *wsi,
691 enum libwebsocket_callback_reasons reason, void *user,
692 void *in, size_t len);
694 typedef int (callback_function)(struct libwebsocket_context *context,
695 struct libwebsocket *wsi,
696 enum libwebsocket_callback_reasons reason, void *user,
697 void *in, size_t len);
699 #ifndef LWS_NO_EXTENSIONS
701 * extension_callback_function() - Hooks to allow extensions to operate
702 * @context: Websockets context
703 * @ext: This extension
704 * @wsi: Opaque websocket instance pointer
705 * @reason: The reason for the call
706 * @user: Pointer to per-session user data allocated by library
707 * @in: Pointer used for some callback reasons
708 * @len: Length set for some callback reasons
710 * Each extension that is active on a particular connection receives
711 * callbacks during the connection lifetime to allow the extension to
712 * operate on websocket data and manage itself.
714 * Libwebsockets takes care of allocating and freeing "user" memory for
715 * each active extension on each connection. That is what is pointed to
716 * by the @user parameter.
718 * LWS_EXT_CALLBACK_CONSTRUCT: called when the server has decided to
719 * select this extension from the list provided by the client,
720 * just before the server will send back the handshake accepting
721 * the connection with this extension active. This gives the
722 * extension a chance to initialize its connection context found
725 * LWS_EXT_CALLBACK_CLIENT_CONSTRUCT: same as LWS_EXT_CALLBACK_CONSTRUCT
726 * but called when client is instantiating this extension. Some
727 * extensions will work the same on client and server side and then
728 * you can just merge handlers for both CONSTRUCTS.
730 * LWS_EXT_CALLBACK_DESTROY: called when the connection the extension was
731 * being used on is about to be closed and deallocated. It's the
732 * last chance for the extension to deallocate anything it has
733 * allocated in the user data (pointed to by @user) before the
734 * user data is deleted. This same callback is used whether you
735 * are in client or server instantiation context.
737 * LWS_EXT_CALLBACK_PACKET_RX_PREPARSE: when this extension was active on
738 * a connection, and a packet of data arrived at the connection,
739 * it is passed to this callback to give the extension a chance to
740 * change the data, eg, decompress it. @user is pointing to the
741 * extension's private connection context data, @in is pointing
742 * to an lws_tokens struct, it consists of a char * pointer called
743 * token, and an int called token_len. At entry, these are
744 * set to point to the received buffer and set to the content
745 * length. If the extension will grow the content, it should use
746 * a new buffer allocated in its private user context data and
747 * set the pointed-to lws_tokens members to point to its buffer.
749 * LWS_EXT_CALLBACK_PACKET_TX_PRESEND: this works the same way as
750 * LWS_EXT_CALLBACK_PACKET_RX_PREPARSE above, except it gives the
751 * extension a chance to change websocket data just before it will
752 * be sent out. Using the same lws_token pointer scheme in @in,
753 * the extension can change the buffer and the length to be
754 * transmitted how it likes. Again if it wants to grow the
755 * buffer safely, it should copy the data into its own buffer and
756 * set the lws_tokens token pointer to it.
758 LWS_VISIBLE LWS_EXTERN int extension_callback(struct libwebsocket_context *context,
759 struct libwebsocket_extension *ext,
760 struct libwebsocket *wsi,
761 enum libwebsocket_extension_callback_reasons reason,
762 void *user, void *in, size_t len);
764 typedef int (extension_callback_function)(struct libwebsocket_context *context,
765 struct libwebsocket_extension *ext,
766 struct libwebsocket *wsi,
767 enum libwebsocket_extension_callback_reasons reason,
768 void *user, void *in, size_t len);
772 * struct libwebsocket_protocols - List of protocols and handlers server
774 * @name: Protocol name that must match the one given in the client
775 * Javascript new WebSocket(url, 'protocol') name
776 * @callback: The service callback used for this protocol. It allows the
777 * service action for an entire protocol to be encapsulated in
778 * the protocol-specific callback
779 * @per_session_data_size: Each new connection using this protocol gets
780 * this much memory allocated on connection establishment and
781 * freed on connection takedown. A pointer to this per-connection
782 * allocation is passed into the callback in the 'user' parameter
783 * @rx_buffer_size: if you want atomic frames delivered to the callback, you
784 * should set this to the size of the biggest legal frame that
785 * you support. If the frame size is exceeded, there is no
786 * error, but the buffer will spill to the user callback when
787 * full, which you can detect by using
788 * libwebsockets_remaining_packet_payload(). Notice that you
789 * just talk about frame size here, the LWS_SEND_BUFFER_PRE_PADDING
790 * and post-padding are automatically also allocated on top.
791 * @no_buffer_all_partial_tx: Leave at zero if you want the library to take
792 * care of all partial tx for you. It's useful if you only have
793 * small tx packets and the chance of any truncated send is small
794 * enough any additional malloc / buffering overhead is less
795 * painful than writing the code to deal with partial sends. For
796 * protocols where you stream big blocks, set to nonzero and use
797 * the return value from libwebsocket_write() to manage how much
799 * @owning_server: the server init call fills in this opaque pointer when
800 * registering this protocol with the server.
801 * @protocol_index: which protocol we are starting from zero
803 * This structure represents one protocol supported by the server. An
804 * array of these structures is passed to libwebsocket_create_server()
805 * allows as many protocols as you like to be handled by one server.
808 struct libwebsocket_protocols {
810 callback_function *callback;
811 size_t per_session_data_size;
812 size_t rx_buffer_size;
813 int no_buffer_all_partial_tx;
816 * below are filled in on server init and can be left uninitialized,
817 * no need for user to use them directly either
820 struct libwebsocket_context *owning_server;
824 #ifndef LWS_NO_EXTENSIONS
826 * struct libwebsocket_extension - An extension we know how to cope with
828 * @name: Formal extension name, eg, "deflate-stream"
829 * @callback: Service callback
830 * @per_session_data_size: Libwebsockets will auto-malloc this much
831 * memory for the use of the extension, a pointer
832 * to it comes in the @user callback parameter
833 * @per_context_private_data: Optional storage for this extension that
834 * is per-context, so it can track stuff across
835 * all sessions, etc, if it wants
838 struct libwebsocket_extension {
840 extension_callback_function *callback;
841 size_t per_session_data_size;
842 void *per_context_private_data;
847 * struct lws_context_creation_info: parameters to create context with
849 * @port: Port to listen on... you can use 0 to suppress listening on
850 * any port, that's what you want if you are not running a
851 * websocket server at all but just using it as a client
852 * @iface: NULL to bind the listen socket to all interfaces, or the
853 * interface name, eg, "eth2"
854 * @protocols: Array of structures listing supported protocols and a protocol-
855 * specific callback for each one. The list is ended with an
856 * entry that has a NULL callback pointer.
857 * It's not const because we write the owning_server member
858 * @extensions: NULL or array of libwebsocket_extension structs listing the
859 * extensions this context supports. If you configured with
860 * --without-extensions, you should give NULL here.
861 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
862 * to listen using SSL, set to the filepath to fetch the
863 * server cert from, otherwise NULL for unencrypted
864 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
866 * @ssl_ca_filepath: CA certificate filepath or NULL
867 * @ssl_cipher_list: List of valid ciphers to use (eg,
868 * "RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL"
869 * or you can leave it as NULL to get "DEFAULT"
870 * @gid: group id to change to after setting listen socket, or -1.
871 * @uid: user id to change to after setting listen socket, or -1.
872 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
873 * @user: optional user pointer that can be recovered via the context
874 * pointer using libwebsocket_context_user
875 * @ka_time: 0 for no keepalive, otherwise apply this keepalive timeout to
876 * all libwebsocket sockets, client or server
877 * @ka_probes: if ka_time was nonzero, after the timeout expires how many
878 * times to try to get a response from the peer before giving up
879 * and killing the connection
880 * @ka_interval: if ka_time was nonzero, how long to wait before each ka_probes
884 struct lws_context_creation_info {
887 struct libwebsocket_protocols *protocols;
888 struct libwebsocket_extension *extensions;
889 const char *ssl_cert_filepath;
890 const char *ssl_private_key_filepath;
891 const char *ssl_ca_filepath;
892 const char *ssl_cipher_list;
895 unsigned int options;
903 LWS_VISIBLE LWS_EXTERN
904 void lws_set_log_level(int level,
905 void (*log_emit_function)(int level, const char *line));
907 LWS_VISIBLE LWS_EXTERN void
908 lwsl_emit_syslog(int level, const char *line);
910 LWS_VISIBLE LWS_EXTERN struct libwebsocket_context *
911 libwebsocket_create_context(struct lws_context_creation_info *info);
913 LWS_VISIBLE LWS_EXTERN int
914 libwebsocket_set_proxy(struct libwebsocket_context *context, const char *proxy);
916 LWS_VISIBLE LWS_EXTERN void
917 libwebsocket_context_destroy(struct libwebsocket_context *context);
919 LWS_VISIBLE LWS_EXTERN int
920 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms);
922 LWS_VISIBLE LWS_EXTERN int
923 libwebsocket_service_fd(struct libwebsocket_context *context,
924 struct pollfd *pollfd);
926 LWS_VISIBLE LWS_EXTERN void *
927 libwebsocket_context_user(struct libwebsocket_context *context);
929 enum pending_timeout {
930 NO_PENDING_TIMEOUT = 0,
931 PENDING_TIMEOUT_AWAITING_PROXY_RESPONSE,
932 PENDING_TIMEOUT_AWAITING_CONNECT_RESPONSE,
933 PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
934 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE,
935 PENDING_TIMEOUT_AWAITING_PING,
936 PENDING_TIMEOUT_CLOSE_ACK,
937 PENDING_TIMEOUT_AWAITING_EXTENSION_CONNECT_RESPONSE,
938 PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE,
939 PENDING_TIMEOUT_SSL_ACCEPT,
940 PENDING_TIMEOUT_HTTP_CONTENT,
944 libwebsocket_set_timeout(struct libwebsocket *wsi,
945 enum pending_timeout reason, int secs);
950 * When sending with websocket protocol (LWS_WRITE_TEXT or LWS_WRITE_BINARY)
951 * the send buffer has to have LWS_SEND_BUFFER_PRE_PADDING bytes valid BEFORE
952 * buf, and LWS_SEND_BUFFER_POST_PADDING bytes valid AFTER (buf + len).
954 * This allows us to add protocol info before and after the data, and send as
955 * one packet on the network without payload copying, for maximum efficiency.
957 * So for example you need this kind of code to use libwebsocket_write with a
960 * char buf[LWS_SEND_BUFFER_PRE_PADDING + 128 + LWS_SEND_BUFFER_POST_PADDING];
962 * // fill your part of the buffer... for example here it's all zeros
963 * memset(&buf[LWS_SEND_BUFFER_PRE_PADDING], 0, 128);
965 * libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 128,
968 * When sending LWS_WRITE_HTTP, there is no protocol addition and you can just
969 * use the whole buffer without taking care of the above.
973 * this is the frame nonce plus two header plus 8 length
974 * there's an additional two for mux extension per mux nesting level
975 * 2 byte prepend on close will already fit because control frames cannot use
976 * the big length style
979 #define LWS_SEND_BUFFER_PRE_PADDING (4 + 10 + (2 * MAX_MUX_RECURSION))
980 #define LWS_SEND_BUFFER_POST_PADDING 4
982 LWS_VISIBLE LWS_EXTERN int
983 libwebsocket_write(struct libwebsocket *wsi, unsigned char *buf, size_t len,
984 enum libwebsocket_write_protocol protocol);
986 LWS_VISIBLE LWS_EXTERN int
987 libwebsockets_serve_http_file(struct libwebsocket_context *context,
988 struct libwebsocket *wsi, const char *file,
989 const char *content_type, const char *other_headers);
990 LWS_VISIBLE LWS_EXTERN int
991 libwebsockets_serve_http_file_fragment(struct libwebsocket_context *context,
992 struct libwebsocket *wsi);
994 LWS_VISIBLE int libwebsockets_return_http_status(
995 struct libwebsocket_context *context,
996 struct libwebsocket *wsi, unsigned int code,
997 const char *html_body);
999 LWS_VISIBLE LWS_EXTERN const struct libwebsocket_protocols *
1000 libwebsockets_get_protocol(struct libwebsocket *wsi);
1002 LWS_VISIBLE LWS_EXTERN int
1003 libwebsocket_callback_on_writable(struct libwebsocket_context *context,
1004 struct libwebsocket *wsi);
1006 LWS_VISIBLE LWS_EXTERN int
1007 libwebsocket_callback_on_writable_all_protocol(
1008 const struct libwebsocket_protocols *protocol);
1010 LWS_VISIBLE LWS_EXTERN int
1011 libwebsocket_get_socket_fd(struct libwebsocket *wsi);
1013 LWS_VISIBLE LWS_EXTERN int
1014 libwebsocket_is_final_fragment(struct libwebsocket *wsi);
1016 LWS_VISIBLE LWS_EXTERN unsigned char
1017 libwebsocket_get_reserved_bits(struct libwebsocket *wsi);
1019 LWS_VISIBLE LWS_EXTERN int
1020 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable);
1022 LWS_VISIBLE LWS_EXTERN void
1023 libwebsocket_rx_flow_allow_all_protocol(
1024 const struct libwebsocket_protocols *protocol);
1026 LWS_VISIBLE LWS_EXTERN size_t
1027 libwebsockets_remaining_packet_payload(struct libwebsocket *wsi);
1029 LWS_VISIBLE LWS_EXTERN struct libwebsocket *
1030 libwebsocket_client_connect(struct libwebsocket_context *clients,
1031 const char *address,
1037 const char *protocol,
1038 int ietf_version_or_minus_one);
1040 LWS_VISIBLE LWS_EXTERN struct libwebsocket *
1041 libwebsocket_client_connect_extended(struct libwebsocket_context *clients,
1042 const char *address,
1048 const char *protocol,
1049 int ietf_version_or_minus_one,
1052 LWS_VISIBLE LWS_EXTERN const char *
1053 libwebsocket_canonical_hostname(struct libwebsocket_context *context);
1056 LWS_VISIBLE LWS_EXTERN void
1057 libwebsockets_get_peer_addresses(struct libwebsocket_context *context,
1058 struct libwebsocket *wsi, int fd, char *name, int name_len,
1059 char *rip, int rip_len);
1061 LWS_VISIBLE LWS_EXTERN int
1062 libwebsockets_get_random(struct libwebsocket_context *context,
1063 void *buf, int len);
1065 LWS_VISIBLE LWS_EXTERN int
1066 lws_daemonize(const char *_lock_path);
1068 LWS_VISIBLE LWS_EXTERN int
1069 lws_send_pipe_choked(struct libwebsocket *wsi);
1071 LWS_VISIBLE LWS_EXTERN int
1072 lws_frame_is_binary(struct libwebsocket *wsi);
1074 LWS_VISIBLE LWS_EXTERN unsigned char *
1075 libwebsockets_SHA1(const unsigned char *d, size_t n, unsigned char *md);
1077 LWS_VISIBLE LWS_EXTERN int
1078 lws_b64_encode_string(const char *in, int in_len, char *out, int out_size);
1080 LWS_VISIBLE LWS_EXTERN int
1081 lws_b64_decode_string(const char *in, char *out, int out_size);
1083 LWS_VISIBLE LWS_EXTERN const char *
1084 lws_get_library_version(void);
1086 /* access to headers... only valid while headers valid */
1088 LWS_VISIBLE LWS_EXTERN int
1089 lws_hdr_total_length(struct libwebsocket *wsi, enum lws_token_indexes h);
1091 LWS_VISIBLE LWS_EXTERN int
1092 lws_hdr_copy(struct libwebsocket *wsi, char *dest, int len,
1093 enum lws_token_indexes h);
1096 * Note: this is not normally needed as a user api. It's provided in case it is
1097 * useful when integrating with other app poll loop service code.
1100 LWS_VISIBLE LWS_EXTERN int
1101 libwebsocket_read(struct libwebsocket_context *context,
1102 struct libwebsocket *wsi,
1103 unsigned char *buf, size_t len);
1105 #ifndef LWS_NO_EXTENSIONS
1106 LWS_VISIBLE LWS_EXTERN struct libwebsocket_extension *libwebsocket_get_internal_extensions();