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
31 #include "lws_config.h"
34 #if defined(WIN32) || defined(_WIN32)
36 #ifndef WIN32_LEAN_AND_MEAN
37 #define WIN32_LEAN_AND_MEAN
44 #define strcasecmp stricmp
45 #define getdtablesize() 30000
51 #define LWS_EXTERN extern __declspec(dllexport)
53 #define LWS_EXTERN extern __declspec(dllimport)
65 #define LWS_VISIBLE __attribute__((visibility("default")))
74 #endif /* LWS_USE_LIBEV */
79 #define LWS_EXTERN extern
89 #define CONTEXT_PORT_NO_LISTEN -1
90 #define MAX_MUX_RECURSION 2
102 LLL_LATENCY = 1 << 9,
104 LLL_COUNT = 10 /* set to count of valid flags */
107 LWS_VISIBLE LWS_EXTERN void _lws_log(int filter, const char *format, ...);
109 /* notice, warn and log are always compiled in */
110 #define lwsl_notice(...) _lws_log(LLL_NOTICE, __VA_ARGS__)
111 #define lwsl_warn(...) _lws_log(LLL_WARN, __VA_ARGS__)
112 #define lwsl_err(...) _lws_log(LLL_ERR, __VA_ARGS__)
114 * weaker logging can be deselected at configure time using --disable-debug
115 * that gets rid of the overhead of checking while keeping _warn and _err
120 #define lwsl_info(...) _lws_log(LLL_INFO, __VA_ARGS__)
121 #define lwsl_debug(...) _lws_log(LLL_DEBUG, __VA_ARGS__)
122 #define lwsl_parser(...) _lws_log(LLL_PARSER, __VA_ARGS__)
123 #define lwsl_header(...) _lws_log(LLL_HEADER, __VA_ARGS__)
124 #define lwsl_ext(...) _lws_log(LLL_EXT, __VA_ARGS__)
125 #define lwsl_client(...) _lws_log(LLL_CLIENT, __VA_ARGS__)
126 #define lwsl_latency(...) _lws_log(LLL_LATENCY, __VA_ARGS__)
127 LWS_VISIBLE LWS_EXTERN void lwsl_hexdump(void *buf, size_t len);
131 #define lwsl_info(...)
132 #define lwsl_debug(...)
133 #define lwsl_parser(...)
134 #define lwsl_header(...)
135 #define lwsl_ext(...)
136 #define lwsl_client(...)
137 #define lwsl_latency(...)
138 #define lwsl_hexdump(a, b)
142 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
144 /* api change list for user code to test against */
146 #define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_ARG
149 enum libwebsocket_context_options {
150 LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT = 2,
151 LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME = 4,
152 LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT = 8,
153 LWS_SERVER_OPTION_LIBEV = 16,
154 LWS_SERVER_OPTION_DISABLE_IPV6 = 32,
157 enum libwebsocket_callback_reasons {
158 LWS_CALLBACK_ESTABLISHED,
159 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
160 LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH,
161 LWS_CALLBACK_CLIENT_ESTABLISHED,
163 LWS_CALLBACK_CLOSED_HTTP,
164 LWS_CALLBACK_RECEIVE,
165 LWS_CALLBACK_CLIENT_RECEIVE,
166 LWS_CALLBACK_CLIENT_RECEIVE_PONG,
167 LWS_CALLBACK_CLIENT_WRITEABLE,
168 LWS_CALLBACK_SERVER_WRITEABLE,
170 LWS_CALLBACK_HTTP_BODY,
171 LWS_CALLBACK_HTTP_BODY_COMPLETION,
172 LWS_CALLBACK_HTTP_FILE_COMPLETION,
173 LWS_CALLBACK_HTTP_WRITEABLE,
174 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
175 LWS_CALLBACK_FILTER_HTTP_CONNECTION,
176 LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED,
177 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
178 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
179 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
180 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
181 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
182 LWS_CALLBACK_CONFIRM_EXTENSION_OKAY,
183 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
184 LWS_CALLBACK_PROTOCOL_INIT,
185 LWS_CALLBACK_PROTOCOL_DESTROY,
186 LWS_CALLBACK_WSI_CREATE, /* always protocol[0] */
187 LWS_CALLBACK_WSI_DESTROY, /* always protocol[0] */
188 LWS_CALLBACK_GET_THREAD_ID,
190 /* external poll() management support */
191 LWS_CALLBACK_ADD_POLL_FD,
192 LWS_CALLBACK_DEL_POLL_FD,
193 LWS_CALLBACK_CHANGE_MODE_POLL_FD,
194 LWS_CALLBACK_LOCK_POLL,
195 LWS_CALLBACK_UNLOCK_POLL,
197 LWS_CALLBACK_USER = 1000, /* user code can use any including / above */
200 // argument structure for all external poll related calls
201 // passed in via 'in'
202 struct libwebsocket_pollargs {
203 int fd; // applicable file descriptor
204 int events; // the new event mask
205 int prev_events; // the previous event mask
209 struct libwebsocket_pollfd {
215 #define libwebsocket_pollfd pollfd
218 enum libwebsocket_extension_callback_reasons {
219 LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT,
220 LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT,
221 LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT,
222 LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT,
223 LWS_EXT_CALLBACK_CONSTRUCT,
224 LWS_EXT_CALLBACK_CLIENT_CONSTRUCT,
225 LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE,
226 LWS_EXT_CALLBACK_CHECK_OK_TO_PROPOSE_EXTENSION,
227 LWS_EXT_CALLBACK_DESTROY,
228 LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING,
229 LWS_EXT_CALLBACK_ANY_WSI_ESTABLISHED,
230 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE,
231 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
232 LWS_EXT_CALLBACK_PACKET_TX_DO_SEND,
233 LWS_EXT_CALLBACK_HANDSHAKE_REPLY_TX,
234 LWS_EXT_CALLBACK_FLUSH_PENDING_TX,
235 LWS_EXT_CALLBACK_EXTENDED_PAYLOAD_RX,
236 LWS_EXT_CALLBACK_CAN_PROXY_CLIENT_CONNECTION,
237 LWS_EXT_CALLBACK_1HZ,
238 LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE,
239 LWS_EXT_CALLBACK_IS_WRITEABLE,
240 LWS_EXT_CALLBACK_PAYLOAD_TX,
241 LWS_EXT_CALLBACK_PAYLOAD_RX,
244 enum libwebsocket_write_protocol {
247 LWS_WRITE_CONTINUATION,
250 /* special 04+ opcodes */
258 LWS_WRITE_NO_FIN = 0x40,
260 * client packet payload goes out on wire unmunged
261 * only useful for security tests since normal servers cannot
262 * decode the content if used
264 LWS_WRITE_CLIENT_IGNORE_XOR_MASK = 0x80
268 * you need these to look at headers that have been parsed if using the
269 * LWS_CALLBACK_FILTER_CONNECTION callback. If a header from the enum
270 * list below is absent, .token = NULL and token_len = 0. Otherwise .token
271 * points to .token_len chars containing that header content.
279 enum lws_token_indexes {
282 WSI_TOKEN_OPTIONS_URI,
284 WSI_TOKEN_CONNECTION,
299 WSI_TOKEN_EXTENSIONS,
301 /* client receives these */
307 WSI_TOKEN_HTTP_ACCEPT,
308 WSI_TOKEN_HTTP_AC_REQUEST_HEADERS,
309 WSI_TOKEN_HTTP_IF_MODIFIED_SINCE,
310 WSI_TOKEN_HTTP_IF_NONE_MATCH,
311 WSI_TOKEN_HTTP_ACCEPT_ENCODING,
312 WSI_TOKEN_HTTP_ACCEPT_LANGUAGE,
313 WSI_TOKEN_HTTP_PRAGMA,
314 WSI_TOKEN_HTTP_CACHE_CONTROL,
315 WSI_TOKEN_HTTP_AUTHORIZATION,
316 WSI_TOKEN_HTTP_COOKIE,
317 WSI_TOKEN_HTTP_CONTENT_LENGTH,
318 WSI_TOKEN_HTTP_CONTENT_TYPE,
320 WSI_TOKEN_HTTP_RANGE,
321 WSI_TOKEN_HTTP_REFERER,
322 WSI_TOKEN_HTTP_URI_ARGS,
327 /* use token storage to stash these */
329 _WSI_TOKEN_CLIENT_SENT_PROTOCOLS,
330 _WSI_TOKEN_CLIENT_PEER_ADDRESS,
331 _WSI_TOKEN_CLIENT_URI,
332 _WSI_TOKEN_CLIENT_HOST,
333 _WSI_TOKEN_CLIENT_ORIGIN,
335 /* always last real token index*/
337 /* parser state additions */
340 WSI_TOKEN_SKIPPING_SAW_CR,
341 WSI_PARSING_COMPLETE,
342 WSI_INIT_TOKEN_MUXURL,
345 struct lws_token_limits {
346 unsigned short token_limit[WSI_TOKEN_COUNT];
353 1000 indicates a normal closure, meaning that the purpose for
354 which the connection was established has been fulfilled.
358 1001 indicates that an endpoint is "going away", such as a server
359 going down or a browser having navigated away from a page.
363 1002 indicates that an endpoint is terminating the connection due
368 1003 indicates that an endpoint is terminating the connection
369 because it has received a type of data it cannot accept (e.g., an
370 endpoint that understands only text data MAY send this if it
371 receives a binary message).
375 Reserved. The specific meaning might be defined in the future.
379 1005 is a reserved value and MUST NOT be set as a status code in a
380 Close control frame by an endpoint. It is designated for use in
381 applications expecting a status code to indicate that no status
382 code was actually present.
386 1006 is a reserved value and MUST NOT be set as a status code in a
387 Close control frame by an endpoint. It is designated for use in
388 applications expecting a status code to indicate that the
389 connection was closed abnormally, e.g., without sending or
390 receiving a Close control frame.
394 1007 indicates that an endpoint is terminating the connection
395 because it has received data within a message that was not
396 consistent with the type of the message (e.g., non-UTF-8 [RFC3629]
397 data within a text message).
401 1008 indicates that an endpoint is terminating the connection
402 because it has received a message that violates its policy. This
403 is a generic status code that can be returned when there is no
404 other more suitable status code (e.g., 1003 or 1009) or if there
405 is a need to hide specific details about the policy.
409 1009 indicates that an endpoint is terminating the connection
410 because it has received a message that is too big for it to
415 1010 indicates that an endpoint (client) is terminating the
416 connection because it has expected the server to negotiate one or
417 more extension, but the server didn't return them in the response
418 message of the WebSocket handshake. The list of extensions that
419 are needed SHOULD appear in the /reason/ part of the Close frame.
420 Note that this status code is not used by the server, because it
421 can fail the WebSocket handshake instead.
425 1011 indicates that a server is terminating the connection because
426 it encountered an unexpected condition that prevented it from
427 fulfilling the request.
431 1015 is a reserved value and MUST NOT be set as a status code in a
432 Close control frame by an endpoint. It is designated for use in
433 applications expecting a status code to indicate that the
434 connection was closed due to a failure to perform a TLS handshake
435 (e.g., the server certificate can't be verified).
438 enum lws_close_status {
439 LWS_CLOSE_STATUS_NOSTATUS = 0,
440 LWS_CLOSE_STATUS_NORMAL = 1000,
441 LWS_CLOSE_STATUS_GOINGAWAY = 1001,
442 LWS_CLOSE_STATUS_PROTOCOL_ERR = 1002,
443 LWS_CLOSE_STATUS_UNACCEPTABLE_OPCODE = 1003,
444 LWS_CLOSE_STATUS_RESERVED = 1004,
445 LWS_CLOSE_STATUS_NO_STATUS = 1005,
446 LWS_CLOSE_STATUS_ABNORMAL_CLOSE = 1006,
447 LWS_CLOSE_STATUS_INVALID_PAYLOAD = 1007,
448 LWS_CLOSE_STATUS_POLICY_VIOLATION = 1008,
449 LWS_CLOSE_STATUS_MESSAGE_TOO_LARGE = 1009,
450 LWS_CLOSE_STATUS_EXTENSION_REQUIRED = 1010,
451 LWS_CLOSE_STATUS_UNEXPECTED_CONDITION = 1011,
452 LWS_CLOSE_STATUS_TLS_FAILURE = 1015,
456 HTTP_STATUS_OK = 200,
457 HTTP_STATUS_NO_CONTENT = 204,
459 HTTP_STATUS_BAD_REQUEST = 400,
460 HTTP_STATUS_UNAUTHORIZED,
461 HTTP_STATUS_PAYMENT_REQUIRED,
462 HTTP_STATUS_FORBIDDEN,
463 HTTP_STATUS_NOT_FOUND,
464 HTTP_STATUS_METHOD_NOT_ALLOWED,
465 HTTP_STATUS_NOT_ACCEPTABLE,
466 HTTP_STATUS_PROXY_AUTH_REQUIRED,
467 HTTP_STATUS_REQUEST_TIMEOUT,
468 HTTP_STATUS_CONFLICT,
470 HTTP_STATUS_LENGTH_REQUIRED,
471 HTTP_STATUS_PRECONDITION_FAILED,
472 HTTP_STATUS_REQ_ENTITY_TOO_LARGE,
473 HTTP_STATUS_REQ_URI_TOO_LONG,
474 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE,
475 HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE,
476 HTTP_STATUS_EXPECTATION_FAILED,
478 HTTP_STATUS_INTERNAL_SERVER_ERROR = 500,
479 HTTP_STATUS_NOT_IMPLEMENTED,
480 HTTP_STATUS_BAD_GATEWAY,
481 HTTP_STATUS_SERVICE_UNAVAILABLE,
482 HTTP_STATUS_GATEWAY_TIMEOUT,
483 HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED,
487 struct libwebsocket_context;
488 /* needed even with extensions disabled for create context */
489 struct libwebsocket_extension;
492 * callback_function() - User server actions
493 * @context: Websockets context
494 * @wsi: Opaque websocket instance pointer
495 * @reason: The reason for the call
496 * @user: Pointer to per-session user data allocated by library
497 * @in: Pointer used for some callback reasons
498 * @len: Length set for some callback reasons
500 * This callback is the way the user controls what is served. All the
501 * protocol detail is hidden and handled by the library.
503 * For each connection / session there is user data allocated that is
504 * pointed to by "user". You set the size of this user data area when
505 * the library is initialized with libwebsocket_create_server.
507 * You get an opportunity to initialize user data when called back with
508 * LWS_CALLBACK_ESTABLISHED reason.
510 * LWS_CALLBACK_ESTABLISHED: after the server completes a handshake with
513 * LWS_CALLBACK_CLIENT_CONNECTION_ERROR: the request client connection has
514 * been unable to complete a handshake with the remote server
516 * LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH: this is the last chance for the
517 * client user code to examine the http headers
518 * and decide to reject the connection. If the
519 * content in the headers is interesting to the
520 * client (url, etc) it needs to copy it out at
521 * this point since it will be destroyed before
522 * the CLIENT_ESTABLISHED call
524 * LWS_CALLBACK_CLIENT_ESTABLISHED: after your client connection completed
525 * a handshake with the remote server
527 * LWS_CALLBACK_CLOSED: when the websocket session ends
529 * LWS_CALLBACK_CLOSED_HTTP: when a HTTP (non-websocket) session ends
531 * LWS_CALLBACK_RECEIVE: data has appeared for this server endpoint from a
532 * remote client, it can be found at *in and is
535 * LWS_CALLBACK_CLIENT_RECEIVE_PONG: if you elected to see PONG packets,
536 * they appear with this callback reason. PONG
537 * packets only exist in 04+ protocol
539 * LWS_CALLBACK_CLIENT_RECEIVE: data has appeared from the server for the
540 * client connection, it can be found at *in and
543 * LWS_CALLBACK_HTTP: an http request has come from a client that is not
544 * asking to upgrade the connection to a websocket
545 * one. This is a chance to serve http content,
546 * for example, to send a script to the client
547 * which will then open the websockets connection.
548 * @in points to the URI path requested and
549 * libwebsockets_serve_http_file() makes it very
550 * simple to send back a file to the client.
551 * Normally after sending the file you are done
552 * with the http connection, since the rest of the
553 * activity will come by websockets from the script
554 * that was delivered by http, so you will want to
555 * return 1; to close and free up the connection.
556 * That's important because it uses a slot in the
557 * total number of client connections allowed set
560 * LWS_CALLBACK_HTTP_BODY: the next @len bytes data from the http
561 * request body HTTP connection is now available in @in.
563 * LWS_CALLBACK_HTTP_BODY_COMPLETION: the expected amount of http request
564 * body has been delivered
566 * LWS_CALLBACK_HTTP_WRITEABLE: you can write more down the http protocol
569 * LWS_CALLBACK_HTTP_FILE_COMPLETION: a file requested to be send down
570 * http link has completed.
572 * LWS_CALLBACK_CLIENT_WRITEABLE:
573 * LWS_CALLBACK_SERVER_WRITEABLE: If you call
574 * libwebsocket_callback_on_writable() on a connection, you will
575 * get one of these callbacks coming when the connection socket
576 * is able to accept another write packet without blocking.
577 * If it already was able to take another packet without blocking,
578 * you'll get this callback at the next call to the service loop
579 * function. Notice that CLIENTs get LWS_CALLBACK_CLIENT_WRITEABLE
580 * and servers get LWS_CALLBACK_SERVER_WRITEABLE.
582 * LWS_CALLBACK_FILTER_NETWORK_CONNECTION: called when a client connects to
583 * the server at network level; the connection is accepted but then
584 * passed to this callback to decide whether to hang up immediately
585 * or not, based on the client IP. @in contains the connection
586 * socket's descriptor. Since the client connection information is
587 * not available yet, @wsi still pointing to the main server socket.
588 * Return non-zero to terminate the connection before sending or
589 * receiving anything. Because this happens immediately after the
590 * network connection from the client, there's no websocket protocol
591 * selected yet so this callback is issued only to protocol 0.
593 * LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED: A new client just had
594 * been connected, accepted, and instantiated into the pool. This
595 * callback allows setting any relevant property to it. Because this
596 * happens immediately after the instantiation of a new client,
597 * there's no websocket protocol selected yet so this callback is
598 * issued only to protocol 0. Only @wsi is defined, pointing to the
599 * new client, and the return value is ignored.
601 * LWS_CALLBACK_FILTER_HTTP_CONNECTION: called when the request has
602 * been received and parsed from the client, but the response is
603 * not sent yet. Return non-zero to disallow the connection.
604 * @user is a pointer to the connection user space allocation,
605 * @in is the URI, eg, "/"
606 * In your handler you can use the public APIs
607 * lws_hdr_total_length() / lws_hdr_copy() to access all of the
608 * headers using the header enums lws_token_indexes from
609 * libwebsockets.h to check for and read the supported header
610 * presence and content before deciding to allow the http
611 * connection to proceed or to kill the connection.
613 * LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION: called when the handshake has
614 * been received and parsed from the client, but the response is
615 * not sent yet. Return non-zero to disallow the connection.
616 * @user is a pointer to the connection user space allocation,
617 * @in is the requested protocol name
618 * In your handler you can use the public APIs
619 * lws_hdr_total_length() / lws_hdr_copy() to access all of the
620 * headers using the header enums lws_token_indexes from
621 * libwebsockets.h to check for and read the supported header
622 * presence and content before deciding to allow the handshake
623 * to proceed or to kill the connection.
625 * LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS: if configured for
626 * including OpenSSL support, this callback allows your user code
627 * to perform extra SSL_CTX_load_verify_locations() or similar
628 * calls to direct OpenSSL where to find certificates the client
629 * can use to confirm the remote server identity. @user is the
632 * LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS: if configured for
633 * including OpenSSL support, this callback allows your user code
634 * to load extra certifcates into the server which allow it to
635 * verify the validity of certificates returned by clients. @user
636 * is the server's OpenSSL SSL_CTX*
638 * LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION: if the
639 * libwebsockets context was created with the option
640 * LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT, then this
641 * callback is generated during OpenSSL verification of the cert
642 * sent from the client. It is sent to protocol[0] callback as
643 * no protocol has been negotiated on the connection yet.
644 * Notice that the libwebsockets context and wsi are both NULL
645 * during this callback. See
646 * http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html
647 * to understand more detail about the OpenSSL callback that
648 * generates this libwebsockets callback and the meanings of the
649 * arguments passed. In this callback, @user is the x509_ctx,
650 * @in is the ssl pointer and @len is preverify_ok
651 * Notice that this callback maintains libwebsocket return
652 * conventions, return 0 to mean the cert is OK or 1 to fail it.
653 * This also means that if you don't handle this callback then
654 * the default callback action of returning 0 allows the client
657 * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER: this callback happens
658 * when a client handshake is being compiled. @user is NULL,
659 * @in is a char **, it's pointing to a char * which holds the
660 * next location in the header buffer where you can add
661 * headers, and @len is the remaining space in the header buffer,
662 * which is typically some hundreds of bytes. So, to add a canned
663 * cookie, your handler code might look similar to:
665 * char **p = (char **)in;
670 * *p += sprintf(*p, "Cookie: a=b\x0d\x0a");
674 * Notice if you add anything, you just have to take care about
675 * the CRLF on the line you added. Obviously this callback is
676 * optional, if you don't handle it everything is fine.
678 * Notice the callback is coming to protocols[0] all the time,
679 * because there is no specific protocol handshook yet.
681 * LWS_CALLBACK_CONFIRM_EXTENSION_OKAY: When the server handshake code
682 * sees that it does support a requested extension, before
683 * accepting the extension by additing to the list sent back to
684 * the client it gives this callback just to check that it's okay
685 * to use that extension. It calls back to the requested protocol
686 * and with @in being the extension name, @len is 0 and @user is
687 * valid. Note though at this time the ESTABLISHED callback hasn't
688 * happened yet so if you initialize @user content there, @user
689 * content during this callback might not be useful for anything.
690 * Notice this callback comes to protocols[0].
692 * LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED: When a client
693 * connection is being prepared to start a handshake to a server,
694 * each supported extension is checked with protocols[0] callback
695 * with this reason, giving the user code a chance to suppress the
696 * claim to support that extension by returning non-zero. If
697 * unhandled, by default 0 will be returned and the extension
698 * support included in the header to the server. Notice this
699 * callback comes to protocols[0].
701 * LWS_CALLBACK_PROTOCOL_INIT: One-time call per protocol so it can
702 * do initial setup / allocations etc
704 * LWS_CALLBACK_PROTOCOL_DESTROY: One-time call per protocol indicating
705 * this protocol won't get used at all after this callback, the
706 * context is getting destroyed. Take the opportunity to
707 * deallocate everything that was allocated by the protocol.
709 * LWS_CALLBACK_WSI_CREATE: outermost (earliest) wsi create notification
711 * LWS_CALLBACK_WSI_DESTROY: outermost (latest) wsi destroy notification
713 * The next five reasons are optional and only need taking care of if you
714 * will be integrating libwebsockets sockets into an external polling
717 * For these calls, @in points to a struct libwebsocket_pollargs that
718 * contains @fd, @events and @prev_events members
720 * LWS_CALLBACK_ADD_POLL_FD: libwebsocket deals with its poll() loop
721 * internally, but in the case you are integrating with another
722 * server you will need to have libwebsocket sockets share a
723 * polling array with the other server. This and the other
724 * POLL_FD related callbacks let you put your specialized
725 * poll array interface code in the callback for protocol 0, the
726 * first protocol you support, usually the HTTP protocol in the
728 * This callback happens when a socket needs to be
729 * added to the polling loop: @in points to a struct
730 * libwebsocket_pollargs; the @fd member of the struct is the file
731 * descriptor, and @events contains the active events.
733 * If you are using the internal polling loop (the "service"
734 * callback), you can just ignore these callbacks.
736 * LWS_CALLBACK_DEL_POLL_FD: This callback happens when a socket descriptor
737 * needs to be removed from an external polling array. @in is
738 * again the struct libwebsocket_pollargs containing the @fd member
739 * to be removed. If you are using the internal polling
740 * loop, you can just ignore it.
742 * LWS_CALLBACK_CHANGE_MODE_POLL_FD: This callback happens when
743 * libwebsockets wants to modify the events for a connectiion.
744 * @in is the struct libwebsocket_pollargs with the @fd to change.
745 * The new event mask is in @events member and the old mask is in
746 * the @prev_events member.
747 * If you are using the internal polling loop, you can just ignore
750 * LWS_CALLBACK_LOCK_POLL:
751 * LWS_CALLBACK_UNLOCK_POLL: These allow the external poll changes driven
752 * by libwebsockets to participate in an external thread locking
753 * scheme around the changes, so the whole thing is threadsafe.
755 LWS_VISIBLE LWS_EXTERN int callback(struct libwebsocket_context *context,
756 struct libwebsocket *wsi,
757 enum libwebsocket_callback_reasons reason, void *user,
758 void *in, size_t len);
760 typedef int (callback_function)(struct libwebsocket_context *context,
761 struct libwebsocket *wsi,
762 enum libwebsocket_callback_reasons reason, void *user,
763 void *in, size_t len);
765 #ifndef LWS_NO_EXTENSIONS
767 * extension_callback_function() - Hooks to allow extensions to operate
768 * @context: Websockets context
769 * @ext: This extension
770 * @wsi: Opaque websocket instance pointer
771 * @reason: The reason for the call
772 * @user: Pointer to per-session user data allocated by library
773 * @in: Pointer used for some callback reasons
774 * @len: Length set for some callback reasons
776 * Each extension that is active on a particular connection receives
777 * callbacks during the connection lifetime to allow the extension to
778 * operate on websocket data and manage itself.
780 * Libwebsockets takes care of allocating and freeing "user" memory for
781 * each active extension on each connection. That is what is pointed to
782 * by the @user parameter.
784 * LWS_EXT_CALLBACK_CONSTRUCT: called when the server has decided to
785 * select this extension from the list provided by the client,
786 * just before the server will send back the handshake accepting
787 * the connection with this extension active. This gives the
788 * extension a chance to initialize its connection context found
791 * LWS_EXT_CALLBACK_CLIENT_CONSTRUCT: same as LWS_EXT_CALLBACK_CONSTRUCT
792 * but called when client is instantiating this extension. Some
793 * extensions will work the same on client and server side and then
794 * you can just merge handlers for both CONSTRUCTS.
796 * LWS_EXT_CALLBACK_DESTROY: called when the connection the extension was
797 * being used on is about to be closed and deallocated. It's the
798 * last chance for the extension to deallocate anything it has
799 * allocated in the user data (pointed to by @user) before the
800 * user data is deleted. This same callback is used whether you
801 * are in client or server instantiation context.
803 * LWS_EXT_CALLBACK_PACKET_RX_PREPARSE: when this extension was active on
804 * a connection, and a packet of data arrived at the connection,
805 * it is passed to this callback to give the extension a chance to
806 * change the data, eg, decompress it. @user is pointing to the
807 * extension's private connection context data, @in is pointing
808 * to an lws_tokens struct, it consists of a char * pointer called
809 * token, and an int called token_len. At entry, these are
810 * set to point to the received buffer and set to the content
811 * length. If the extension will grow the content, it should use
812 * a new buffer allocated in its private user context data and
813 * set the pointed-to lws_tokens members to point to its buffer.
815 * LWS_EXT_CALLBACK_PACKET_TX_PRESEND: this works the same way as
816 * LWS_EXT_CALLBACK_PACKET_RX_PREPARSE above, except it gives the
817 * extension a chance to change websocket data just before it will
818 * be sent out. Using the same lws_token pointer scheme in @in,
819 * the extension can change the buffer and the length to be
820 * transmitted how it likes. Again if it wants to grow the
821 * buffer safely, it should copy the data into its own buffer and
822 * set the lws_tokens token pointer to it.
824 LWS_VISIBLE LWS_EXTERN int extension_callback(struct libwebsocket_context *context,
825 struct libwebsocket_extension *ext,
826 struct libwebsocket *wsi,
827 enum libwebsocket_extension_callback_reasons reason,
828 void *user, void *in, size_t len);
830 typedef int (extension_callback_function)(struct libwebsocket_context *context,
831 struct libwebsocket_extension *ext,
832 struct libwebsocket *wsi,
833 enum libwebsocket_extension_callback_reasons reason,
834 void *user, void *in, size_t len);
838 * struct libwebsocket_protocols - List of protocols and handlers server
840 * @name: Protocol name that must match the one given in the client
841 * Javascript new WebSocket(url, 'protocol') name
842 * @callback: The service callback used for this protocol. It allows the
843 * service action for an entire protocol to be encapsulated in
844 * the protocol-specific callback
845 * @per_session_data_size: Each new connection using this protocol gets
846 * this much memory allocated on connection establishment and
847 * freed on connection takedown. A pointer to this per-connection
848 * allocation is passed into the callback in the 'user' parameter
849 * @rx_buffer_size: if you want atomic frames delivered to the callback, you
850 * should set this to the size of the biggest legal frame that
851 * you support. If the frame size is exceeded, there is no
852 * error, but the buffer will spill to the user callback when
853 * full, which you can detect by using
854 * libwebsockets_remaining_packet_payload(). Notice that you
855 * just talk about frame size here, the LWS_SEND_BUFFER_PRE_PADDING
856 * and post-padding are automatically also allocated on top.
857 * @no_buffer_all_partial_tx: Leave at zero if you want the library to take
858 * care of all partial tx for you. It's useful if you only have
859 * small tx packets and the chance of any truncated send is small
860 * enough any additional malloc / buffering overhead is less
861 * painful than writing the code to deal with partial sends. For
862 * protocols where you stream big blocks, set to nonzero and use
863 * the return value from libwebsocket_write() to manage how much
865 * @owning_server: the server init call fills in this opaque pointer when
866 * registering this protocol with the server.
867 * @protocol_index: which protocol we are starting from zero
869 * This structure represents one protocol supported by the server. An
870 * array of these structures is passed to libwebsocket_create_server()
871 * allows as many protocols as you like to be handled by one server.
874 struct libwebsocket_protocols {
876 callback_function *callback;
877 size_t per_session_data_size;
878 size_t rx_buffer_size;
879 int no_buffer_all_partial_tx;
882 * below are filled in on server init and can be left uninitialized,
883 * no need for user to use them directly either
886 struct libwebsocket_context *owning_server;
890 #ifndef LWS_NO_EXTENSIONS
892 * struct libwebsocket_extension - An extension we know how to cope with
894 * @name: Formal extension name, eg, "deflate-stream"
895 * @callback: Service callback
896 * @per_session_data_size: Libwebsockets will auto-malloc this much
897 * memory for the use of the extension, a pointer
898 * to it comes in the @user callback parameter
899 * @per_context_private_data: Optional storage for this extension that
900 * is per-context, so it can track stuff across
901 * all sessions, etc, if it wants
904 struct libwebsocket_extension {
906 extension_callback_function *callback;
907 size_t per_session_data_size;
908 void *per_context_private_data;
913 * struct lws_context_creation_info: parameters to create context with
915 * @port: Port to listen on... you can use 0 to suppress listening on
916 * any port, that's what you want if you are not running a
917 * websocket server at all but just using it as a client
918 * @iface: NULL to bind the listen socket to all interfaces, or the
919 * interface name, eg, "eth2"
920 * @protocols: Array of structures listing supported protocols and a protocol-
921 * specific callback for each one. The list is ended with an
922 * entry that has a NULL callback pointer.
923 * It's not const because we write the owning_server member
924 * @extensions: NULL or array of libwebsocket_extension structs listing the
925 * extensions this context supports. If you configured with
926 * --without-extensions, you should give NULL here.
927 * @token_limits: NULL or struct lws_token_limits pointer which is initialized
928 * with a token length limit for each possible WSI_TOKEN_***
929 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
930 * to listen using SSL, set to the filepath to fetch the
931 * server cert from, otherwise NULL for unencrypted
932 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
934 * @ssl_ca_filepath: CA certificate filepath or NULL
935 * @ssl_cipher_list: List of valid ciphers to use (eg,
936 * "RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL"
937 * or you can leave it as NULL to get "DEFAULT"
938 * @gid: group id to change to after setting listen socket, or -1.
939 * @uid: user id to change to after setting listen socket, or -1.
940 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
941 * @user: optional user pointer that can be recovered via the context
942 * pointer using libwebsocket_context_user
943 * @ka_time: 0 for no keepalive, otherwise apply this keepalive timeout to
944 * all libwebsocket sockets, client or server
945 * @ka_probes: if ka_time was nonzero, after the timeout expires how many
946 * times to try to get a response from the peer before giving up
947 * and killing the connection
948 * @ka_interval: if ka_time was nonzero, how long to wait before each ka_probes
952 struct lws_context_creation_info {
955 struct libwebsocket_protocols *protocols;
956 struct libwebsocket_extension *extensions;
957 struct lws_token_limits *token_limits;
958 const char *ssl_cert_filepath;
959 const char *ssl_private_key_filepath;
960 const char *ssl_ca_filepath;
961 const char *ssl_cipher_list;
962 const char *http_proxy_address;
963 unsigned int http_proxy_port;
966 unsigned int options;
974 LWS_VISIBLE LWS_EXTERN
975 void lws_set_log_level(int level,
976 void (*log_emit_function)(int level, const char *line));
978 LWS_VISIBLE LWS_EXTERN void
979 lwsl_emit_syslog(int level, const char *line);
981 LWS_VISIBLE LWS_EXTERN struct libwebsocket_context *
982 libwebsocket_create_context(struct lws_context_creation_info *info);
984 LWS_VISIBLE LWS_EXTERN int
985 libwebsocket_set_proxy(struct libwebsocket_context *context, const char *proxy);
987 LWS_VISIBLE LWS_EXTERN void
988 libwebsocket_context_destroy(struct libwebsocket_context *context);
990 LWS_VISIBLE LWS_EXTERN int
991 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms);
993 LWS_VISIBLE LWS_EXTERN void
994 libwebsocket_cancel_service(struct libwebsocket_context *context);
997 LWS_VISIBLE LWS_EXTERN int
998 libwebsocket_initloop(
999 struct libwebsocket_context *context, struct ev_loop *loop);
1002 libwebsocket_sigint_cb(
1003 struct ev_loop *loop, struct ev_signal *watcher, int revents);
1004 #endif /* LWS_USE_LIBEV */
1006 LWS_VISIBLE LWS_EXTERN int
1007 libwebsocket_service_fd(struct libwebsocket_context *context,
1008 struct libwebsocket_pollfd *pollfd);
1010 LWS_VISIBLE LWS_EXTERN void *
1011 libwebsocket_context_user(struct libwebsocket_context *context);
1013 enum pending_timeout {
1014 NO_PENDING_TIMEOUT = 0,
1015 PENDING_TIMEOUT_AWAITING_PROXY_RESPONSE,
1016 PENDING_TIMEOUT_AWAITING_CONNECT_RESPONSE,
1017 PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
1018 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE,
1019 PENDING_TIMEOUT_AWAITING_PING,
1020 PENDING_TIMEOUT_CLOSE_ACK,
1021 PENDING_TIMEOUT_AWAITING_EXTENSION_CONNECT_RESPONSE,
1022 PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE,
1023 PENDING_TIMEOUT_SSL_ACCEPT,
1024 PENDING_TIMEOUT_HTTP_CONTENT,
1025 PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND,
1028 LWS_VISIBLE LWS_EXTERN void
1029 libwebsocket_set_timeout(struct libwebsocket *wsi,
1030 enum pending_timeout reason, int secs);
1035 * When sending with websocket protocol (LWS_WRITE_TEXT or LWS_WRITE_BINARY)
1036 * the send buffer has to have LWS_SEND_BUFFER_PRE_PADDING bytes valid BEFORE
1037 * buf, and LWS_SEND_BUFFER_POST_PADDING bytes valid AFTER (buf + len).
1039 * This allows us to add protocol info before and after the data, and send as
1040 * one packet on the network without payload copying, for maximum efficiency.
1042 * So for example you need this kind of code to use libwebsocket_write with a
1045 * char buf[LWS_SEND_BUFFER_PRE_PADDING + 128 + LWS_SEND_BUFFER_POST_PADDING];
1047 * // fill your part of the buffer... for example here it's all zeros
1048 * memset(&buf[LWS_SEND_BUFFER_PRE_PADDING], 0, 128);
1050 * libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 128,
1053 * When sending LWS_WRITE_HTTP, there is no protocol addition and you can just
1054 * use the whole buffer without taking care of the above.
1058 * this is the frame nonce plus two header plus 8 length
1059 * there's an additional two for mux extension per mux nesting level
1060 * 2 byte prepend on close will already fit because control frames cannot use
1061 * the big length style
1064 #define LWS_SEND_BUFFER_PRE_PADDING (4 + 10 + (2 * MAX_MUX_RECURSION))
1065 #define LWS_SEND_BUFFER_POST_PADDING 4
1067 LWS_VISIBLE LWS_EXTERN int
1068 libwebsocket_write(struct libwebsocket *wsi, unsigned char *buf, size_t len,
1069 enum libwebsocket_write_protocol protocol);
1071 /* helper for case where buffer may be const */
1072 #define libwebsocket_write_http(wsi, buf, len) \
1073 libwebsocket_write(wsi, (unsigned char *)(buf), len, LWS_WRITE_HTTP)
1075 LWS_VISIBLE LWS_EXTERN int
1076 libwebsockets_serve_http_file(struct libwebsocket_context *context,
1077 struct libwebsocket *wsi, const char *file,
1078 const char *content_type, const char *other_headers);
1079 LWS_VISIBLE LWS_EXTERN int
1080 libwebsockets_serve_http_file_fragment(struct libwebsocket_context *context,
1081 struct libwebsocket *wsi);
1083 LWS_VISIBLE LWS_EXTERN int libwebsockets_return_http_status(
1084 struct libwebsocket_context *context,
1085 struct libwebsocket *wsi, unsigned int code,
1086 const char *html_body);
1088 LWS_VISIBLE LWS_EXTERN const struct libwebsocket_protocols *
1089 libwebsockets_get_protocol(struct libwebsocket *wsi);
1091 LWS_VISIBLE LWS_EXTERN int
1092 libwebsocket_callback_on_writable(struct libwebsocket_context *context,
1093 struct libwebsocket *wsi);
1095 LWS_VISIBLE LWS_EXTERN int
1096 libwebsocket_callback_on_writable_all_protocol(
1097 const struct libwebsocket_protocols *protocol);
1099 LWS_VISIBLE LWS_EXTERN int
1100 libwebsocket_callback_all_protocol(
1101 const struct libwebsocket_protocols *protocol, int reason);
1103 LWS_VISIBLE LWS_EXTERN int
1104 libwebsocket_get_socket_fd(struct libwebsocket *wsi);
1106 LWS_VISIBLE LWS_EXTERN int
1107 libwebsocket_is_final_fragment(struct libwebsocket *wsi);
1109 LWS_VISIBLE LWS_EXTERN unsigned char
1110 libwebsocket_get_reserved_bits(struct libwebsocket *wsi);
1112 LWS_VISIBLE LWS_EXTERN int
1113 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable);
1115 LWS_VISIBLE LWS_EXTERN void
1116 libwebsocket_rx_flow_allow_all_protocol(
1117 const struct libwebsocket_protocols *protocol);
1119 LWS_VISIBLE LWS_EXTERN size_t
1120 libwebsockets_remaining_packet_payload(struct libwebsocket *wsi);
1122 LWS_VISIBLE LWS_EXTERN struct libwebsocket *
1123 libwebsocket_client_connect(struct libwebsocket_context *clients,
1124 const char *address,
1130 const char *protocol,
1131 int ietf_version_or_minus_one);
1133 LWS_VISIBLE LWS_EXTERN struct libwebsocket *
1134 libwebsocket_client_connect_extended(struct libwebsocket_context *clients,
1135 const char *address,
1141 const char *protocol,
1142 int ietf_version_or_minus_one,
1145 LWS_VISIBLE LWS_EXTERN const char *
1146 libwebsocket_canonical_hostname(struct libwebsocket_context *context);
1149 LWS_VISIBLE LWS_EXTERN void
1150 libwebsockets_get_peer_addresses(struct libwebsocket_context *context,
1151 struct libwebsocket *wsi, int fd, char *name, int name_len,
1152 char *rip, int rip_len);
1154 LWS_VISIBLE LWS_EXTERN int
1155 libwebsockets_get_random(struct libwebsocket_context *context,
1156 void *buf, int len);
1158 LWS_VISIBLE LWS_EXTERN int
1159 lws_daemonize(const char *_lock_path);
1161 LWS_VISIBLE LWS_EXTERN int
1162 lws_send_pipe_choked(struct libwebsocket *wsi);
1164 LWS_VISIBLE LWS_EXTERN int
1165 lws_frame_is_binary(struct libwebsocket *wsi);
1167 LWS_VISIBLE LWS_EXTERN unsigned char *
1168 libwebsockets_SHA1(const unsigned char *d, size_t n, unsigned char *md);
1170 LWS_VISIBLE LWS_EXTERN int
1171 lws_b64_encode_string(const char *in, int in_len, char *out, int out_size);
1173 LWS_VISIBLE LWS_EXTERN int
1174 lws_b64_decode_string(const char *in, char *out, int out_size);
1176 LWS_VISIBLE LWS_EXTERN const char *
1177 lws_get_library_version(void);
1179 /* access to headers... only valid while headers valid */
1181 LWS_VISIBLE LWS_EXTERN int
1182 lws_hdr_total_length(struct libwebsocket *wsi, enum lws_token_indexes h);
1184 LWS_VISIBLE LWS_EXTERN int
1185 lws_hdr_copy(struct libwebsocket *wsi, char *dest, int len,
1186 enum lws_token_indexes h);
1189 * Note: this is not normally needed as a user api. It's provided in case it is
1190 * useful when integrating with other app poll loop service code.
1193 LWS_VISIBLE LWS_EXTERN int
1194 libwebsocket_read(struct libwebsocket_context *context,
1195 struct libwebsocket *wsi,
1196 unsigned char *buf, size_t len);
1198 #ifndef LWS_NO_EXTENSIONS
1199 LWS_VISIBLE LWS_EXTERN struct libwebsocket_extension *libwebsocket_get_internal_extensions();