2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010-2016 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,
24 #ifndef LIBWEBSOCKET_H_3060898B846849FF9F88F5DB59B5950C
25 #define LIBWEBSOCKET_H_3060898B846849FF9F88F5DB59B5950C
31 #include "mbed-drivers/mbed.h"
32 #include "sal-iface-eth/EthernetInterface.h"
33 #include "sockets/TCPListener.h"
34 #include "sal-stack-lwip/lwipv4_init.h"
38 using namespace mbed::Sockets::v0;
50 awaiting_on_writeable(0)
55 void set_wsi(struct lws *_wsi) { wsi = _wsi; }
56 int actual_onRX(Socket *s);
58 void onError(Socket *s, socket_error_t err);
59 void onDisconnect(TCPStream *s);
60 void onSent(Socket *s, uint16_t len);
61 void serialized_writeable(struct lws *wsi);
69 char awaiting_on_writeable;
72 class lws_conn_listener : lws_conn {
75 srv(SOCKET_STACK_LWIP_IPV4)
77 srv.setOnError(TCPStream::ErrorHandler_t(this,
78 &lws_conn_listener::onError));
81 void start(const uint16_t port); /**< start listening */
84 void onRX(Socket *s); /**< incoming data ready */
85 void onError(Socket *s, socket_error_t err); /**< if error occurs */
86 void onIncoming(TCPListener *s, void *impl); /**< new connection */
87 void onDisconnect(TCPStream *s); /**< disconnection */
100 #if defined(MBED_OPERATORS) || defined(LWS_WITH_ESP8266)
107 #include "lws_config.h"
109 #if defined(WIN32) || defined(_WIN32)
110 #ifndef WIN32_LEAN_AND_MEAN
111 #define WIN32_LEAN_AND_MEAN
114 #include <winsock2.h>
115 #include <ws2tcpip.h>
121 #define _O_RDONLY 0x0000
122 #define O_RDONLY _O_RDONLY
125 // Visual studio older than 2015 and WIN_CE has only _stricmp
126 #if (defined(_MSC_VER) && _MSC_VER < 1900) || defined(_WIN32_WCE)
127 #define strcasecmp _stricmp
128 #elif !defined(__MINGW32__)
129 #define strcasecmp stricmp
131 #define getdtablesize() 30000
133 #define LWS_INLINE __inline
135 #define LWS_WARN_UNUSED_RESULT
136 #define LWS_WARN_DEPRECATED
140 #define LWS_EXTERN extern __declspec(dllexport)
142 #define LWS_EXTERN extern __declspec(dllimport)
148 #define LWS_INVALID_FILE INVALID_HANDLE_VALUE
149 #define LWS_O_RDONLY _O_RDONLY
151 #if !defined(__MINGW32__) && (!defined(_MSC_VER) || _MSC_VER < 1900) /* Visual Studio 2015 already defines this in <stdio.h> */
152 #define lws_snprintf _snprintf
156 #define __func__ __FUNCTION__
159 #else /* NOT WIN32 */
162 #if defined(__NetBSD__) || defined(__FreeBSD__)
163 #include <netinet/in.h>
166 #define LWS_INLINE inline
167 #define LWS_O_RDONLY O_RDONLY
169 #if !defined(MBED_OPERATORS) && !defined(LWS_WITH_ESP8266)
172 #define LWS_INVALID_FILE -1
174 #define getdtablesize() (20)
175 #define LWS_INVALID_FILE NULL
178 #if defined(__GNUC__)
180 /* warn_unused_result attribute only supported by GCC 3.4 or later */
181 #if __GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
182 #define LWS_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
184 #define LWS_WARN_UNUSED_RESULT
187 #define LWS_VISIBLE __attribute__((visibility("default")))
188 #define LWS_WARN_DEPRECATED __attribute__ ((deprecated))
191 #define LWS_WARN_UNUSED_RESULT
192 #define LWS_WARN_DEPRECATED
195 #if defined(__ANDROID__)
197 #define getdtablesize() sysconf(_SC_OPEN_MAX)
204 #endif /* LWS_USE_LIBEV */
207 #ifdef LWS_HAVE_UV_VERSION_H
208 #include <uv-version.h>
210 #endif /* LWS_USE_LIBUV */
213 #define LWS_EXTERN extern
219 #include <sys/time.h>
223 #ifdef LWS_OPENSSL_SUPPORT
226 #ifdef USE_OLD_CYASSL
227 #include <cyassl/openssl/ssl.h>
228 #include <cyassl/error-ssl.h>
230 #include <wolfssl/openssl/ssl.h>
231 #include <wolfssl/error-ssl.h>
232 #endif /* not USE_OLD_CYASSL */
234 #if defined(LWS_USE_POLARSSL)
235 #include <polarssl/ssl.h>
236 struct lws_polarssl_context {
237 x509_crt ca; /**< ca */
238 x509_crt certificate; /**< cert */
239 rsa_context key; /**< key */
241 typedef struct lws_polarssl_context SSL_CTX;
242 typedef ssl_context SSL;
244 #if defined(LWS_USE_MBEDTLS)
245 #include <mbedtls/ssl.h>
247 #include <openssl/ssl.h>
248 #include <openssl/err.h>
249 #endif /* not USE_MBEDTLS */
250 #endif /* not USE_POLARSSL */
251 #endif /* not USE_WOLFSSL */
255 #define CONTEXT_PORT_NO_LISTEN -1
257 /** \defgroup log Logging
261 * Lws provides flexible and filterable logging facilities, which can be
262 * used inside lws and in user code.
264 * Log categories may be individually filtered bitwise, and directed to built-in
265 * sinks for syslog-compatible logging, or a user-defined function.
269 enum lws_log_levels {
279 LLL_LATENCY = 1 << 9,
281 LLL_COUNT = 10 /* set to count of valid flags */
284 LWS_VISIBLE LWS_EXTERN void _lws_log(int filter, const char *format, ...);
285 LWS_VISIBLE LWS_EXTERN void _lws_logv(int filter, const char *format, va_list vl);
287 * lwsl_timestamp: generate logging timestamp string
289 * \param level: logging level
290 * \param p: char * buffer to take timestamp
291 * \param len: length of p
293 * returns length written in p
295 LWS_VISIBLE LWS_EXTERN int
296 lwsl_timestamp(int level, char *p, int len);
298 #define lwsl_err(...) _lws_log(LLL_ERR, __VA_ARGS__)
300 #if !defined(LWS_WITH_NO_LOGS)
301 /* notice, warn and log are always compiled in */
302 #define lwsl_warn(...) _lws_log(LLL_WARN, __VA_ARGS__)
303 #define lwsl_notice(...) _lws_log(LLL_NOTICE, __VA_ARGS__)
306 * weaker logging can be deselected at configure time using --disable-debug
307 * that gets rid of the overhead of checking while keeping _warn and _err
311 #if defined(LWS_WITH_ESP8266)
316 #if defined(LWS_WITH_NO_LOGS)
317 /* notice, warn and log are always compiled in */
318 //#define lwsl_err(...) _lws_log(LLL_ERR, __VA_ARGS__)
319 #define lwsl_warn(...) _lws_log(LLL_WARN, __VA_ARGS__)
320 #define lwsl_notice(...) _lws_log(LLL_NOTICE, __VA_ARGS__)
322 #define lwsl_info(...) _lws_log(LLL_INFO, __VA_ARGS__)
323 #define lwsl_debug(...) _lws_log(LLL_DEBUG, __VA_ARGS__)
324 #define lwsl_parser(...) _lws_log(LLL_PARSER, __VA_ARGS__)
325 #define lwsl_header(...) _lws_log(LLL_HEADER, __VA_ARGS__)
326 #define lwsl_ext(...) _lws_log(LLL_EXT, __VA_ARGS__)
327 #define lwsl_client(...) _lws_log(LLL_CLIENT, __VA_ARGS__)
328 #define lwsl_latency(...) _lws_log(LLL_LATENCY, __VA_ARGS__)
330 * lwsl_hexdump() - helper to hexdump a buffer (DEBUG builds only)
332 * \param buf: buffer start to dump
333 * \param len: length of buffer to dump
335 LWS_VISIBLE LWS_EXTERN void lwsl_hexdump(void *buf, size_t len);
338 #if defined(LWS_WITH_NO_LOGS)
339 //#define lwsl_err(...) do {} while(0)
340 #define lwsl_warn(...) do {} while(0)
341 #define lwsl_notice(...) do {} while(0)
343 #define lwsl_info(...) do {} while(0)
344 #define lwsl_debug(...) do {} while(0)
345 #define lwsl_parser(...) do {} while(0)
346 #define lwsl_header(...) do {} while(0)
347 #define lwsl_ext(...) do {} while(0)
348 #define lwsl_client(...) do {} while(0)
349 #define lwsl_latency(...) do {} while(0)
350 #define lwsl_hexdump(a, b)
355 * lws_set_log_level() - Set the logging bitfield
356 * \param level: OR together the LLL_ debug contexts you want output from
357 * \param log_emit_function: NULL to leave it as it is, or a user-supplied
358 * function to perform log string emission instead of
359 * the default stderr one.
361 * log level defaults to "err", "warn" and "notice" contexts enabled and
362 * emission on stderr.
364 LWS_VISIBLE LWS_EXTERN void
365 lws_set_log_level(int level,
366 void (*log_emit_function)(int level, const char *line));
369 * lwsl_emit_syslog() - helper log emit function writes to system log
371 * \param level: one of LLL_ log level indexes
372 * \param line: log string
374 * You use this by passing the function pointer to lws_set_log_level(), to set
375 * it as the log emit function, it is not called directly.
377 LWS_VISIBLE LWS_EXTERN void
378 lwsl_emit_syslog(int level, const char *line);
385 #ifndef lws_container_of
386 #define lws_container_of(P,T,M) ((T *)((char *)(P) - offsetof(T, M)))
392 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
395 /* api change list for user code to test against */
397 #define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_ARG
399 /* the struct lws_protocols has the id field present */
400 #define LWS_FEATURE_PROTOCOLS_HAS_ID_FIELD
402 /* you can call lws_get_peer_write_allowance */
403 #define LWS_FEATURE_PROTOCOLS_HAS_PEER_WRITE_ALLOWANCE
405 /* extra parameter introduced in 917f43ab821 */
406 #define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_LEN
408 /* File operations stuff exists */
409 #define LWS_FEATURE_FOPS
413 typedef SOCKET lws_sockfd_type;
414 typedef HANDLE lws_filefd_type;
415 #define lws_sockfd_valid(sfd) (!!sfd)
417 lws_sockfd_type fd; /**< file descriptor */
418 SHORT events; /**< which events to respond to */
419 SHORT revents; /**< which events happened */
421 #define LWS_POLLHUP (FD_CLOSE)
422 #define LWS_POLLIN (FD_READ | FD_ACCEPT)
423 #define LWS_POLLOUT (FD_WRITE)
426 #if defined(MBED_OPERATORS)
427 /* it's a class lws_conn * */
428 typedef void * lws_sockfd_type;
429 typedef void * lws_filefd_type;
430 #define lws_sockfd_valid(sfd) (!!sfd)
432 lws_sockfd_type fd; /**< fd related to */
433 short events; /**< which POLL... events to respond to */
434 short revents; /**< which POLL... events occurred */
436 #define POLLIN 0x0001
437 #define POLLPRI 0x0002
438 #define POLLOUT 0x0004
439 #define POLLERR 0x0008
440 #define POLLHUP 0x0010
441 #define POLLNVAL 0x0020
445 void * mbed3_create_tcp_stream_socket(void);
446 void mbed3_delete_tcp_stream_socket(void *sockfd);
447 void mbed3_tcp_stream_bind(void *sock, int port, struct lws *);
448 void mbed3_tcp_stream_accept(void *sock, struct lws *);
450 #if defined(LWS_WITH_ESP8266)
452 #include <user_interface.h>
455 typedef struct espconn * lws_sockfd_type;
456 typedef void * lws_filefd_type;
457 #define lws_sockfd_valid(sfd) (!!sfd)
459 lws_sockfd_type fd; /**< fd related to */
460 short events; /**< which POLL... events to respond to */
461 short revents; /**< which POLL... events occurred */
463 #define POLLIN 0x0001
464 #define POLLPRI 0x0002
465 #define POLLOUT 0x0004
466 #define POLLERR 0x0008
467 #define POLLHUP 0x0010
468 #define POLLNVAL 0x0020
472 lws_sockfd_type esp8266_create_tcp_listen_socket(struct lws_vhost *vh);
473 void esp8266_tcp_stream_accept(lws_sockfd_type fd, struct lws *wsi);
479 int ets_snprintf(char *str, size_t size, const char *format, ...);
480 #define snprintf ets_snprintf
482 typedef os_timer_t uv_timer_t;
483 typedef void uv_cb_t(uv_timer_t *);
485 void os_timer_disarm(void *);
486 void os_timer_setfn(os_timer_t *, os_timer_func_t *, void *);
488 void ets_timer_arm_new(os_timer_t *, int, int, int);
490 //void os_timer_arm(os_timer_t *, int, int);
492 #define UV_VERSION_MAJOR 1
494 #define lws_uv_getloop(a, b) (NULL)
496 static inline void uv_timer_init(void *l, uv_timer_t *t)
499 memset(t, 0, sizeof(*t));
503 static inline void uv_timer_start(uv_timer_t *t, uv_cb_t *cb, int first, int rep)
505 os_timer_setfn(t, (os_timer_func_t *)cb, t);
507 os_timer_arm(t, first, !!rep);
510 static inline void uv_timer_stop(uv_timer_t *t)
516 typedef int lws_sockfd_type;
517 typedef int lws_filefd_type;
518 #define lws_sockfd_valid(sfd) (sfd >= 0)
522 #define lws_pollfd pollfd
523 #define LWS_POLLHUP (POLLHUP|POLLERR)
524 #define LWS_POLLIN (POLLIN)
525 #define LWS_POLLOUT (POLLOUT)
528 /** struct lws_pollargs - argument structure for all external poll related calls
529 * passed in via 'in' */
530 struct lws_pollargs {
531 lws_sockfd_type fd; /**< applicable socket descriptor */
532 int events; /**< the new event mask */
533 int prev_events; /**< the previous event mask */
537 struct lws_token_limits;
539 /*! \defgroup wsclose Websocket Close
541 * ##Websocket close frame control
543 * When we close a ws connection, we can send a reason code and a short
544 * UTF-8 description back with the close packet.
549 * NOTE: These public enums are part of the abi. If you want to add one,
550 * add it at where specified so existing users are unaffected.
552 /** enum lws_close_status - RFC6455 close status codes */
553 enum lws_close_status {
554 LWS_CLOSE_STATUS_NOSTATUS = 0,
555 LWS_CLOSE_STATUS_NORMAL = 1000,
556 /**< 1000 indicates a normal closure, meaning that the purpose for
557 which the connection was established has been fulfilled. */
558 LWS_CLOSE_STATUS_GOINGAWAY = 1001,
559 /**< 1001 indicates that an endpoint is "going away", such as a server
560 going down or a browser having navigated away from a page. */
561 LWS_CLOSE_STATUS_PROTOCOL_ERR = 1002,
562 /**< 1002 indicates that an endpoint is terminating the connection due
563 to a protocol error. */
564 LWS_CLOSE_STATUS_UNACCEPTABLE_OPCODE = 1003,
565 /**< 1003 indicates that an endpoint is terminating the connection
566 because it has received a type of data it cannot accept (e.g., an
567 endpoint that understands only text data MAY send this if it
568 receives a binary message). */
569 LWS_CLOSE_STATUS_RESERVED = 1004,
570 /**< Reserved. The specific meaning might be defined in the future. */
571 LWS_CLOSE_STATUS_NO_STATUS = 1005,
572 /**< 1005 is a reserved value and MUST NOT be set as a status code in a
573 Close control frame by an endpoint. It is designated for use in
574 applications expecting a status code to indicate that no status
575 code was actually present. */
576 LWS_CLOSE_STATUS_ABNORMAL_CLOSE = 1006,
577 /**< 1006 is a reserved value and MUST NOT be set as a status code in a
578 Close control frame by an endpoint. It is designated for use in
579 applications expecting a status code to indicate that the
580 connection was closed abnormally, e.g., without sending or
581 receiving a Close control frame. */
582 LWS_CLOSE_STATUS_INVALID_PAYLOAD = 1007,
583 /**< 1007 indicates that an endpoint is terminating the connection
584 because it has received data within a message that was not
585 consistent with the type of the message (e.g., non-UTF-8 [RFC3629]
586 data within a text message). */
587 LWS_CLOSE_STATUS_POLICY_VIOLATION = 1008,
588 /**< 1008 indicates that an endpoint is terminating the connection
589 because it has received a message that violates its policy. This
590 is a generic status code that can be returned when there is no
591 other more suitable status code (e.g., 1003 or 1009) or if there
592 is a need to hide specific details about the policy. */
593 LWS_CLOSE_STATUS_MESSAGE_TOO_LARGE = 1009,
594 /**< 1009 indicates that an endpoint is terminating the connection
595 because it has received a message that is too big for it to
597 LWS_CLOSE_STATUS_EXTENSION_REQUIRED = 1010,
598 /**< 1010 indicates that an endpoint (client) is terminating the
599 connection because it has expected the server to negotiate one or
600 more extension, but the server didn't return them in the response
601 message of the WebSocket handshake. The list of extensions that
602 are needed SHOULD appear in the /reason/ part of the Close frame.
603 Note that this status code is not used by the server, because it
604 can fail the WebSocket handshake instead */
605 LWS_CLOSE_STATUS_UNEXPECTED_CONDITION = 1011,
606 /**< 1011 indicates that a server is terminating the connection because
607 it encountered an unexpected condition that prevented it from
608 fulfilling the request. */
609 LWS_CLOSE_STATUS_TLS_FAILURE = 1015,
610 /**< 1015 is a reserved value and MUST NOT be set as a status code in a
611 Close control frame by an endpoint. It is designated for use in
612 applications expecting a status code to indicate that the
613 connection was closed due to a failure to perform a TLS handshake
614 (e.g., the server certificate can't be verified). */
616 /****** add new things just above ---^ ******/
618 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY = 9999,
622 * lws_close_reason - Set reason and aux data to send with Close packet
623 * If you are going to return nonzero from the callback
624 * requesting the connection to close, you can optionally
625 * call this to set the reason the peer will be told if
628 * \param wsi: The websocket connection to set the close reason on
629 * \param status: A valid close status from websocket standard
630 * \param buf: NULL or buffer containing up to 124 bytes of auxiliary data
631 * \param len: Length of data in \param buf to send
633 LWS_VISIBLE LWS_EXTERN void
634 lws_close_reason(struct lws *wsi, enum lws_close_status status,
635 unsigned char *buf, size_t len);
641 /* needed even with extensions disabled for create context */
642 struct lws_extension;
644 /*! \defgroup usercb User Callback
646 * ##User protocol callback
648 * The protocol callback is the primary way lws interacts with
649 * user code. For one of a list of a few dozen reasons the callback gets
650 * called at some event to be handled.
652 * All of the events can be ignored, returning 0 is taken as "OK" and returning
653 * nonzero in most cases indicates that the connection should be closed.
659 * NOTE: These public enums are part of the abi. If you want to add one,
660 * add it at where specified so existing users are unaffected.
662 /** enum lws_callback_reasons - reason you're getting a protocol callback */
663 enum lws_callback_reasons {
664 LWS_CALLBACK_ESTABLISHED = 0,
665 /**< (VH) after the server completes a handshake with an incoming
666 * client. If you built the library with ssl support, in is a
667 * pointer to the ssl struct associated with the connection or NULL.*/
668 LWS_CALLBACK_CLIENT_CONNECTION_ERROR = 1,
669 /**< the request client connection has been unable to complete a
670 * handshake with the remote server. If in is non-NULL, you can
671 * find an error string of length len where it points to
673 * Diagnostic strings that may be returned include
675 * "getaddrinfo (ipv6) failed"
676 * "unknown address family"
677 * "getaddrinfo (ipv4) failed"
678 * "set socket opts failed"
679 * "insert wsi failed"
680 * "lws_ssl_client_connect1 failed"
681 * "lws_ssl_client_connect2 failed"
685 * "HS: Redirect code but no Location"
686 * "HS: URI did not parse"
687 * "HS: Redirect failed"
688 * "HS: Server did not return 200"
690 * "HS: disallowed by client filter"
691 * "HS: disallowed at ESTABLISHED"
692 * "HS: ACCEPT missing"
693 * "HS: ws upgrade response not 101"
694 * "HS: UPGRADE missing"
695 * "HS: Upgrade to something other than websocket"
696 * "HS: CONNECTION missing"
697 * "HS: UPGRADE malformed"
698 * "HS: PROTOCOL malformed"
699 * "HS: Cannot match protocol"
700 * "HS: EXT: list too big"
701 * "HS: EXT: failed setting defaults"
702 * "HS: EXT: failed parsing defaults"
703 * "HS: EXT: failed parsing options"
704 * "HS: EXT: Rejects server options"
705 * "HS: EXT: unknown ext"
706 * "HS: Accept hash wrong"
707 * "HS: Rejected by filter cb"
709 * "HS: SO_SNDBUF failed"
710 * "HS: Rejected at CLIENT_ESTABLISHED"
712 LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH = 2,
713 /**< this is the last chance for the client user code to examine the
714 * http headers and decide to reject the connection. If the
715 * content in the headers is interesting to the
716 * client (url, etc) it needs to copy it out at
717 * this point since it will be destroyed before
718 * the CLIENT_ESTABLISHED call */
719 LWS_CALLBACK_CLIENT_ESTABLISHED = 3,
720 /**< after your client connection completed
721 * a handshake with the remote server */
722 LWS_CALLBACK_CLOSED = 4,
723 /**< when the websocket session ends */
724 LWS_CALLBACK_CLOSED_HTTP = 5,
725 /**< when a HTTP (non-websocket) session ends */
726 LWS_CALLBACK_RECEIVE = 6,
727 /**< data has appeared for this server endpoint from a
728 * remote client, it can be found at *in and is
730 LWS_CALLBACK_RECEIVE_PONG = 7,
731 /**< servers receive PONG packets with this callback reason */
732 LWS_CALLBACK_CLIENT_RECEIVE = 8,
733 /**< data has appeared from the server for the client connection, it
734 * can be found at *in and is len bytes long */
735 LWS_CALLBACK_CLIENT_RECEIVE_PONG = 9,
736 /**< clients receive PONG packets with this callback reason */
737 LWS_CALLBACK_CLIENT_WRITEABLE = 10,
738 /**< If you call lws_callback_on_writable() on a connection, you will
739 * get one of these callbacks coming when the connection socket
740 * is able to accept another write packet without blocking.
741 * If it already was able to take another packet without blocking,
742 * you'll get this callback at the next call to the service loop
743 * function. Notice that CLIENTs get LWS_CALLBACK_CLIENT_WRITEABLE
744 * and servers get LWS_CALLBACK_SERVER_WRITEABLE. */
745 LWS_CALLBACK_SERVER_WRITEABLE = 11,
746 /**< See LWS_CALLBACK_CLIENT_WRITEABLE */
747 LWS_CALLBACK_HTTP = 12,
748 /**< an http request has come from a client that is not
749 * asking to upgrade the connection to a websocket
750 * one. This is a chance to serve http content,
751 * for example, to send a script to the client
752 * which will then open the websockets connection.
753 * in points to the URI path requested and
754 * lws_serve_http_file() makes it very
755 * simple to send back a file to the client.
756 * Normally after sending the file you are done
757 * with the http connection, since the rest of the
758 * activity will come by websockets from the script
759 * that was delivered by http, so you will want to
760 * return 1; to close and free up the connection. */
761 LWS_CALLBACK_HTTP_BODY = 13,
762 /**< the next len bytes data from the http
763 * request body HTTP connection is now available in in. */
764 LWS_CALLBACK_HTTP_BODY_COMPLETION = 14,
765 /**< the expected amount of http request body has been delivered */
766 LWS_CALLBACK_HTTP_FILE_COMPLETION = 15,
767 /**< a file requested to be sent down http link has completed. */
768 LWS_CALLBACK_HTTP_WRITEABLE = 16,
769 /**< you can write more down the http protocol link now. */
770 LWS_CALLBACK_FILTER_NETWORK_CONNECTION = 17,
771 /**< called when a client connects to
772 * the server at network level; the connection is accepted but then
773 * passed to this callback to decide whether to hang up immediately
774 * or not, based on the client IP. in contains the connection
775 * socket's descriptor. Since the client connection information is
776 * not available yet, wsi still pointing to the main server socket.
777 * Return non-zero to terminate the connection before sending or
778 * receiving anything. Because this happens immediately after the
779 * network connection from the client, there's no websocket protocol
780 * selected yet so this callback is issued only to protocol 0. */
781 LWS_CALLBACK_FILTER_HTTP_CONNECTION = 18,
782 /**< called when the request has
783 * been received and parsed from the client, but the response is
784 * not sent yet. Return non-zero to disallow the connection.
785 * user is a pointer to the connection user space allocation,
786 * in is the URI, eg, "/"
787 * In your handler you can use the public APIs
788 * lws_hdr_total_length() / lws_hdr_copy() to access all of the
789 * headers using the header enums lws_token_indexes from
790 * libwebsockets.h to check for and read the supported header
791 * presence and content before deciding to allow the http
792 * connection to proceed or to kill the connection. */
793 LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED = 19,
794 /**< A new client just had
795 * been connected, accepted, and instantiated into the pool. This
796 * callback allows setting any relevant property to it. Because this
797 * happens immediately after the instantiation of a new client,
798 * there's no websocket protocol selected yet so this callback is
799 * issued only to protocol 0. Only wsi is defined, pointing to the
800 * new client, and the return value is ignored. */
801 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION = 20,
802 /**< called when the handshake has
803 * been received and parsed from the client, but the response is
804 * not sent yet. Return non-zero to disallow the connection.
805 * user is a pointer to the connection user space allocation,
806 * in is the requested protocol name
807 * In your handler you can use the public APIs
808 * lws_hdr_total_length() / lws_hdr_copy() to access all of the
809 * headers using the header enums lws_token_indexes from
810 * libwebsockets.h to check for and read the supported header
811 * presence and content before deciding to allow the handshake
812 * to proceed or to kill the connection. */
813 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS = 21,
814 /**< if configured for
815 * including OpenSSL support, this callback allows your user code
816 * to perform extra SSL_CTX_load_verify_locations() or similar
817 * calls to direct OpenSSL where to find certificates the client
818 * can use to confirm the remote server identity. user is the
819 * OpenSSL SSL_CTX* */
820 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS = 22,
821 /**< if configured for
822 * including OpenSSL support, this callback allows your user code
823 * to load extra certifcates into the server which allow it to
824 * verify the validity of certificates returned by clients. user
825 * is the server's OpenSSL SSL_CTX* */
826 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION = 23,
827 /**< if the libwebsockets vhost was created with the option
828 * LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT, then this
829 * callback is generated during OpenSSL verification of the cert
830 * sent from the client. It is sent to protocol[0] callback as
831 * no protocol has been negotiated on the connection yet.
832 * Notice that the libwebsockets context and wsi are both NULL
833 * during this callback. See
834 * http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html
835 * to understand more detail about the OpenSSL callback that
836 * generates this libwebsockets callback and the meanings of the
837 * arguments passed. In this callback, user is the x509_ctx,
838 * in is the ssl pointer and len is preverify_ok
839 * Notice that this callback maintains libwebsocket return
840 * conventions, return 0 to mean the cert is OK or 1 to fail it.
841 * This also means that if you don't handle this callback then
842 * the default callback action of returning 0 allows the client
844 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER = 24,
845 /**< this callback happens
846 * when a client handshake is being compiled. user is NULL,
847 * in is a char **, it's pointing to a char * which holds the
848 * next location in the header buffer where you can add
849 * headers, and len is the remaining space in the header buffer,
850 * which is typically some hundreds of bytes. So, to add a canned
851 * cookie, your handler code might look similar to:
853 * char **p = (char **)in;
858 * *p += sprintf(*p, "Cookie: a=b\x0d\x0a");
862 * Notice if you add anything, you just have to take care about
863 * the CRLF on the line you added. Obviously this callback is
864 * optional, if you don't handle it everything is fine.
866 * Notice the callback is coming to protocols[0] all the time,
867 * because there is no specific protocol negotiated yet. */
868 LWS_CALLBACK_CONFIRM_EXTENSION_OKAY = 25,
869 /**< When the server handshake code
870 * sees that it does support a requested extension, before
871 * accepting the extension by additing to the list sent back to
872 * the client it gives this callback just to check that it's okay
873 * to use that extension. It calls back to the requested protocol
874 * and with in being the extension name, len is 0 and user is
875 * valid. Note though at this time the ESTABLISHED callback hasn't
876 * happened yet so if you initialize user content there, user
877 * content during this callback might not be useful for anything.
878 * Notice this callback comes to protocols[0]. */
879 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED = 26,
881 * connection is being prepared to start a handshake to a server,
882 * each supported extension is checked with protocols[0] callback
883 * with this reason, giving the user code a chance to suppress the
884 * claim to support that extension by returning non-zero. If
885 * unhandled, by default 0 will be returned and the extension
886 * support included in the header to the server. Notice this
887 * callback comes to protocols[0]. */
888 LWS_CALLBACK_PROTOCOL_INIT = 27,
889 /**< One-time call per protocol, per-vhost using it, so it can
890 * do initial setup / allocations etc */
891 LWS_CALLBACK_PROTOCOL_DESTROY = 28,
892 /**< One-time call per protocol, per-vhost using it, indicating
893 * this protocol won't get used at all after this callback, the
894 * vhost is getting destroyed. Take the opportunity to
895 * deallocate everything that was allocated by the protocol. */
896 LWS_CALLBACK_WSI_CREATE = 29,
897 /**< outermost (earliest) wsi create notification to protocols[0] */
898 LWS_CALLBACK_WSI_DESTROY = 30,
899 /**< outermost (latest) wsi destroy notification to protocols[0] */
900 LWS_CALLBACK_GET_THREAD_ID = 31,
901 /**< lws can accept callback when writable requests from other
902 * threads, if you implement this callback and return an opaque
903 * current thread ID integer. */
905 /* external poll() management support */
906 LWS_CALLBACK_ADD_POLL_FD = 32,
907 /**< lws normally deals with its poll() or other event loop
908 * internally, but in the case you are integrating with another
909 * server you will need to have lws sockets share a
910 * polling array with the other server. This and the other
911 * POLL_FD related callbacks let you put your specialized
912 * poll array interface code in the callback for protocol 0, the
913 * first protocol you support, usually the HTTP protocol in the
915 * This callback happens when a socket needs to be
916 * added to the polling loop: in points to a struct
917 * lws_pollargs; the fd member of the struct is the file
918 * descriptor, and events contains the active events
920 * If you are using the internal lws polling / event loop
921 * you can just ignore these callbacks. */
922 LWS_CALLBACK_DEL_POLL_FD = 33,
923 /**< This callback happens when a socket descriptor
924 * needs to be removed from an external polling array. in is
925 * again the struct lws_pollargs containing the fd member
926 * to be removed. If you are using the internal polling
927 * loop, you can just ignore it. */
928 LWS_CALLBACK_CHANGE_MODE_POLL_FD = 34,
929 /**< This callback happens when lws wants to modify the events for
931 * in is the struct lws_pollargs with the fd to change.
932 * The new event mask is in events member and the old mask is in
933 * the prev_events member.
934 * If you are using the internal polling loop, you can just ignore
936 LWS_CALLBACK_LOCK_POLL = 35,
937 /**< These allow the external poll changes driven
938 * by lws to participate in an external thread locking
939 * scheme around the changes, so the whole thing is threadsafe.
940 * These are called around three activities in the library,
941 * - inserting a new wsi in the wsi / fd table (len=1)
942 * - deleting a wsi from the wsi / fd table (len=1)
943 * - changing a wsi's POLLIN/OUT state (len=0)
944 * Locking and unlocking external synchronization objects when
945 * len == 1 allows external threads to be synchronized against
946 * wsi lifecycle changes if it acquires the same lock for the
947 * duration of wsi dereference from the other thread context. */
948 LWS_CALLBACK_UNLOCK_POLL = 36,
949 /**< See LWS_CALLBACK_LOCK_POLL, ignore if using lws internal poll */
951 LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY = 37,
952 /**< if configured for including OpenSSL support but no private key
953 * file has been specified (ssl_private_key_filepath is NULL), this is
954 * called to allow the user to set the private key directly via
955 * libopenssl and perform further operations if required; this might be
956 * useful in situations where the private key is not directly accessible
957 * by the OS, for example if it is stored on a smartcard.
958 * user is the server's OpenSSL SSL_CTX* */
959 LWS_CALLBACK_WS_PEER_INITIATED_CLOSE = 38,
960 /**< The peer has sent an unsolicited Close WS packet. in and
961 * len are the optional close code (first 2 bytes, network
962 * order) and the optional additional information which is not
963 * defined in the standard, and may be a string or non-human- readable data.
964 * If you return 0 lws will echo the close and then close the
965 * connection. If you return nonzero lws will just close the
968 LWS_CALLBACK_WS_EXT_DEFAULTS = 39,
971 LWS_CALLBACK_CGI = 40,
973 LWS_CALLBACK_CGI_TERMINATED = 41,
975 LWS_CALLBACK_CGI_STDIN_DATA = 42,
977 LWS_CALLBACK_CGI_STDIN_COMPLETED = 43,
979 LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP = 44,
981 LWS_CALLBACK_CLOSED_CLIENT_HTTP = 45,
983 LWS_CALLBACK_RECEIVE_CLIENT_HTTP = 46,
985 LWS_CALLBACK_COMPLETED_CLIENT_HTTP = 47,
987 LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ = 48,
989 LWS_CALLBACK_HTTP_BIND_PROTOCOL = 49,
991 LWS_CALLBACK_HTTP_DROP_PROTOCOL = 50,
993 LWS_CALLBACK_CHECK_ACCESS_RIGHTS = 51,
995 LWS_CALLBACK_PROCESS_HTML = 52,
997 LWS_CALLBACK_ADD_HEADERS = 53,
999 LWS_CALLBACK_SESSION_INFO = 54,
1002 LWS_CALLBACK_GS_EVENT = 55,
1004 LWS_CALLBACK_HTTP_PMO = 56,
1005 /**< per-mount options for this connection, called before
1006 * the normal LWS_CALLBACK_HTTP when the mount has per-mount
1009 LWS_CALLBACK_CLIENT_HTTP_WRITEABLE = 57,
1010 /**< when doing an HTTP type client connection, you can call
1011 * lws_client_http_body_pending(wsi, 1) from
1012 * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER to get these callbacks
1013 * sending the HTTP headers.
1015 * From this callback, when you have sent everything, you should let
1016 * lws know by calling lws_client_http_body_pending(wsi, 0)
1019 /****** add new things just above ---^ ******/
1021 LWS_CALLBACK_USER = 1000,
1022 /**< user code can use any including / above without fear of clashes */
1028 * typedef lws_callback_function() - User server actions
1029 * \param wsi: Opaque websocket instance pointer
1030 * \param reason: The reason for the call
1031 * \param user: Pointer to per-session user data allocated by library
1032 * \param in: Pointer used for some callback reasons
1033 * \param len: Length set for some callback reasons
1035 * This callback is the way the user controls what is served. All the
1036 * protocol detail is hidden and handled by the library.
1038 * For each connection / session there is user data allocated that is
1039 * pointed to by "user". You set the size of this user data area when
1040 * the library is initialized with lws_create_server.
1043 lws_callback_function(struct lws *wsi, enum lws_callback_reasons reason,
1044 void *user, void *in, size_t len);
1047 /*! \defgroup extensions
1049 * ##Extension releated functions
1051 * Ws defines optional extensions, lws provides the ability to implement these
1052 * in user code if so desired.
1054 * We provide one extensions permessage-deflate.
1059 * NOTE: These public enums are part of the abi. If you want to add one,
1060 * add it at where specified so existing users are unaffected.
1062 enum lws_extension_callback_reasons {
1063 LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT = 0,
1064 LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT = 1,
1065 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT = 2,
1066 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT = 3,
1067 LWS_EXT_CB_CONSTRUCT = 4,
1068 LWS_EXT_CB_CLIENT_CONSTRUCT = 5,
1069 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE = 6,
1070 LWS_EXT_CB_CHECK_OK_TO_PROPOSE_EXTENSION = 7,
1071 LWS_EXT_CB_DESTROY = 8,
1072 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING = 9,
1073 LWS_EXT_CB_ANY_WSI_ESTABLISHED = 10,
1074 LWS_EXT_CB_PACKET_RX_PREPARSE = 11,
1075 LWS_EXT_CB_PACKET_TX_PRESEND = 12,
1076 LWS_EXT_CB_PACKET_TX_DO_SEND = 13,
1077 LWS_EXT_CB_HANDSHAKE_REPLY_TX = 14,
1078 LWS_EXT_CB_FLUSH_PENDING_TX = 15,
1079 LWS_EXT_CB_EXTENDED_PAYLOAD_RX = 16,
1080 LWS_EXT_CB_CAN_PROXY_CLIENT_CONNECTION = 17,
1081 LWS_EXT_CB_1HZ = 18,
1082 LWS_EXT_CB_REQUEST_ON_WRITEABLE = 19,
1083 LWS_EXT_CB_IS_WRITEABLE = 20,
1084 LWS_EXT_CB_PAYLOAD_TX = 21,
1085 LWS_EXT_CB_PAYLOAD_RX = 22,
1086 LWS_EXT_CB_OPTION_DEFAULT = 23,
1087 LWS_EXT_CB_OPTION_SET = 24,
1088 LWS_EXT_CB_OPTION_CONFIRM = 25,
1089 LWS_EXT_CB_NAMED_OPTION_SET = 26,
1091 /****** add new things just above ---^ ******/
1094 /** enum lws_ext_options_types */
1095 enum lws_ext_options_types {
1096 EXTARG_NONE, /**< does not take an argument */
1097 EXTARG_DEC, /**< requires a decimal argument */
1098 EXTARG_OPT_DEC /**< may have an optional decimal argument */
1100 /* Add new things just above here ---^
1101 * This is part of the ABI, don't needlessly break compatibility */
1104 /** struct lws_ext_options - Option arguments to the extension. These are
1105 * used in the negotiation at ws upgrade time.
1106 * The helper function lws_ext_parse_options()
1107 * uses these to generate callbacks */
1108 struct lws_ext_options {
1109 const char *name; /**< Option name, eg, "server_no_context_takeover" */
1110 enum lws_ext_options_types type; /**< What kind of args the option can take */
1112 /* Add new things just above here ---^
1113 * This is part of the ABI, don't needlessly break compatibility */
1116 /** struct lws_ext_option_arg */
1117 struct lws_ext_option_arg {
1118 const char *option_name; /**< may be NULL, option_index used then */
1119 int option_index; /**< argument ordinal to use if option_name missing */
1120 const char *start; /**< value */
1121 int len; /**< length of value */
1125 * typedef lws_extension_callback_function() - Hooks to allow extensions to operate
1126 * \param context: Websockets context
1127 * \param ext: This extension
1128 * \param wsi: Opaque websocket instance pointer
1129 * \param reason: The reason for the call
1130 * \param user: Pointer to ptr to per-session user data allocated by library
1131 * \param in: Pointer used for some callback reasons
1132 * \param len: Length set for some callback reasons
1134 * Each extension that is active on a particular connection receives
1135 * callbacks during the connection lifetime to allow the extension to
1136 * operate on websocket data and manage itself.
1138 * Libwebsockets takes care of allocating and freeing "user" memory for
1139 * each active extension on each connection. That is what is pointed to
1140 * by the user parameter.
1142 * LWS_EXT_CB_CONSTRUCT: called when the server has decided to
1143 * select this extension from the list provided by the client,
1144 * just before the server will send back the handshake accepting
1145 * the connection with this extension active. This gives the
1146 * extension a chance to initialize its connection context found
1149 * LWS_EXT_CB_CLIENT_CONSTRUCT: same as LWS_EXT_CB_CONSTRUCT
1150 * but called when client is instantiating this extension. Some
1151 * extensions will work the same on client and server side and then
1152 * you can just merge handlers for both CONSTRUCTS.
1154 * LWS_EXT_CB_DESTROY: called when the connection the extension was
1155 * being used on is about to be closed and deallocated. It's the
1156 * last chance for the extension to deallocate anything it has
1157 * allocated in the user data (pointed to by user) before the
1158 * user data is deleted. This same callback is used whether you
1159 * are in client or server instantiation context.
1161 * LWS_EXT_CB_PACKET_RX_PREPARSE: when this extension was active on
1162 * a connection, and a packet of data arrived at the connection,
1163 * it is passed to this callback to give the extension a chance to
1164 * change the data, eg, decompress it. user is pointing to the
1165 * extension's private connection context data, in is pointing
1166 * to an lws_tokens struct, it consists of a char * pointer called
1167 * token, and an int called token_len. At entry, these are
1168 * set to point to the received buffer and set to the content
1169 * length. If the extension will grow the content, it should use
1170 * a new buffer allocated in its private user context data and
1171 * set the pointed-to lws_tokens members to point to its buffer.
1173 * LWS_EXT_CB_PACKET_TX_PRESEND: this works the same way as
1174 * LWS_EXT_CB_PACKET_RX_PREPARSE above, except it gives the
1175 * extension a chance to change websocket data just before it will
1176 * be sent out. Using the same lws_token pointer scheme in in,
1177 * the extension can change the buffer and the length to be
1178 * transmitted how it likes. Again if it wants to grow the
1179 * buffer safely, it should copy the data into its own buffer and
1180 * set the lws_tokens token pointer to it.
1182 * LWS_EXT_CB_ARGS_VALIDATE:
1185 lws_extension_callback_function(struct lws_context *context,
1186 const struct lws_extension *ext, struct lws *wsi,
1187 enum lws_extension_callback_reasons reason,
1188 void *user, void *in, size_t len);
1190 /** struct lws_extension - An extension we support */
1191 struct lws_extension {
1192 const char *name; /**< Formal extension name, eg, "permessage-deflate" */
1193 lws_extension_callback_function *callback; /**< Service callback */
1194 const char *client_offer; /**< String containing exts and options client offers */
1196 /* Add new things just above here ---^
1197 * This is part of the ABI, don't needlessly break compatibility */
1201 * lws_set_extension_option(): set extension option if possible
1203 * \param wsi: websocket connection
1204 * \param ext_name: name of ext, like "permessage-deflate"
1205 * \param opt_name: name of option, like "rx_buf_size"
1206 * \param opt_val: value to set option to
1208 LWS_VISIBLE LWS_EXTERN int
1209 lws_set_extension_option(struct lws *wsi, const char *ext_name,
1210 const char *opt_name, const char *opt_val);
1212 #ifndef LWS_NO_EXTENSIONS
1213 /* lws_get_internal_extensions() - DEPRECATED
1215 * \Deprecated There is no longer a set internal extensions table. The table is provided
1216 * by user code along with application-specific settings. See the test
1217 * client and server for how to do.
1219 static LWS_INLINE LWS_WARN_DEPRECATED const struct lws_extension *
1220 lws_get_internal_extensions(void) { return NULL; }
1223 * lws_ext_parse_options() - deal with parsing negotiated extension options
1225 * \param ext: related extension struct
1226 * \param wsi: websocket connection
1227 * \param ext_user: per-connection extension private data
1228 * \param opts: list of supported options
1229 * \param o: option string to parse
1230 * \param len: length
1232 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
1233 lws_ext_parse_options(const struct lws_extension *ext, struct lws *wsi,
1234 void *ext_user, const struct lws_ext_options *opts,
1235 const char *o, int len);
1238 /** lws_extension_callback_pm_deflate() - extension for RFC7692
1240 * \param context: lws context
1241 * \param ext: related lws_extension struct
1242 * \param wsi: websocket connection
1243 * \param reason: incoming callback reason
1244 * \param user: per-connection extension private data
1245 * \param in: pointer parameter
1246 * \param len: length parameter
1248 * Built-in callback implementing RFC7692 permessage-deflate
1251 int lws_extension_callback_pm_deflate(
1252 struct lws_context *context, const struct lws_extension *ext,
1253 struct lws *wsi, enum lws_extension_callback_reasons reason,
1254 void *user, void *in, size_t len);
1257 * The internal exts are part of the public abi
1258 * If we add more extensions, publish the callback here ------v
1262 /*! \defgroup Protocols-and-Plugins Protocols and Plugins
1265 * ##Protocol and protocol plugin -related apis
1267 * Protocols bind ws protocol names to a custom callback specific to that
1268 * protocol implementaion.
1270 * A list of protocols can be passed in at context creation time, but it is
1271 * also legal to leave that NULL and add the protocols and their callback code
1274 * Plugins are much preferable compared to cut and pasting code into an
1275 * application each time, since they can be used standalone.
1278 /** struct lws_protocols - List of protocols and handlers client or server
1281 struct lws_protocols {
1283 /**< Protocol name that must match the one given in the client
1284 * Javascript new WebSocket(url, 'protocol') name. */
1285 lws_callback_function *callback;
1286 /**< The service callback used for this protocol. It allows the
1287 * service action for an entire protocol to be encapsulated in
1288 * the protocol-specific callback */
1289 size_t per_session_data_size;
1290 /**< Each new connection using this protocol gets
1291 * this much memory allocated on connection establishment and
1292 * freed on connection takedown. A pointer to this per-connection
1293 * allocation is passed into the callback in the 'user' parameter */
1294 size_t rx_buffer_size;
1295 /**< lws allocates this much space for rx data and informs callback
1296 * when something came. Due to rx flow control, the callback may not
1297 * be able to consume it all without having to return to the event
1298 * loop. That is supported in lws.
1300 * This also controls how much may be sent at once at the moment,
1301 * although this is likely to change.
1304 /**< ignored by lws, but useful to contain user information bound
1305 * to the selected protocol. For example if this protocol was
1306 * called "myprotocol-v2", you might set id to 2, and the user
1307 * code that acts differently according to the version can do so by
1308 * switch (wsi->protocol->id), user code might use some bits as
1309 * capability flags based on selected protocol version, etc. */
1310 void *user; /**< ignored by lws, but user code can pass a pointer
1311 here it can later access from the protocol callback */
1313 /* Add new things just above here ---^
1314 * This is part of the ABI, don't needlessly break compatibility */
1320 * lws_vhost_name_to_protocol() - get vhost's protocol object from its name
1322 * \param vh: vhost to search
1323 * \param name: protocol name
1325 * Returns NULL or a pointer to the vhost's protocol of the requested name
1327 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1328 lws_vhost_name_to_protocol(struct lws_vhost *vh, const char *name);
1331 * lws_get_protocol() - Returns a protocol pointer from a websocket
1333 * \param wsi: pointer to struct websocket you want to know the protocol of
1336 * Some apis can act on all live connections of a given protocol,
1337 * this is how you can get a pointer to the active protocol if needed.
1339 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1340 lws_get_protocol(struct lws *wsi);
1342 /** lws_protocol_get() - deprecated: use lws_get_protocol */
1343 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1344 lws_protocol_get(struct lws *wsi) LWS_WARN_DEPRECATED;
1347 * lws_protocol_vh_priv_zalloc() - Allocate and zero down a protocol's per-vhost
1349 * \param vhost: vhost the instance is related to
1350 * \param prot: protocol the instance is related to
1351 * \param size: bytes to allocate
1353 * Protocols often find it useful to allocate a per-vhost struct, this is a
1354 * helper to be called in the per-vhost init LWS_CALLBACK_PROTOCOL_INIT
1356 LWS_VISIBLE LWS_EXTERN void *
1357 lws_protocol_vh_priv_zalloc(struct lws_vhost *vhost, const struct lws_protocols *prot,
1361 * lws_protocol_vh_priv_get() - retreive a protocol's per-vhost storage
1363 * \param vhost: vhost the instance is related to
1364 * \param prot: protocol the instance is related to
1366 * Recover a pointer to the allocated per-vhost storage for the protocol created
1367 * by lws_protocol_vh_priv_zalloc() earlier
1369 LWS_VISIBLE LWS_EXTERN void *
1370 lws_protocol_vh_priv_get(struct lws_vhost *vhost, const struct lws_protocols *prot);
1373 * lws_finalize_startup() - drop initial process privileges
1375 * \param context: lws context
1377 * This is called after the end of the vhost protocol initializations, but
1378 * you may choose to call it earlier
1380 LWS_VISIBLE LWS_EXTERN int
1381 lws_finalize_startup(struct lws_context *context);
1383 #ifdef LWS_WITH_PLUGINS
1385 /* PLUGINS implies LIBUV */
1387 #define LWS_PLUGIN_API_MAGIC 180
1389 /** struct lws_plugin_capability - how a plugin introduces itself to lws */
1390 struct lws_plugin_capability {
1391 unsigned int api_magic; /**< caller fills this in, plugin fills rest */
1392 const struct lws_protocols *protocols; /**< array of supported protocols provided by plugin */
1393 int count_protocols; /**< how many protocols */
1394 const struct lws_extension *extensions; /**< array of extensions provided by plugin */
1395 int count_extensions; /**< how many extensions */
1398 typedef int (*lws_plugin_init_func)(struct lws_context *,
1399 struct lws_plugin_capability *);
1400 typedef int (*lws_plugin_destroy_func)(struct lws_context *);
1402 /** struct lws_plugin */
1404 struct lws_plugin *list; /**< linked list */
1405 #if (UV_VERSION_MAJOR > 0)
1406 uv_lib_t lib; /**< shared library pointer */
1408 void *l; /**< so we can compile on ancient libuv */
1410 char name[64]; /**< name of the plugin */
1411 struct lws_plugin_capability caps; /**< plugin capabilities */
1419 /*! \defgroup generic-sessions plugin: generic-sessions
1420 * \ingroup Protocols-and-Plugins
1422 * ##Plugin Generic-sessions related
1424 * generic-sessions plugin provides a reusable, generic session and login /
1425 * register / forgot password framework including email verification.
1429 #define LWSGS_EMAIL_CONTENT_SIZE 16384
1430 /**< Maximum size of email we might send */
1432 /* SHA-1 binary and hexified versions */
1433 /** typedef struct lwsgw_hash_bin */
1434 typedef struct { unsigned char bin[20]; /**< binary representation of hash */} lwsgw_hash_bin;
1435 /** typedef struct lwsgw_hash */
1436 typedef struct { char id[41]; /**< ascii hex representation of hash */ } lwsgw_hash;
1438 /** enum lwsgs_auth_bits */
1439 enum lwsgs_auth_bits {
1440 LWSGS_AUTH_LOGGED_IN = 1, /**< user is logged in as somebody */
1441 LWSGS_AUTH_ADMIN = 2, /**< logged in as the admin user */
1442 LWSGS_AUTH_VERIFIED = 4, /**< user has verified his email */
1443 LWSGS_AUTH_FORGOT_FLOW = 8, /**< he just completed "forgot password" flow */
1446 /** struct lws_session_info - information about user session status */
1447 struct lws_session_info {
1448 char username[32]; /**< username logged in as, or empty string */
1449 char email[100]; /**< email address associated with login, or empty string */
1450 char ip[72]; /**< ip address session was started from */
1451 unsigned int mask; /**< access rights mask associated with session
1452 * see enum lwsgs_auth_bits */
1453 char session[42]; /**< session id string, usable as opaque uid when not logged in */
1456 /** enum lws_gs_event */
1458 LWSGSE_CREATED, /**< a new user was created */
1459 LWSGSE_DELETED /**< an existing user was deleted */
1462 /** struct lws_gs_event_args */
1463 struct lws_gs_event_args {
1464 enum lws_gs_event event; /**< which event happened */
1465 const char *username; /**< which username the event happened to */
1466 const char *email; /**< the email address of that user */
1472 /*! \defgroup context-and-vhost
1475 * ##Context and Vhost releated functions
1477 * LWS requires that there is one context, in which you may define multiple
1478 * vhosts. Each vhost is a virtual host, with either its own listen port
1479 * or sharing an existing one. Each vhost has its own SSL context that can
1480 * be set up individually or left disabled.
1482 * If you don't care about multiple "site" support, you can ignore it and
1483 * lws will create a single default vhost at context creation time.
1488 * NOTE: These public enums are part of the abi. If you want to add one,
1489 * add it at where specified so existing users are unaffected.
1492 /** enum lws_context_options - context and vhost options */
1493 enum lws_context_options {
1494 LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT = (1 << 1) |
1496 /**< (VH) Don't allow the connection unless the client has a
1497 * client cert that we recognize; provides
1498 * LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT */
1499 LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME = (1 << 2),
1500 /**< (CTX) Don't try to get the server's hostname */
1501 LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT = (1 << 3) |
1503 /**< (VH) Allow non-SSL (plaintext) connections on the same
1504 * port as SSL is listening... undermines the security of SSL;
1505 * provides LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT */
1506 LWS_SERVER_OPTION_LIBEV = (1 << 4),
1507 /**< (CTX) Use libev event loop */
1508 LWS_SERVER_OPTION_DISABLE_IPV6 = (1 << 5),
1509 /**< (VH) Disable IPV6 support */
1510 LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS = (1 << 6),
1511 /**< (VH) Don't load OS CA certs, you will need to load your
1513 LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED = (1 << 7),
1514 /**< (VH) Accept connections with no valid Cert (eg, selfsigned) */
1515 LWS_SERVER_OPTION_VALIDATE_UTF8 = (1 << 8),
1516 /**< (VH) Check UT-8 correctness */
1517 LWS_SERVER_OPTION_SSL_ECDH = (1 << 9) |
1519 /**< (VH) initialize ECDH ciphers */
1520 LWS_SERVER_OPTION_LIBUV = (1 << 10),
1521 /**< (CTX) Use libuv event loop */
1522 LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS = (1 << 11) |
1524 /**< (VH) Use http redirect to force http to https
1525 * (deprecated: use mount redirection) */
1526 LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT = (1 << 12),
1527 /**< (CTX) Initialize the SSL library at all */
1528 LWS_SERVER_OPTION_EXPLICIT_VHOSTS = (1 << 13),
1529 /**< (CTX) Only create the context when calling context
1530 * create api, implies user code will create its own vhosts */
1531 LWS_SERVER_OPTION_UNIX_SOCK = (1 << 14),
1532 /**< (VH) Use Unix socket */
1533 LWS_SERVER_OPTION_STS = (1 << 15),
1534 /**< (VH) Send Strict Transport Security header, making
1535 * clients subsequently go to https even if user asked for http */
1536 LWS_SERVER_OPTION_IPV6_V6ONLY_MODIFY = (1 << 16),
1537 /**< (VH) Enable LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE to take effect */
1538 LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE = (1 << 17),
1539 /**< (VH) if set, only ipv6 allowed on the vhost */
1540 LWS_SERVER_OPTION_UV_NO_SIGSEGV_SIGFPE_SPIN = (1 << 18),
1541 /**< (CTX) Libuv only: Do not spin on SIGSEGV / SIGFPE. A segfault
1542 * normally makes the lib spin so you can attach a debugger to it
1543 * even if it happened without a debugger in place. You can disable
1544 * that by giving this option.
1547 /****** add new things just above ---^ ******/
1550 #define lws_check_opt(c, f) (((c) & (f)) == (f))
1552 /** struct lws_context_creation_info - parameters to create context and /or vhost with
1554 * This is also used to create vhosts.... if LWS_SERVER_OPTION_EXPLICIT_VHOSTS
1555 * is not given, then for backwards compatibility one vhost is created at
1556 * context-creation time using the info from this struct.
1558 * If LWS_SERVER_OPTION_EXPLICIT_VHOSTS is given, then no vhosts are created
1559 * at the same time as the context, they are expected to be created afterwards.
1561 struct lws_context_creation_info {
1563 /**< VHOST: Port to listen on... you can use CONTEXT_PORT_NO_LISTEN to
1564 * suppress listening on any port, that's what you want if you are
1565 * not running a websocket server at all but just using it as a
1568 /**< VHOST: NULL to bind the listen socket to all interfaces, or the
1569 * interface name, eg, "eth2"
1570 * If options specifies LWS_SERVER_OPTION_UNIX_SOCK, this member is
1571 * the pathname of a UNIX domain socket. you can use the UNIX domain
1572 * sockets in abstract namespace, by prepending an at symbol to the
1574 const struct lws_protocols *protocols;
1575 /**< VHOST: Array of structures listing supported protocols and a protocol-
1576 * specific callback for each one. The list is ended with an
1577 * entry that has a NULL callback pointer. */
1578 const struct lws_extension *extensions;
1579 /**< VHOST: NULL or array of lws_extension structs listing the
1580 * extensions this context supports. */
1581 const struct lws_token_limits *token_limits;
1582 /**< CONTEXT: NULL or struct lws_token_limits pointer which is initialized
1583 * with a token length limit for each possible WSI_TOKEN_ */
1584 const char *ssl_private_key_password;
1585 /**< VHOST: NULL or the passphrase needed for the private key */
1586 const char *ssl_cert_filepath;
1587 /**< VHOST: If libwebsockets was compiled to use ssl, and you want
1588 * to listen using SSL, set to the filepath to fetch the
1589 * server cert from, otherwise NULL for unencrypted */
1590 const char *ssl_private_key_filepath;
1591 /**< VHOST: filepath to private key if wanting SSL mode;
1592 * if this is set to NULL but sll_cert_filepath is set, the
1593 * OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY callback is called
1594 * to allow setting of the private key directly via openSSL
1596 const char *ssl_ca_filepath;
1597 /**< VHOST: CA certificate filepath or NULL */
1598 const char *ssl_cipher_list;
1599 /**< VHOST: List of valid ciphers to use (eg,
1600 * "RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL"
1601 * or you can leave it as NULL to get "DEFAULT" */
1602 const char *http_proxy_address;
1603 /**< VHOST: If non-NULL, attempts to proxy via the given address.
1604 * If proxy auth is required, use format "username:password\@server:port" */
1605 unsigned int http_proxy_port;
1606 /**< VHOST: If http_proxy_address was non-NULL, uses this port */
1608 /**< CONTEXT: group id to change to after setting listen socket, or -1. */
1610 /**< CONTEXT: user id to change to after setting listen socket, or -1. */
1611 unsigned int options;
1612 /**< VHOST + CONTEXT: 0, or LWS_SERVER_OPTION_... bitfields */
1614 /**< CONTEXT: optional user pointer that can be recovered via the context
1615 * pointer using lws_context_user */
1617 /**< CONTEXT: 0 for no TCP keepalive, otherwise apply this keepalive
1618 * timeout to all libwebsocket sockets, client or server */
1620 /**< CONTEXT: if ka_time was nonzero, after the timeout expires how many
1621 * times to try to get a response from the peer before giving up
1622 * and killing the connection */
1624 /**< CONTEXT: if ka_time was nonzero, how long to wait before each ka_probes
1626 #ifdef LWS_OPENSSL_SUPPORT
1627 SSL_CTX *provided_client_ssl_ctx;
1628 /**< CONTEXT: If non-null, swap out libwebsockets ssl
1629 * implementation for the one provided by provided_ssl_ctx.
1630 * Libwebsockets no longer is responsible for freeing the context
1631 * if this option is selected. */
1632 #else /* maintain structure layout either way */
1633 void *provided_client_ssl_ctx; /**< dummy if ssl disabled */
1636 short max_http_header_data;
1637 /**< CONTEXT: The max amount of header payload that can be handled
1638 * in an http request (unrecognized header payload is dropped) */
1639 short max_http_header_pool;
1640 /**< CONTEXT: The max number of connections with http headers that
1641 * can be processed simultaneously (the corresponding memory is
1642 * allocated for the lifetime of the context). If the pool is
1643 * busy new incoming connections must wait for accept until one
1646 unsigned int count_threads;
1647 /**< CONTEXT: how many contexts to create in an array, 0 = 1 */
1648 unsigned int fd_limit_per_thread;
1649 /**< CONTEXT: nonzero means restrict each service thread to this
1650 * many fds, 0 means the default which is divide the process fd
1651 * limit by the number of threads. */
1652 unsigned int timeout_secs;
1653 /**< VHOST: various processes involving network roundtrips in the
1654 * library are protected from hanging forever by timeouts. If
1655 * nonzero, this member lets you set the timeout used in seconds.
1656 * Otherwise a default timeout is used. */
1657 const char *ecdh_curve;
1658 /**< VHOST: if NULL, defaults to initializing server with "prime256v1" */
1659 const char *vhost_name;
1660 /**< VHOST: name of vhost, must match external DNS name used to
1661 * access the site, like "warmcat.com" as it's used to match
1662 * Host: header and / or SNI name for SSL. */
1663 const char * const *plugin_dirs;
1664 /**< CONTEXT: NULL, or NULL-terminated array of directories to
1665 * scan for lws protocol plugins at context creation time */
1666 const struct lws_protocol_vhost_options *pvo;
1667 /**< VHOST: pointer to optional linked list of per-vhost
1668 * options made accessible to protocols */
1669 int keepalive_timeout;
1670 /**< VHOST: (default = 0 = 60s) seconds to allow remote
1671 * client to hold on to an idle HTTP/1.1 connection */
1672 const char *log_filepath;
1673 /**< VHOST: filepath to append logs to... this is opened before
1674 * any dropping of initial privileges */
1675 const struct lws_http_mount *mounts;
1676 /**< VHOST: optional linked list of mounts for this vhost */
1677 const char *server_string;
1678 /**< CONTEXT: string used in HTTP headers to identify server
1679 * software, if NULL, "libwebsockets". */
1680 unsigned int pt_serv_buf_size;
1681 /**< CONTEXT: 0 = default of 4096. This buffer is used by
1682 * various service related features including file serving, it
1683 * defines the max chunk of file that can be sent at once.
1684 * At the risk of lws having to buffer failed large sends, it
1685 * can be increased to, eg, 128KiB to improve throughput. */
1686 unsigned int max_http_header_data2;
1687 /**< CONTEXT: if max_http_header_data is 0 and this
1688 * is nonzero, this will be used in place of the default. It's
1689 * like this for compatibility with the original short version,
1690 * this is unsigned int length. */
1691 long ssl_options_set;
1692 /**< VHOST: Any bits set here will be set as SSL options */
1693 long ssl_options_clear;
1694 /**< VHOST: Any bits set here will be cleared as SSL options */
1695 unsigned short ws_ping_pong_interval;
1696 /**< CONTEXT: 0 for none, else interval in seconds between sending
1697 * PINGs on idle websocket connections. When the PING is sent,
1698 * the PONG must come within the normal timeout_secs timeout period
1699 * or the connection will be dropped.
1700 * Any RX or TX traffic on the connection restarts the interval timer,
1701 * so a connection which always sends or receives something at intervals
1702 * less than the interval given here will never send PINGs / expect
1703 * PONGs. Conversely as soon as the ws connection is established, an
1704 * idle connection will do the PING / PONG roundtrip as soon as
1705 * ws_ping_pong_interval seconds has passed without traffic
1707 const struct lws_protocol_vhost_options *headers;
1708 /**< VHOST: pointer to optional linked list of per-vhost
1709 * canned headers that are added to server responses */
1711 const struct lws_protocol_vhost_options *reject_service_keywords;
1712 /**< CONTEXT: Optional list of keywords and rejection codes + text.
1714 * The keywords are checked for existing in the user agent string.
1716 * Eg, "badrobot" "404 Not Found"
1718 void *external_baggage_free_on_destroy;
1719 /**< CONTEXT: NULL, or pointer to something externally malloc'd, that
1720 * should be freed when the context is destroyed. This allows you to
1721 * automatically sync the freeing action to the context destruction
1722 * action, so there is no need for an external free() if the context
1723 * succeeded to create.
1726 /* Add new things just above here ---^
1727 * This is part of the ABI, don't needlessly break compatibility
1729 * The below is to ensure later library versions with new
1730 * members added above will see 0 (default) even if the app
1731 * was not built against the newer headers.
1734 void *_unused[8]; /**< dummy */
1738 * lws_create_context() - Create the websocket handler
1739 * \param info: pointer to struct with parameters
1741 * This function creates the listening socket (if serving) and takes care
1742 * of all initialization in one step.
1744 * If option LWS_SERVER_OPTION_EXPLICIT_VHOSTS is given, no vhost is
1745 * created; you're expected to create your own vhosts afterwards using
1746 * lws_create_vhost(). Otherwise a vhost named "default" is also created
1747 * using the information in the vhost-related members, for compatibility.
1749 * After initialization, it returns a struct lws_context * that
1750 * represents this server. After calling, user code needs to take care
1751 * of calling lws_service() with the context pointer to get the
1752 * server's sockets serviced. This must be done in the same process
1753 * context as the initialization call.
1755 * The protocol callback functions are called for a handful of events
1756 * including http requests coming in, websocket connections becoming
1757 * established, and data arriving; it's also called periodically to allow
1758 * async transmission.
1760 * HTTP requests are sent always to the FIRST protocol in protocol, since
1761 * at that time websocket protocol has not been negotiated. Other
1762 * protocols after the first one never see any HTTP callback activity.
1764 * The server created is a simple http server by default; part of the
1765 * websocket standard is upgrading this http connection to a websocket one.
1767 * This allows the same server to provide files like scripts and favicon /
1768 * images or whatever over http and dynamic data over websockets all in
1769 * one place; they're all handled in the user callback.
1771 LWS_VISIBLE LWS_EXTERN struct lws_context *
1772 lws_create_context(struct lws_context_creation_info *info);
1775 * lws_context_destroy() - Destroy the websocket context
1776 * \param context: Websocket context
1778 * This function closes any active connections and then frees the
1779 * context. After calling this, any further use of the context is
1782 LWS_VISIBLE LWS_EXTERN void
1783 lws_context_destroy(struct lws_context *context);
1785 LWS_VISIBLE LWS_EXTERN void
1786 lws_context_destroy2(struct lws_context *context);
1788 typedef int (*lws_reload_func)(void);
1791 * lws_context_deprecate() - Deprecate the websocket context
1792 * \param context: Websocket context
1794 * This function is used on an existing context before superceding it
1795 * with a new context.
1797 * It closes any listen sockets in the context, so new connections are
1800 * And it marks the context to be deleted when the number of active
1801 * connections into it falls to zero.
1803 * Otherwise if you attach the deprecated context to the replacement
1804 * context when it has been created using lws_context_attach_deprecated()
1805 * both any deprecated and the new context will service their connections.
1807 * This is aimed at allowing seamless configuration reloads.
1809 * The callback cb will be called after the listen sockets are actually
1810 * closed and may be reopened. In the callback the new context should be
1811 * configured and created. (With libuv, socket close happens async after
1812 * more loop events).
1814 LWS_VISIBLE LWS_EXTERN void
1815 lws_context_deprecate(struct lws_context *context, lws_reload_func cb);
1817 LWS_VISIBLE LWS_EXTERN int
1818 lws_context_is_deprecated(struct lws_context *context);
1821 * lws_set_proxy() - Setups proxy to lws_context.
1822 * \param vhost: pointer to struct lws_vhost you want set proxy for
1823 * \param proxy: pointer to c string containing proxy in format address:port
1825 * Returns 0 if proxy string was parsed and proxy was setup.
1826 * Returns -1 if proxy is NULL or has incorrect format.
1828 * This is only required if your OS does not provide the http_proxy
1829 * environment variable (eg, OSX)
1831 * IMPORTANT! You should call this function right after creation of the
1832 * lws_context and before call to connect. If you call this
1833 * function after connect behavior is undefined.
1834 * This function will override proxy settings made on lws_context
1835 * creation with genenv() call.
1837 LWS_VISIBLE LWS_EXTERN int
1838 lws_set_proxy(struct lws_vhost *vhost, const char *proxy);
1844 * lws_create_vhost() - Create a vhost (virtual server context)
1845 * \param context: pointer to result of lws_create_context()
1846 * \param info: pointer to struct with parameters
1848 * This function creates a virtual server (vhost) using the vhost-related
1849 * members of the info struct. You can create many vhosts inside one context
1850 * if you created the context with the option LWS_SERVER_OPTION_EXPLICIT_VHOSTS
1852 LWS_EXTERN LWS_VISIBLE struct lws_vhost *
1853 lws_create_vhost(struct lws_context *context,
1854 struct lws_context_creation_info *info);
1857 * lwsws_get_config_globals() - Parse a JSON server config file
1858 * \param info: pointer to struct with parameters
1859 * \param d: filepath of the config file
1860 * \param config_strings: storage for the config strings extracted from JSON,
1861 * the pointer is incremented as strings are stored
1862 * \param len: pointer to the remaining length left in config_strings
1863 * the value is decremented as strings are stored
1865 * This function prepares a n lws_context_creation_info struct with global
1866 * settings from a file d.
1868 * Requires CMake option LWS_WITH_LEJP_CONF to have been enabled
1870 LWS_VISIBLE LWS_EXTERN int
1871 lwsws_get_config_globals(struct lws_context_creation_info *info, const char *d,
1872 char **config_strings, int *len);
1875 * lwsws_get_config_vhosts() - Create vhosts from a JSON server config file
1876 * \param context: pointer to result of lws_create_context()
1877 * \param info: pointer to struct with parameters
1878 * \param d: filepath of the config file
1879 * \param config_strings: storage for the config strings extracted from JSON,
1880 * the pointer is incremented as strings are stored
1881 * \param len: pointer to the remaining length left in config_strings
1882 * the value is decremented as strings are stored
1884 * This function creates vhosts into a context according to the settings in
1885 *JSON files found in directory d.
1887 * Requires CMake option LWS_WITH_LEJP_CONF to have been enabled
1889 LWS_VISIBLE LWS_EXTERN int
1890 lwsws_get_config_vhosts(struct lws_context *context,
1891 struct lws_context_creation_info *info, const char *d,
1892 char **config_strings, int *len);
1894 /** lws_vhost_get() - \deprecated deprecated: use lws_get_vhost() */
1895 LWS_VISIBLE LWS_EXTERN struct lws_vhost *
1896 lws_vhost_get(struct lws *wsi) LWS_WARN_DEPRECATED;
1899 * lws_get_vhost() - return the vhost a wsi belongs to
1901 * \param wsi: which connection
1903 LWS_VISIBLE LWS_EXTERN struct lws_vhost *
1904 lws_get_vhost(struct lws *wsi);
1907 * lws_json_dump_vhost() - describe vhost state and stats in JSON
1909 * \param vh: the vhost
1910 * \param buf: buffer to fill with JSON
1911 * \param len: max length of buf
1913 LWS_VISIBLE LWS_EXTERN int
1914 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len);
1917 * lws_json_dump_context() - describe context state and stats in JSON
1919 * \param context: the context
1920 * \param buf: buffer to fill with JSON
1921 * \param len: max length of buf
1923 LWS_VISIBLE LWS_EXTERN int
1924 lws_json_dump_context(const struct lws_context *context, char *buf, int len,
1928 * lws_context_user() - get the user data associated with the context
1929 * \param context: Websocket context
1931 * This returns the optional user allocation that can be attached to
1932 * the context the sockets live in at context_create time. It's a way
1933 * to let all sockets serviced in the same context share data without
1934 * using globals statics in the user code.
1936 LWS_VISIBLE LWS_EXTERN void *
1937 lws_context_user(struct lws_context *context);
1939 /*! \defgroup vhost-mounts Vhost mounts and options
1940 * \ingroup context-and-vhost-creation
1942 * ##Vhost mounts and options
1945 /** struct lws_protocol_vhost_options - linked list of per-vhost protocol
1946 * name=value options
1948 * This provides a general way to attach a linked-list of name=value pairs,
1949 * which can also have an optional child link-list using the options member.
1951 struct lws_protocol_vhost_options {
1952 const struct lws_protocol_vhost_options *next; /**< linked list */
1953 const struct lws_protocol_vhost_options *options; /**< child linked-list of more options for this node */
1954 const char *name; /**< name of name=value pair */
1955 const char *value; /**< value of name=value pair */
1958 /** enum lws_mount_protocols
1959 * This specifies the mount protocol for a mountpoint, whether it is to be
1960 * served from a filesystem, or it is a cgi etc.
1962 enum lws_mount_protocols {
1963 LWSMPRO_HTTP = 0, /**< not supported yet */
1964 LWSMPRO_HTTPS = 1, /**< not supported yet */
1965 LWSMPRO_FILE = 2, /**< serve from filesystem directory */
1966 LWSMPRO_CGI = 3, /**< pass to CGI to handle */
1967 LWSMPRO_REDIR_HTTP = 4, /**< redirect to http:// url */
1968 LWSMPRO_REDIR_HTTPS = 5, /**< redirect to https:// url */
1969 LWSMPRO_CALLBACK = 6, /**< hand by named protocol's callback */
1972 /** struct lws_http_mount
1974 * arguments for mounting something in a vhost's url namespace
1976 struct lws_http_mount {
1977 const struct lws_http_mount *mount_next;
1978 /**< pointer to next struct lws_http_mount */
1979 const char *mountpoint;
1980 /**< mountpoint in http pathspace, eg, "/" */
1982 /**< path to be mounted, eg, "/var/www/warmcat.com" */
1984 /**< default target, eg, "index.html" */
1985 const char *protocol;
1986 /**<"protocol-name" to handle mount */
1988 const struct lws_protocol_vhost_options *cgienv;
1989 /**< optional linked-list of cgi options. These are created
1990 * as environment variables for the cgi process
1992 const struct lws_protocol_vhost_options *extra_mimetypes;
1993 /**< optional linked-list of mimetype mappings */
1994 const struct lws_protocol_vhost_options *interpret;
1995 /**< optional linked-list of files to be interpreted */
1998 /**< seconds cgi is allowed to live, if cgi://mount type */
2000 /**< max-age for reuse of client cache of files, seconds */
2001 unsigned int auth_mask;
2002 /**< bits set here must be set for authorized client session */
2004 unsigned int cache_reusable:1; /**< set if client cache may reuse this */
2005 unsigned int cache_revalidate:1; /**< set if client cache should revalidate on use */
2006 unsigned int cache_intermediaries:1; /**< set if intermediaries are allowed to cache */
2008 unsigned char origin_protocol; /**< one of enum lws_mount_protocols */
2009 unsigned char mountpoint_len; /**< length of mountpoint string */
2011 const char *basic_auth_login_file;
2012 /**<NULL, or filepath to use to check basic auth logins against */
2014 /* Add new things just above here ---^
2015 * This is part of the ABI, don't needlessly break compatibility
2017 * The below is to ensure later library versions with new
2018 * members added above will see 0 (default) even if the app
2019 * was not built against the newer headers.
2022 void *_unused[2]; /**< dummy */
2027 /*! \defgroup client
2030 * ##Client releated functions
2034 /** enum lws_client_connect_ssl_connection_flags - flags that may be used
2035 * with struct lws_client_connect_info ssl_connection member to control if
2036 * and how SSL checks apply to the client connection being created
2039 enum lws_client_connect_ssl_connection_flags {
2040 LCCSCF_USE_SSL = (1 << 0),
2041 LCCSCF_ALLOW_SELFSIGNED = (1 << 1),
2042 LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK = (1 << 2),
2043 LCCSCF_ALLOW_EXPIRED = (1 << 3)
2046 /** struct lws_client_connect_info - parameters to connect with when using
2047 * lws_client_connect_via_info() */
2049 struct lws_client_connect_info {
2050 struct lws_context *context;
2051 /**< lws context to create connection in */
2052 const char *address;
2053 /**< remote address to connect to */
2055 /**< remote port to connect to */
2057 /**< nonzero for ssl */
2061 /**< content of host header */
2063 /**< content of origin header */
2064 const char *protocol;
2065 /**< list of ws protocols we could accept */
2066 int ietf_version_or_minus_one;
2067 /**< deprecated: currently leave at 0 or -1 */
2069 /**< if non-NULL, use this as wsi user_data instead of malloc it */
2070 const struct lws_extension *client_exts;
2071 /**< array of extensions that may be used on connection */
2073 /**< if non-NULL, do this http method instead of ws[s] upgrade.
2074 * use "GET" to be a simple http client connection */
2075 struct lws *parent_wsi;
2076 /**< if another wsi is responsible for this connection, give it here.
2077 * this is used to make sure if the parent closes so do any
2078 * child connections first. */
2079 const char *uri_replace_from;
2080 /**< if non-NULL, when this string is found in URIs in
2081 * text/html content-encoding, it's replaced with uri_replace_to */
2082 const char *uri_replace_to;
2083 /**< see uri_replace_from */
2084 struct lws_vhost *vhost;
2085 /**< vhost to bind to (used to determine related SSL_CTX) */
2087 /**< if not NULL, store the new wsi here early in the connection
2088 * process. Although we return the new wsi, the call to create the
2089 * client connection does progress the connection somewhat and may
2090 * meet an error that will result in the connection being scrubbed and
2091 * NULL returned. While the wsi exists though, he may process a
2092 * callback like CLIENT_CONNECTION_ERROR with his wsi: this gives the
2093 * user callback a way to identify which wsi it is that faced the error
2094 * even before the new wsi is returned and even if ultimately no wsi
2098 /* Add new things just above here ---^
2099 * This is part of the ABI, don't needlessly break compatibility
2101 * The below is to ensure later library versions with new
2102 * members added above will see 0 (default) even if the app
2103 * was not built against the newer headers.
2106 void *_unused[4]; /**< dummy */
2110 * lws_client_connect_via_info() - Connect to another websocket server
2111 * \param ccinfo: pointer to lws_client_connect_info struct
2113 * This function creates a connection to a remote server using the
2114 * information provided in ccinfo.
2116 LWS_VISIBLE LWS_EXTERN struct lws *
2117 lws_client_connect_via_info(struct lws_client_connect_info * ccinfo);
2120 * lws_client_connect() - Connect to another websocket server
2121 * \deprecated DEPRECATED use lws_client_connect_via_info
2122 * \param clients: Websocket context
2123 * \param address: Remote server address, eg, "myserver.com"
2124 * \param port: Port to connect to on the remote server, eg, 80
2125 * \param ssl_connection: 0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
2127 * \param path: Websocket path on server
2128 * \param host: Hostname on server
2129 * \param origin: Socket origin name
2130 * \param protocol: Comma-separated list of protocols being asked for from
2131 * the server, or just one. The server will pick the one it
2132 * likes best. If you don't want to specify a protocol, which is
2133 * legal, use NULL here.
2134 * \param ietf_version_or_minus_one: -1 to ask to connect using the default, latest
2135 * protocol supported, or the specific protocol ordinal
2137 * This function creates a connection to a remote server
2139 /* deprecated, use lws_client_connect_via_info() */
2140 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
2141 lws_client_connect(struct lws_context *clients, const char *address,
2142 int port, int ssl_connection, const char *path,
2143 const char *host, const char *origin, const char *protocol,
2144 int ietf_version_or_minus_one) LWS_WARN_DEPRECATED;
2145 /* deprecated, use lws_client_connect_via_info() */
2147 * lws_client_connect_extended() - Connect to another websocket server
2148 * \deprecated DEPRECATED use lws_client_connect_via_info
2149 * \param clients: Websocket context
2150 * \param address: Remote server address, eg, "myserver.com"
2151 * \param port: Port to connect to on the remote server, eg, 80
2152 * \param ssl_connection: 0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
2154 * \param path: Websocket path on server
2155 * \param host: Hostname on server
2156 * \param origin: Socket origin name
2157 * \param protocol: Comma-separated list of protocols being asked for from
2158 * the server, or just one. The server will pick the one it
2160 * \param ietf_version_or_minus_one: -1 to ask to connect using the default, latest
2161 * protocol supported, or the specific protocol ordinal
2162 * \param userdata: Pre-allocated user data
2164 * This function creates a connection to a remote server
2166 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
2167 lws_client_connect_extended(struct lws_context *clients, const char *address,
2168 int port, int ssl_connection, const char *path,
2169 const char *host, const char *origin,
2170 const char *protocol, int ietf_version_or_minus_one,
2171 void *userdata) LWS_WARN_DEPRECATED;
2174 * lws_init_vhost_client_ssl() - also enable client SSL on an existing vhost
2176 * \param info: client ssl related info
2177 * \param vhost: which vhost to initialize client ssl operations on
2179 * You only need to call this if you plan on using SSL client connections on
2180 * the vhost. For non-SSL client connections, it's not necessary to call this.
2182 * The following members of info are used during the call
2184 * - options must have LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT set,
2185 * otherwise the call does nothing
2186 * - provided_client_ssl_ctx must be NULL to get a generated client
2187 * ssl context, otherwise you can pass a prepared one in by setting it
2188 * - ssl_cipher_list may be NULL or set to the client valid cipher list
2189 * - ssl_ca_filepath may be NULL or client cert filepath
2190 * - ssl_cert_filepath may be NULL or client cert filepath
2191 * - ssl_private_key_filepath may be NULL or client cert private key
2193 * You must create your vhost explicitly if you want to use this, so you have
2194 * a pointer to the vhost. Create the context first with the option flag
2195 * LWS_SERVER_OPTION_EXPLICIT_VHOSTS and then call lws_create_vhost() with
2196 * the same info struct.
2198 LWS_VISIBLE LWS_EXTERN int
2199 lws_init_vhost_client_ssl(const struct lws_context_creation_info *info,
2200 struct lws_vhost *vhost);
2202 LWS_VISIBLE LWS_EXTERN int
2203 lws_http_client_read(struct lws *wsi, char **buf, int *len);
2206 * lws_http_client_http_response() - get last HTTP response code
2208 * \param wsi: client connection
2210 * Returns the last server response code, eg, 200 for client http connections.
2212 LWS_VISIBLE LWS_EXTERN unsigned int
2213 lws_http_client_http_response(struct lws *wsi);
2215 LWS_VISIBLE LWS_EXTERN void
2216 lws_client_http_body_pending(struct lws *wsi, int something_left_to_send);
2219 * lws_client_http_body_pending() - control if client connection neeeds to send body
2221 * \param wsi: client connection
2222 * \param something_left_to_send: nonzero if need to send more body, 0 (default)
2223 * if nothing more to send
2225 * If you will send payload data with your HTTP client connection, eg, for POST,
2226 * when you set the related http headers in
2227 * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER callback you should also call
2228 * this API with something_left_to_send nonzero, and call
2229 * lws_callback_on_writable(wsi);
2231 * After sending the headers, lws will call your callback with
2232 * LWS_CALLBACK_CLIENT_HTTP_WRITEABLE reason when writable. You can send the
2233 * next part of the http body payload, calling lws_callback_on_writable(wsi);
2234 * if there is more to come, or lws_client_http_body_pending(wsi, 0); to
2235 * let lws know the last part is sent and the connection can move on.
2240 /** \defgroup service Built-in service loop entry
2242 * ##Built-in service loop entry
2244 * If you're not using libev / libuv, these apis are needed to enter the poll()
2245 * wait in lws and service any connections with pending events.
2250 * lws_service() - Service any pending websocket activity
2251 * \param context: Websocket context
2252 * \param timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
2253 * service otherwise block and service immediately, returning
2254 * after the timeout if nothing needed service.
2256 * This function deals with any pending websocket traffic, for three
2257 * kinds of event. It handles these events on both server and client
2258 * types of connection the same.
2260 * 1) Accept new connections to our context's server
2262 * 2) Call the receive callback for incoming frame data received by
2263 * server or client connections.
2265 * You need to call this service function periodically to all the above
2266 * functions to happen; if your application is single-threaded you can
2267 * just call it in your main event loop.
2269 * Alternatively you can fork a new process that asynchronously handles
2270 * calling this service in a loop. In that case you are happy if this
2271 * call blocks your thread until it needs to take care of something and
2272 * would call it with a large nonzero timeout. Your loop then takes no
2273 * CPU while there is nothing happening.
2275 * If you are calling it in a single-threaded app, you don't want it to
2276 * wait around blocking other things in your loop from happening, so you
2277 * would call it with a timeout_ms of 0, so it returns immediately if
2278 * nothing is pending, or as soon as it services whatever was pending.
2280 LWS_VISIBLE LWS_EXTERN int
2281 lws_service(struct lws_context *context, int timeout_ms);
2284 * lws_service() - Service any pending websocket activity
2286 * \param context: Websocket context
2287 * \param timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
2288 * service otherwise block and service immediately, returning
2289 * after the timeout if nothing needed service.
2291 * Same as lws_service(), but for a specific thread service index. Only needed
2292 * if you are spawning multiple service threads.
2294 LWS_VISIBLE LWS_EXTERN int
2295 lws_service_tsi(struct lws_context *context, int timeout_ms, int tsi);
2298 * lws_cancel_service_pt() - Cancel servicing of pending socket activity
2300 * \param wsi: Cancel service on the thread this wsi is serviced by
2302 * This function lets a call to lws_service() waiting for a timeout
2303 * immediately return.
2305 * It works by creating a phony event and then swallowing it silently.
2307 * The reason it may be needed is when waiting in poll(), changes to
2308 * the event masks are ignored by the OS until poll() is reentered. This
2309 * lets you halt the poll() wait and make the reentry happen immediately
2310 * instead of having the wait out the rest of the poll timeout.
2312 LWS_VISIBLE LWS_EXTERN void
2313 lws_cancel_service_pt(struct lws *wsi);
2316 * lws_cancel_service() - Cancel wait for new pending socket activity
2317 * \param context: Websocket context
2319 * This function let a call to lws_service() waiting for a timeout
2320 * immediately return.
2322 * What it basically does is provide a fake event that will be swallowed,
2323 * so the wait in poll() is ended. That's useful because poll() doesn't
2324 * attend to changes in POLLIN/OUT/ERR until it re-enters the wait.
2326 LWS_VISIBLE LWS_EXTERN void
2327 lws_cancel_service(struct lws_context *context);
2330 * lws_service_fd() - Service polled socket with something waiting
2331 * \param context: Websocket context
2332 * \param pollfd: The pollfd entry describing the socket fd and which events
2333 * happened, or NULL to tell lws to do only timeout servicing.
2335 * This function takes a pollfd that has POLLIN or POLLOUT activity and
2336 * services it according to the state of the associated
2339 * The one call deals with all "service" that might happen on a socket
2340 * including listen accepts, http files as well as websocket protocol.
2342 * If a pollfd says it has something, you can just pass it to
2343 * lws_service_fd() whether it is a socket handled by lws or not.
2344 * If it sees it is a lws socket, the traffic will be handled and
2345 * pollfd->revents will be zeroed now.
2347 * If the socket is foreign to lws, it leaves revents alone. So you can
2348 * see if you should service yourself by checking the pollfd revents
2349 * after letting lws try to service it.
2351 * You should also call this with pollfd = NULL to just allow the
2352 * once-per-second global timeout checks; if less than a second since the last
2353 * check it returns immediately then.
2355 LWS_VISIBLE LWS_EXTERN int
2356 lws_service_fd(struct lws_context *context, struct lws_pollfd *pollfd);
2359 * lws_service_fd_tsi() - Service polled socket in specific service thread
2360 * \param context: Websocket context
2361 * \param pollfd: The pollfd entry describing the socket fd and which events
2363 * \param tsi: thread service index
2365 * Same as lws_service_fd() but used with multiple service threads
2367 LWS_VISIBLE LWS_EXTERN int
2368 lws_service_fd_tsi(struct lws_context *context, struct lws_pollfd *pollfd,
2372 * lws_service_adjust_timeout() - Check for any connection needing forced service
2373 * \param context: Websocket context
2374 * \param timeout_ms: The original poll timeout value. You can just set this
2375 * to 1 if you don't really have a poll timeout.
2376 * \param tsi: thread service index
2378 * Under some conditions connections may need service even though there is no
2379 * pending network action on them, this is "forced service". For default
2380 * poll() and libuv / libev, the library takes care of calling this and
2381 * dealing with it for you. But for external poll() integration, you need
2382 * access to the apis.
2384 * If anybody needs "forced service", returned timeout is zero. In that case,
2385 * you can call lws_service_tsi() with a timeout of -1 to only service
2386 * guys who need forced service.
2388 LWS_VISIBLE LWS_EXTERN int
2389 lws_service_adjust_timeout(struct lws_context *context, int timeout_ms, int tsi);
2391 /* Backwards compatibility */
2392 #define lws_plat_service_tsi lws_service_tsi
2396 /*! \defgroup http HTTP
2398 Modules related to handling HTTP
2402 /*! \defgroup httpft HTTP File transfer
2405 APIs for sending local files in response to HTTP requests
2410 * lws_get_mimetype() - Determine mimetype to use from filename
2412 * \param file: filename
2413 * \param m: NULL, or mount context
2415 * This uses a canned list of known filetypes first, if no match and m is
2416 * non-NULL, then tries a list of per-mount file suffix to mimtype mappings.
2418 * Returns either NULL or a pointer to the mimetype matching the file.
2420 LWS_VISIBLE LWS_EXTERN const char *
2421 lws_get_mimetype(const char *file, const struct lws_http_mount *m);
2424 * lws_serve_http_file() - Send a file back to the client using http
2425 * \param wsi: Websocket instance (available from user callback)
2426 * \param file: The file to issue over http
2427 * \param content_type: The http content type, eg, text/html
2428 * \param other_headers: NULL or pointer to header string
2429 * \param other_headers_len: length of the other headers if non-NULL
2431 * This function is intended to be called from the callback in response
2432 * to http requests from the client. It allows the callback to issue
2433 * local files down the http link in a single step.
2435 * Returning <0 indicates error and the wsi should be closed. Returning
2436 * >0 indicates the file was completely sent and
2437 * lws_http_transaction_completed() called on the wsi (and close if != 0)
2438 * ==0 indicates the file transfer is started and needs more service later,
2439 * the wsi should be left alone.
2441 LWS_VISIBLE LWS_EXTERN int
2442 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
2443 const char *other_headers, int other_headers_len);
2444 LWS_VISIBLE LWS_EXTERN int
2445 lws_serve_http_file_fragment(struct lws *wsi);
2448 /*! \defgroup html-chunked-substitution HTML Chunked Substitution
2451 * ##HTML chunked Substitution
2453 * APIs for receiving chunks of text, replacing a set of variable names via
2454 * a callback, and then prepending and appending HTML chunked encoding
2460 HTTP_STATUS_OK = 200,
2461 HTTP_STATUS_NO_CONTENT = 204,
2462 HTTP_STATUS_PARTIAL_CONTENT = 206,
2464 HTTP_STATUS_MOVED_PERMANENTLY = 301,
2465 HTTP_STATUS_FOUND = 302,
2466 HTTP_STATUS_SEE_OTHER = 303,
2468 HTTP_STATUS_BAD_REQUEST = 400,
2469 HTTP_STATUS_UNAUTHORIZED,
2470 HTTP_STATUS_PAYMENT_REQUIRED,
2471 HTTP_STATUS_FORBIDDEN,
2472 HTTP_STATUS_NOT_FOUND,
2473 HTTP_STATUS_METHOD_NOT_ALLOWED,
2474 HTTP_STATUS_NOT_ACCEPTABLE,
2475 HTTP_STATUS_PROXY_AUTH_REQUIRED,
2476 HTTP_STATUS_REQUEST_TIMEOUT,
2477 HTTP_STATUS_CONFLICT,
2479 HTTP_STATUS_LENGTH_REQUIRED,
2480 HTTP_STATUS_PRECONDITION_FAILED,
2481 HTTP_STATUS_REQ_ENTITY_TOO_LARGE,
2482 HTTP_STATUS_REQ_URI_TOO_LONG,
2483 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE,
2484 HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE,
2485 HTTP_STATUS_EXPECTATION_FAILED,
2487 HTTP_STATUS_INTERNAL_SERVER_ERROR = 500,
2488 HTTP_STATUS_NOT_IMPLEMENTED,
2489 HTTP_STATUS_BAD_GATEWAY,
2490 HTTP_STATUS_SERVICE_UNAVAILABLE,
2491 HTTP_STATUS_GATEWAY_TIMEOUT,
2492 HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED,
2495 struct lws_process_html_args {
2496 char *p; /**< pointer to the buffer containing the data */
2497 int len; /**< length of the original data at p */
2498 int max_len; /**< maximum length we can grow the data to */
2499 int final; /**< set if this is the last chunk of the file */
2502 typedef const char *(*lws_process_html_state_cb)(void *data, int index);
2504 struct lws_process_html_state {
2505 char *start; /**< pointer to start of match */
2506 char swallow[16]; /**< matched character buffer */
2507 int pos; /**< position in match */
2508 void *data; /**< opaque pointer */
2509 const char * const *vars; /**< list of variable names */
2510 int count_vars; /**< count of variable names */
2512 lws_process_html_state_cb replace; /**< called on match to perform substitution */
2515 /*! lws_chunked_html_process() - generic chunked substitution
2516 * \param args: buffer to process using chunked encoding
2517 * \param s: current processing state
2519 LWS_VISIBLE LWS_EXTERN int
2520 lws_chunked_html_process(struct lws_process_html_args *args,
2521 struct lws_process_html_state *s);
2524 /** \defgroup HTTP-headers-read HTTP headers: read
2527 * ##HTTP header releated functions
2529 * In lws the client http headers are temporarily stored in a pool, only for the
2530 * duration of the http part of the handshake. It's because in most cases,
2531 * the header content is ignored for the whole rest of the connection lifetime
2532 * and would then just be taking up space needlessly.
2534 * During LWS_CALLBACK_HTTP when the URI path is delivered is the last time
2535 * the http headers are still allocated, you can use these apis then to
2536 * look at and copy out interesting header content (cookies, etc)
2538 * Notice that the header total length reported does not include a terminating
2539 * '\0', however you must allocate for it when using the _copy apis. So the
2540 * length reported for a header containing "123" is 3, but you must provide
2541 * a buffer of length 4 so that "123\0" may be copied into it, or the copy
2542 * will fail with a nonzero return code.
2544 * In the special case of URL arguments, like ?x=1&y=2, the arguments are
2545 * stored in a token named for the method, eg, WSI_TOKEN_GET_URI if it
2546 * was a GET or WSI_TOKEN_POST_URI if POST. You can check the total
2547 * length to confirm the method.
2549 * For URL arguments, each argument is stored urldecoded in a "fragment", so
2550 * you can use the fragment-aware api lws_hdr_copy_fragment() to access each
2551 * argument in turn: the fragments contain urldecoded strings like x=1 or y=2.
2553 * As a convenience, lws has an api that will find the fragment with a
2554 * given name= part, lws_get_urlarg_by_name().
2558 /** struct lws_tokens
2559 * you need these to look at headers that have been parsed if using the
2560 * LWS_CALLBACK_FILTER_CONNECTION callback. If a header from the enum
2561 * list below is absent, .token = NULL and token_len = 0. Otherwise .token
2562 * points to .token_len chars containing that header content.
2565 char *token; /**< pointer to start of the token */
2566 int token_len; /**< length of the token's value */
2569 /* enum lws_token_indexes
2570 * these have to be kept in sync with lextable.h / minilex.c
2572 * NOTE: These public enums are part of the abi. If you want to add one,
2573 * add it at where specified so existing users are unaffected.
2575 enum lws_token_indexes {
2576 WSI_TOKEN_GET_URI = 0,
2577 WSI_TOKEN_POST_URI = 1,
2578 WSI_TOKEN_OPTIONS_URI = 2,
2580 WSI_TOKEN_CONNECTION = 4,
2581 WSI_TOKEN_UPGRADE = 5,
2582 WSI_TOKEN_ORIGIN = 6,
2583 WSI_TOKEN_DRAFT = 7,
2584 WSI_TOKEN_CHALLENGE = 8,
2585 WSI_TOKEN_EXTENSIONS = 9,
2586 WSI_TOKEN_KEY1 = 10,
2587 WSI_TOKEN_KEY2 = 11,
2588 WSI_TOKEN_PROTOCOL = 12,
2589 WSI_TOKEN_ACCEPT = 13,
2590 WSI_TOKEN_NONCE = 14,
2591 WSI_TOKEN_HTTP = 15,
2592 WSI_TOKEN_HTTP2_SETTINGS = 16,
2593 WSI_TOKEN_HTTP_ACCEPT = 17,
2594 WSI_TOKEN_HTTP_AC_REQUEST_HEADERS = 18,
2595 WSI_TOKEN_HTTP_IF_MODIFIED_SINCE = 19,
2596 WSI_TOKEN_HTTP_IF_NONE_MATCH = 20,
2597 WSI_TOKEN_HTTP_ACCEPT_ENCODING = 21,
2598 WSI_TOKEN_HTTP_ACCEPT_LANGUAGE = 22,
2599 WSI_TOKEN_HTTP_PRAGMA = 23,
2600 WSI_TOKEN_HTTP_CACHE_CONTROL = 24,
2601 WSI_TOKEN_HTTP_AUTHORIZATION = 25,
2602 WSI_TOKEN_HTTP_COOKIE = 26,
2603 WSI_TOKEN_HTTP_CONTENT_LENGTH = 27,
2604 WSI_TOKEN_HTTP_CONTENT_TYPE = 28,
2605 WSI_TOKEN_HTTP_DATE = 29,
2606 WSI_TOKEN_HTTP_RANGE = 30,
2607 WSI_TOKEN_HTTP_REFERER = 31,
2609 WSI_TOKEN_VERSION = 33,
2610 WSI_TOKEN_SWORIGIN = 34,
2612 WSI_TOKEN_HTTP_COLON_AUTHORITY = 35,
2613 WSI_TOKEN_HTTP_COLON_METHOD = 36,
2614 WSI_TOKEN_HTTP_COLON_PATH = 37,
2615 WSI_TOKEN_HTTP_COLON_SCHEME = 38,
2616 WSI_TOKEN_HTTP_COLON_STATUS = 39,
2618 WSI_TOKEN_HTTP_ACCEPT_CHARSET = 40,
2619 WSI_TOKEN_HTTP_ACCEPT_RANGES = 41,
2620 WSI_TOKEN_HTTP_ACCESS_CONTROL_ALLOW_ORIGIN = 42,
2621 WSI_TOKEN_HTTP_AGE = 43,
2622 WSI_TOKEN_HTTP_ALLOW = 44,
2623 WSI_TOKEN_HTTP_CONTENT_DISPOSITION = 45,
2624 WSI_TOKEN_HTTP_CONTENT_ENCODING = 46,
2625 WSI_TOKEN_HTTP_CONTENT_LANGUAGE = 47,
2626 WSI_TOKEN_HTTP_CONTENT_LOCATION = 48,
2627 WSI_TOKEN_HTTP_CONTENT_RANGE = 49,
2628 WSI_TOKEN_HTTP_ETAG = 50,
2629 WSI_TOKEN_HTTP_EXPECT = 51,
2630 WSI_TOKEN_HTTP_EXPIRES = 52,
2631 WSI_TOKEN_HTTP_FROM = 53,
2632 WSI_TOKEN_HTTP_IF_MATCH = 54,
2633 WSI_TOKEN_HTTP_IF_RANGE = 55,
2634 WSI_TOKEN_HTTP_IF_UNMODIFIED_SINCE = 56,
2635 WSI_TOKEN_HTTP_LAST_MODIFIED = 57,
2636 WSI_TOKEN_HTTP_LINK = 58,
2637 WSI_TOKEN_HTTP_LOCATION = 59,
2638 WSI_TOKEN_HTTP_MAX_FORWARDS = 60,
2639 WSI_TOKEN_HTTP_PROXY_AUTHENTICATE = 61,
2640 WSI_TOKEN_HTTP_PROXY_AUTHORIZATION = 62,
2641 WSI_TOKEN_HTTP_REFRESH = 63,
2642 WSI_TOKEN_HTTP_RETRY_AFTER = 64,
2643 WSI_TOKEN_HTTP_SERVER = 65,
2644 WSI_TOKEN_HTTP_SET_COOKIE = 66,
2645 WSI_TOKEN_HTTP_STRICT_TRANSPORT_SECURITY = 67,
2646 WSI_TOKEN_HTTP_TRANSFER_ENCODING = 68,
2647 WSI_TOKEN_HTTP_USER_AGENT = 69,
2648 WSI_TOKEN_HTTP_VARY = 70,
2649 WSI_TOKEN_HTTP_VIA = 71,
2650 WSI_TOKEN_HTTP_WWW_AUTHENTICATE = 72,
2652 WSI_TOKEN_PATCH_URI = 73,
2653 WSI_TOKEN_PUT_URI = 74,
2654 WSI_TOKEN_DELETE_URI = 75,
2656 WSI_TOKEN_HTTP_URI_ARGS = 76,
2657 WSI_TOKEN_PROXY = 77,
2658 WSI_TOKEN_HTTP_X_REAL_IP = 78,
2659 WSI_TOKEN_HTTP1_0 = 79,
2660 WSI_TOKEN_X_FORWARDED_FOR = 80,
2662 /****** add new things just above ---^ ******/
2664 /* use token storage to stash these internally, not for
2667 _WSI_TOKEN_CLIENT_SENT_PROTOCOLS,
2668 _WSI_TOKEN_CLIENT_PEER_ADDRESS,
2669 _WSI_TOKEN_CLIENT_URI,
2670 _WSI_TOKEN_CLIENT_HOST,
2671 _WSI_TOKEN_CLIENT_ORIGIN,
2672 _WSI_TOKEN_CLIENT_METHOD,
2674 /* always last real token index*/
2677 /* parser state additions, no storage associated */
2678 WSI_TOKEN_NAME_PART,
2680 WSI_TOKEN_SKIPPING_SAW_CR,
2681 WSI_PARSING_COMPLETE,
2682 WSI_INIT_TOKEN_MUXURL,
2685 struct lws_token_limits {
2686 unsigned short token_limit[WSI_TOKEN_COUNT]; /**< max chars for this token */
2690 * lws_token_to_string() - returns a textual representation of a hdr token index
2692 * \param: token index
2694 LWS_VISIBLE LWS_EXTERN const unsigned char *
2695 lws_token_to_string(enum lws_token_indexes token);
2699 * lws_hdr_total_length: report length of all fragments of a header totalled up
2700 * The returned length does not include the space for a
2703 * \param wsi: websocket connection
2704 * \param h: which header index we are interested in
2706 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2707 lws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h);
2710 * lws_hdr_fragment_length: report length of a single fragment of a header
2711 * The returned length does not include the space for a
2714 * \param wsi: websocket connection
2715 * \param h: which header index we are interested in
2716 * \param frag_idx: which fragment of h we want to get the length of
2718 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2719 lws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx);
2722 * lws_hdr_copy() - copy a single fragment of the given header to a buffer
2723 * The buffer length len must include space for an additional
2724 * terminating '\0', or it will fail returning -1.
2726 * \param wsi: websocket connection
2727 * \param dest: destination buffer
2728 * \param len: length of destination buffer
2729 * \param h: which header index we are interested in
2731 * copies the whole, aggregated header, even if it was delivered in
2732 * several actual headers piece by piece
2734 LWS_VISIBLE LWS_EXTERN int
2735 lws_hdr_copy(struct lws *wsi, char *dest, int len, enum lws_token_indexes h);
2738 * lws_hdr_copy_fragment() - copy a single fragment of the given header to a buffer
2739 * The buffer length len must include space for an additional
2740 * terminating '\0', or it will fail returning -1.
2741 * If the requested fragment index is not present, it fails
2744 * \param wsi: websocket connection
2745 * \param dest: destination buffer
2746 * \param len: length of destination buffer
2747 * \param h: which header index we are interested in
2748 * \param frag_idx: which fragment of h we want to copy
2750 * Normally this is only useful
2751 * to parse URI arguments like ?x=1&y=2, token index WSI_TOKEN_HTTP_URI_ARGS
2752 * fragment 0 will contain "x=1" and fragment 1 "y=2"
2754 LWS_VISIBLE LWS_EXTERN int
2755 lws_hdr_copy_fragment(struct lws *wsi, char *dest, int len,
2756 enum lws_token_indexes h, int frag_idx);
2759 * lws_get_urlarg_by_name() - return pointer to arg value if present
2760 * \param wsi: the connection to check
2761 * \param name: the arg name, like "token="
2762 * \param buf: the buffer to receive the urlarg (including the name= part)
2763 * \param len: the length of the buffer to receive the urlarg
2765 * Returns NULL if not found or a pointer inside buf to just after the
2768 LWS_VISIBLE LWS_EXTERN const char *
2769 lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len);
2772 /*! \defgroup HTTP-headers-create HTTP headers: create
2774 * ## HTTP headers: Create
2776 * These apis allow you to create HTTP response headers in a way compatible with
2777 * both HTTP/1.x and HTTP/2.
2779 * They each append to a buffer taking care about the buffer end, which is
2780 * passed in as a pointer. When data is written to the buffer, the current
2781 * position p is updated accordingly.
2783 * All of these apis are LWS_WARN_UNUSED_RESULT as they can run out of space
2784 * and fail with nonzero return.
2788 * lws_add_http_header_status() - add the HTTP response status code
2790 * \param wsi: the connection to check
2791 * \param code: an HTTP code like 200, 404 etc (see enum http_status)
2792 * \param p: pointer to current position in buffer pointer
2793 * \param end: pointer to end of buffer
2795 * Adds the initial response code, so should be called first
2797 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2798 lws_add_http_header_status(struct lws *wsi,
2799 unsigned int code, unsigned char **p,
2800 unsigned char *end);
2802 * lws_add_http_header_by_name() - append named header and value
2804 * \param wsi: the connection to check
2805 * \param name: the hdr name, like "my-header"
2806 * \param value: the value after the = for this header
2807 * \param length: the length of the value
2808 * \param p: pointer to current position in buffer pointer
2809 * \param end: pointer to end of buffer
2811 * Appends name: value to the headers
2813 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2814 lws_add_http_header_by_name(struct lws *wsi, const unsigned char *name,
2815 const unsigned char *value, int length,
2816 unsigned char **p, unsigned char *end);
2818 * lws_add_http_header_by_token() - append given header and value
2820 * \param wsi: the connection to check
2821 * \param token: the token index for the hdr
2822 * \param value: the value after the = for this header
2823 * \param length: the length of the value
2824 * \param p: pointer to current position in buffer pointer
2825 * \param end: pointer to end of buffer
2827 * Appends name=value to the headers, but is able to take advantage of better
2828 * HTTP/2 coding mechanisms where possible.
2830 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2831 lws_add_http_header_by_token(struct lws *wsi, enum lws_token_indexes token,
2832 const unsigned char *value, int length,
2833 unsigned char **p, unsigned char *end);
2835 * lws_add_http_header_by_name() - append content-length helper
2837 * \param wsi: the connection to check
2838 * \param content_length: the content length to use
2839 * \param p: pointer to current position in buffer pointer
2840 * \param end: pointer to end of buffer
2842 * Appends content-length: content_length to the headers
2844 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2845 lws_add_http_header_content_length(struct lws *wsi,
2846 unsigned long content_length,
2847 unsigned char **p, unsigned char *end);
2849 * lws_finalize_http_header() - terminate header block
2851 * \param wsi: the connection to check
2852 * \param p: pointer to current position in buffer pointer
2853 * \param end: pointer to end of buffer
2855 * Indicates no more headers will be added
2857 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2858 lws_finalize_http_header(struct lws *wsi, unsigned char **p,
2859 unsigned char *end);
2862 /** \defgroup form-parsing Form Parsing
2864 * ##POSTed form parsing functions
2866 * These lws_spa (stateful post arguments) apis let you parse and urldecode
2867 * POSTed form arguments, both using simple urlencoded and multipart transfer
2870 * It's capable of handling file uploads as well a named input parsing,
2871 * and the apis are the same for both form upload styles.
2873 * You feed it a list of parameter names and it creates pointers to the
2874 * urldecoded arguments: file upload parameters pass the file data in chunks to
2875 * a user-supplied callback as they come.
2877 * Since it's stateful, it handles the incoming data needing more than one
2878 * POST_BODY callback and has no limit on uploaded file size.
2882 /** enum lws_spa_fileupload_states */
2883 enum lws_spa_fileupload_states {
2885 /**< a chunk of file content has arrived */
2886 LWS_UFS_FINAL_CONTENT,
2887 /**< the last chunk (possibly zero length) of file content has arrived */
2889 /**< a new file is starting to arrive */
2893 * lws_spa_fileupload_cb() - callback to receive file upload data
2895 * \param data: opt_data pointer set in lws_spa_create
2896 * \param name: name of the form field being uploaded
2897 * \param filename: original filename from client
2898 * \param buf: start of data to receive
2899 * \param len: length of data to receive
2900 * \param state: information about how this call relates to file
2902 * Notice name and filename shouldn't be trusted, as they are passed from
2903 * HTTP provided by the client.
2905 typedef int (*lws_spa_fileupload_cb)(void *data, const char *name,
2906 const char *filename, char *buf, int len,
2907 enum lws_spa_fileupload_states state);
2909 /** struct lws_spa - opaque urldecode parser capable of handling multipart
2910 * and file uploads */
2914 * lws_spa_create() - create urldecode parser
2916 * \param wsi: lws connection (used to find Content Type)
2917 * \param param_names: array of form parameter names, like "username"
2918 * \param count_params: count of param_names
2919 * \param max_storage: total amount of form parameter values we can store
2920 * \param opt_cb: NULL, or callback to receive file upload data.
2921 * \param opt_data: NULL, or user pointer provided to opt_cb.
2923 * Creates a urldecode parser and initializes it.
2925 * opt_cb can be NULL if you just want normal name=value parsing, however
2926 * if one or more entries in your form are bulk data (file transfer), you
2927 * can provide this callback and filter on the name callback parameter to
2928 * treat that urldecoded data separately. The callback should return -1
2929 * in case of fatal error, and 0 if OK.
2931 LWS_VISIBLE LWS_EXTERN struct lws_spa *
2932 lws_spa_create(struct lws *wsi, const char * const *param_names,
2933 int count_params, int max_storage, lws_spa_fileupload_cb opt_cb,
2937 * lws_spa_process() - parses a chunk of input data
2939 * \param spa: the parser object previously created
2940 * \param in: incoming, urlencoded data
2941 * \param len: count of bytes valid at \param in
2943 LWS_VISIBLE LWS_EXTERN int
2944 lws_spa_process(struct lws_spa *spa, const char *in, int len);
2947 * lws_spa_finalize() - indicate incoming data completed
2949 * \param spa: the parser object previously created
2951 LWS_VISIBLE LWS_EXTERN int
2952 lws_spa_finalize(struct lws_spa *spa);
2955 * lws_spa_get_length() - return length of parameter value
2957 * \param spa: the parser object previously created
2958 * \param n: parameter ordinal to return length of value for
2960 LWS_VISIBLE LWS_EXTERN int
2961 lws_spa_get_length(struct lws_spa *spa, int n);
2964 * lws_spa_get_string() - return pointer to parameter value
2965 * \param spa: the parser object previously created
2966 * \param n: parameter ordinal to return pointer to value for
2968 LWS_VISIBLE LWS_EXTERN const char *
2969 lws_spa_get_string(struct lws_spa *spa, int n);
2972 * lws_spa_destroy() - destroy parser object
2974 * \param spa: the parser object previously created
2976 LWS_VISIBLE LWS_EXTERN int
2977 lws_spa_destroy(struct lws_spa *spa);
2980 /*! \defgroup urlendec Urlencode and Urldecode
2983 * ##HTML chunked Substitution
2985 * APIs for receiving chunks of text, replacing a set of variable names via
2986 * a callback, and then prepending and appending HTML chunked encoding
2992 * lws_urlencode() - like strncpy but with urlencoding
2994 * \param escaped: output buffer
2995 * \param string: input buffer ('/0' terminated)
2996 * \param len: output buffer max length
2998 * Because urlencoding expands the output string, it's not
2999 * possible to do it in-place, ie, with escaped == string
3001 LWS_VISIBLE LWS_EXTERN const char *
3002 lws_urlencode(char *escaped, const char *string, int len);
3007 * This simple urldecode only operates until the first '\0' and requires the
3008 * data to exist all at once
3011 * lws_urldecode() - like strncpy but with urldecoding
3013 * \param string: output buffer
3014 * \param escaped: input buffer ('\0' terminated)
3015 * \param len: output buffer max length
3017 * This is only useful for '\0' terminated strings
3019 * Since urldecoding only shrinks the output string, it is possible to
3020 * do it in-place, ie, string == escaped
3022 LWS_VISIBLE LWS_EXTERN int
3023 lws_urldecode(char *string, const char *escaped, int len);
3026 * lws_return_http_status() - Return simple http status
3027 * \param wsi: Websocket instance (available from user callback)
3028 * \param code: Status index, eg, 404
3029 * \param html_body: User-readable HTML description < 1KB, or NULL
3031 * Helper to report HTTP errors back to the client cleanly and
3034 LWS_VISIBLE LWS_EXTERN int
3035 lws_return_http_status(struct lws *wsi, unsigned int code,
3036 const char *html_body);
3039 * lws_http_redirect() - write http redirect into buffer
3041 * \param wsi: websocket connection
3042 * \param code: HTTP response code (eg, 301)
3043 * \param loc: where to redirect to
3044 * \param len: length of loc
3045 * \param p: pointer current position in buffer (updated as we write)
3046 * \param end: pointer to end of buffer
3048 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3049 lws_http_redirect(struct lws *wsi, int code, const unsigned char *loc, int len,
3050 unsigned char **p, unsigned char *end);
3053 * lws_http_transaction_completed() - wait for new http transaction or close
3054 * \param wsi: websocket connection
3056 * Returns 1 if the HTTP connection must close now
3057 * Returns 0 and resets connection to wait for new HTTP header /
3058 * transaction if possible
3060 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3061 lws_http_transaction_completed(struct lws *wsi);
3064 /*! \defgroup pur Sanitize / purify SQL and JSON helpers
3066 * ##Sanitize / purify SQL and JSON helpers
3068 * APIs for escaping untrusted JSON and SQL safely before use
3073 * lws_sql_purify() - like strncpy but with escaping for sql quotes
3075 * \param escaped: output buffer
3076 * \param string: input buffer ('/0' terminated)
3077 * \param len: output buffer max length
3079 * Because escaping expands the output string, it's not
3080 * possible to do it in-place, ie, with escaped == string
3082 LWS_VISIBLE LWS_EXTERN const char *
3083 lws_sql_purify(char *escaped, const char *string, int len);
3086 * lws_json_purify() - like strncpy but with escaping for json chars
3088 * \param escaped: output buffer
3089 * \param string: input buffer ('/0' terminated)
3090 * \param len: output buffer max length
3092 * Because escaping expands the output string, it's not
3093 * possible to do it in-place, ie, with escaped == string
3095 LWS_VISIBLE LWS_EXTERN const char *
3096 lws_json_purify(char *escaped, const char *string, int len);
3099 /*! \defgroup ev libev helpers
3103 * APIs specific to libev event loop itegration
3107 #ifdef LWS_USE_LIBEV
3108 typedef void (lws_ev_signal_cb_t)(EV_P_ struct ev_signal *w, int revents);
3110 LWS_VISIBLE LWS_EXTERN int
3111 lws_ev_sigint_cfg(struct lws_context *context, int use_ev_sigint,
3112 lws_ev_signal_cb_t *cb);
3114 LWS_VISIBLE LWS_EXTERN int
3115 lws_ev_initloop(struct lws_context *context, struct ev_loop *loop, int tsi);
3117 LWS_VISIBLE LWS_EXTERN void
3118 lws_ev_sigint_cb(struct ev_loop *loop, struct ev_signal *watcher, int revents);
3119 #endif /* LWS_USE_LIBEV */
3123 /*! \defgroup uv libuv helpers
3127 * APIs specific to libuv event loop itegration
3130 #ifdef LWS_USE_LIBUV
3131 LWS_VISIBLE LWS_EXTERN int
3132 lws_uv_sigint_cfg(struct lws_context *context, int use_uv_sigint,
3135 LWS_VISIBLE LWS_EXTERN void
3136 lws_libuv_run(const struct lws_context *context, int tsi);
3138 LWS_VISIBLE LWS_EXTERN void
3139 lws_libuv_stop(struct lws_context *context);
3141 LWS_VISIBLE LWS_EXTERN void
3142 lws_libuv_stop_without_kill(const struct lws_context *context, int tsi);
3144 LWS_VISIBLE LWS_EXTERN int
3145 lws_uv_initloop(struct lws_context *context, uv_loop_t *loop, int tsi);
3147 LWS_VISIBLE LWS_EXTERN uv_loop_t *
3148 lws_uv_getloop(struct lws_context *context, int tsi);
3150 LWS_VISIBLE LWS_EXTERN void
3151 lws_uv_sigint_cb(uv_signal_t *watcher, int signum);
3152 #endif /* LWS_USE_LIBUV */
3155 /*! \defgroup timeout Connection timeouts
3157 APIs related to setting connection timeouts
3162 * NOTE: These public enums are part of the abi. If you want to add one,
3163 * add it at where specified so existing users are unaffected.
3165 enum pending_timeout {
3166 NO_PENDING_TIMEOUT = 0,
3167 PENDING_TIMEOUT_AWAITING_PROXY_RESPONSE = 1,
3168 PENDING_TIMEOUT_AWAITING_CONNECT_RESPONSE = 2,
3169 PENDING_TIMEOUT_ESTABLISH_WITH_SERVER = 3,
3170 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE = 4,
3171 PENDING_TIMEOUT_AWAITING_PING = 5,
3172 PENDING_TIMEOUT_CLOSE_ACK = 6,
3173 PENDING_TIMEOUT_AWAITING_EXTENSION_CONNECT_RESPONSE = 7,
3174 PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE = 8,
3175 PENDING_TIMEOUT_SSL_ACCEPT = 9,
3176 PENDING_TIMEOUT_HTTP_CONTENT = 10,
3177 PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND = 11,
3178 PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE = 12,
3179 PENDING_TIMEOUT_SHUTDOWN_FLUSH = 13,
3180 PENDING_TIMEOUT_CGI = 14,
3181 PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE = 15,
3182 PENDING_TIMEOUT_WS_PONG_CHECK_SEND_PING = 16,
3183 PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG = 17,
3184 PENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD = 18,
3186 /****** add new things just above ---^ ******/
3190 * lws_set_timeout() - marks the wsi as subject to a timeout
3192 * You will not need this unless you are doing something special
3194 * \param wsi: Websocket connection instance
3195 * \param reason: timeout reason
3196 * \param secs: how many seconds
3198 LWS_VISIBLE LWS_EXTERN void
3199 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs);
3202 /*! \defgroup sending-data Sending data
3204 APIs related to writing data on a connection
3207 #if !defined(LWS_SIZEOFPTR)
3208 #define LWS_SIZEOFPTR (sizeof (void *))
3210 #if !defined(u_int64_t)
3211 #define u_int64_t unsigned long long
3214 #if defined(__x86_64__)
3215 #define _LWS_PAD_SIZE 16 /* Intel recommended for best performance */
3217 #define _LWS_PAD_SIZE LWS_SIZEOFPTR /* Size of a pointer on the target arch */
3219 #define _LWS_PAD(n) (((n) % _LWS_PAD_SIZE) ? \
3220 ((n) + (_LWS_PAD_SIZE - ((n) % _LWS_PAD_SIZE))) : (n))
3221 #define LWS_PRE _LWS_PAD(4 + 10)
3222 /* used prior to 1.7 and retained for backward compatibility */
3223 #define LWS_SEND_BUFFER_PRE_PADDING LWS_PRE
3224 #define LWS_SEND_BUFFER_POST_PADDING 0
3227 * NOTE: These public enums are part of the abi. If you want to add one,
3228 * add it at where specified so existing users are unaffected.
3230 enum lws_write_protocol {
3232 /**< Send a ws TEXT message,the pointer must have LWS_PRE valid
3233 * memory behind it. The receiver expects only valid utf-8 in the
3235 LWS_WRITE_BINARY = 1,
3236 /**< Send a ws BINARY message, the pointer must have LWS_PRE valid
3237 * memory behind it. Any sequence of bytes is valid */
3238 LWS_WRITE_CONTINUATION = 2,
3239 /**< Continue a previous ws message, the pointer must have LWS_PRE valid
3240 * memory behind it */
3242 /**< Send HTTP content */
3244 /* LWS_WRITE_CLOSE is handled by lws_close_reason() */
3248 /* Same as write_http but we know this write ends the transaction */
3249 LWS_WRITE_HTTP_FINAL = 7,
3253 LWS_WRITE_HTTP_HEADERS = 8,
3254 /**< Send http headers (http2 encodes this payload and LWS_WRITE_HTTP
3255 * payload differently, http 1.x links also handle this correctly. so
3256 * to be compatible with both in the future,header response part should
3257 * be sent using this regardless of http version expected)
3260 /****** add new things just above ---^ ******/
3264 LWS_WRITE_NO_FIN = 0x40,
3265 /**< This part of the message is not the end of the message */
3267 LWS_WRITE_CLIENT_IGNORE_XOR_MASK = 0x80
3268 /**< client packet payload goes out on wire unmunged
3269 * only useful for security tests since normal servers cannot
3270 * decode the content if used */
3275 * lws_write() - Apply protocol then write data to client
3276 * \param wsi: Websocket instance (available from user callback)
3277 * \param buf: The data to send. For data being sent on a websocket
3278 * connection (ie, not default http), this buffer MUST have
3279 * LWS_PRE bytes valid BEFORE the pointer.
3280 * This is so the protocol header data can be added in-situ.
3281 * \param len: Count of the data bytes in the payload starting from buf
3282 * \param protocol: Use LWS_WRITE_HTTP to reply to an http connection, and one
3283 * of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
3284 * data on a websockets connection. Remember to allow the extra
3285 * bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
3288 * This function provides the way to issue data back to the client
3289 * for both http and websocket protocols.
3293 * When sending with websocket protocol
3297 * LWS_WRITE_CONTINUATION,
3301 * the send buffer has to have LWS_PRE bytes valid BEFORE
3302 * the buffer pointer you pass to lws_write().
3304 * This allows us to add protocol info before and after the data, and send as
3305 * one packet on the network without payload copying, for maximum efficiency.
3307 * So for example you need this kind of code to use lws_write with a
3310 * char buf[LWS_PRE + 128];
3312 * // fill your part of the buffer... for example here it's all zeros
3313 * memset(&buf[LWS_PRE], 0, 128);
3315 * lws_write(wsi, &buf[LWS_PRE], 128, LWS_WRITE_TEXT);
3317 * When sending HTTP, with
3320 * LWS_WRITE_HTTP_HEADERS
3321 * LWS_WRITE_HTTP_FINAL
3323 * there is no protocol data prepended, and don't need to take care about the
3324 * LWS_PRE bytes valid before the buffer pointer.
3326 * LWS_PRE is at least the frame nonce + 2 header + 8 length
3327 * LWS_SEND_BUFFER_POST_PADDING is deprecated, it's now 0 and can be left off.
3328 * The example apps no longer use it.
3330 * Pad LWS_PRE to the CPU word size, so that word references
3331 * to the address immediately after the padding won't cause an unaligned access
3332 * error. Sometimes for performance reasons the recommended padding is even
3333 * larger than sizeof(void *).
3335 * In the case of sending using websocket protocol, be sure to allocate
3336 * valid storage before and after buf as explained above. This scheme
3337 * allows maximum efficiency of sending data and protocol in a single
3338 * packet while not burdening the user code with any protocol knowledge.
3340 * Return may be -1 for a fatal error needing connection close, or the
3341 * number of bytes sent.
3346 * The OS may not accept everything you asked to write on the connection.
3348 * Posix defines POLLOUT indication from poll() to show that the connection
3349 * will accept more write data, but it doesn't specifiy how much. It may just
3350 * accept one byte of whatever you wanted to send.
3352 * LWS will buffer the remainder automatically, and send it out autonomously.
3354 * During that time, WRITABLE callbacks will be suppressed.
3356 * This is to handle corner cases where unexpectedly the OS refuses what we
3357 * usually expect it to accept. You should try to send in chunks that are
3358 * almost always accepted in order to avoid the inefficiency of the buffering.
3360 LWS_VISIBLE LWS_EXTERN int
3361 lws_write(struct lws *wsi, unsigned char *buf, size_t len,
3362 enum lws_write_protocol protocol);
3364 /* helper for case where buffer may be const */
3365 #define lws_write_http(wsi, buf, len) \
3366 lws_write(wsi, (unsigned char *)(buf), len, LWS_WRITE_HTTP)
3369 /** \defgroup callback-when-writeable Callback when writeable
3371 * ##Callback When Writeable
3373 * lws can only write data on a connection when it is able to accept more
3374 * data without blocking.
3376 * So a basic requirement is we should only use the lws_write() apis when the
3377 * connection we want to write on says that he can accept more data.
3379 * When lws cannot complete your send at the time, it will buffer the data
3380 * and send it in the background, suppressing any further WRITEABLE callbacks
3381 * on that connection until it completes. So it is important to write new
3382 * things in a new writeable callback.
3384 * These apis reflect the various ways we can indicate we would like to be
3385 * called back when one or more connections is writeable.
3390 * lws_callback_on_writable() - Request a callback when this socket
3391 * becomes able to be written to without
3394 * \param wsi: Websocket connection instance to get callback for
3396 * - Which: only this wsi
3397 * - When: when the individual connection becomes writeable
3398 * - What: LWS_CALLBACK_*_WRITEABLE
3400 LWS_VISIBLE LWS_EXTERN int
3401 lws_callback_on_writable(struct lws *wsi);
3404 * lws_callback_on_writable_all_protocol() - Request a callback for all
3405 * connections on same vhost using the given protocol when it
3406 * becomes possible to write to each socket without
3409 * \param context: lws_context
3410 * \param protocol: Protocol whose connections will get callbacks
3412 * - Which: connections using this protocol on ANY VHOST
3413 * - When: when the individual connection becomes writeable
3414 * - What: LWS_CALLBACK_*_WRITEABLE
3416 LWS_VISIBLE LWS_EXTERN int
3417 lws_callback_on_writable_all_protocol(const struct lws_context *context,
3418 const struct lws_protocols *protocol);
3421 * lws_callback_on_writable_all_protocol_vhost() - Request a callback for
3422 * all connections using the given protocol when it
3423 * becomes possible to write to each socket without
3426 * \param vhost: Only consider connections on this lws_vhost
3427 * \param protocol: Protocol whose connections will get callbacks
3429 * - Which: connections using this protocol on GIVEN VHOST ONLY
3430 * - When: when the individual connection becomes writeable
3431 * - What: LWS_CALLBACK_*_WRITEABLE
3433 LWS_VISIBLE LWS_EXTERN int
3434 lws_callback_on_writable_all_protocol_vhost(const struct lws_vhost *vhost,
3435 const struct lws_protocols *protocol);
3438 * lws_callback_all_protocol() - Callback all connections using
3439 * the given protocol with the given reason
3441 * \param context: lws_context
3442 * \param protocol: Protocol whose connections will get callbacks
3443 * \param reason: Callback reason index
3445 * - Which: connections using this protocol on ALL VHOSTS
3446 * - When: when the individual connection becomes writeable
3449 LWS_VISIBLE LWS_EXTERN int
3450 lws_callback_all_protocol(struct lws_context *context,
3451 const struct lws_protocols *protocol, int reason);
3454 * lws_callback_all_protocol_vhost() - Callback all connections using
3455 * the given protocol with the given reason
3457 * \param vh: Vhost whose connections will get callbacks
3458 * \param protocol: Which protocol to match
3459 * \param reason: Callback reason index
3461 * - Which: connections using this protocol on GIVEN VHOST ONLY
3465 LWS_VISIBLE LWS_EXTERN int
3466 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
3467 const struct lws_protocols *protocol, int reason);
3470 * lws_callback_vhost_protocols() - Callback all protocols enabled on a vhost
3471 * with the given reason
3473 * \param wsi: wsi whose vhost will get callbacks
3474 * \param reason: Callback reason index
3475 * \param in: in argument to callback
3476 * \param len: len argument to callback
3478 * - Which: connections using this protocol on same VHOST as wsi ONLY
3482 LWS_VISIBLE LWS_EXTERN int
3483 lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len);
3485 LWS_VISIBLE LWS_EXTERN int
3486 lws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason,
3487 void *user, void *in, size_t len);
3490 * lws_get_socket_fd() - returns the socket file descriptor
3492 * You will not need this unless you are doing something special
3494 * \param wsi: Websocket connection instance
3496 LWS_VISIBLE LWS_EXTERN int
3497 lws_get_socket_fd(struct lws *wsi);
3500 * lws_get_peer_write_allowance() - get the amount of data writeable to peer
3503 * \param wsi: Websocket connection instance
3505 * if the protocol does not have any guidance, returns -1. Currently only
3506 * http2 connections get send window information from this API. But your code
3507 * should use it so it can work properly with any protocol.
3509 * If nonzero return is the amount of payload data the peer or intermediary has
3510 * reported it has buffer space for. That has NO relationship with the amount
3511 * of buffer space your OS can accept on this connection for a write action.
3513 * This number represents the maximum you could send to the peer or intermediary
3514 * on this connection right now without the protocol complaining.
3516 * lws manages accounting for send window updates and payload writes
3517 * automatically, so this number reflects the situation at the peer or
3518 * intermediary dynamically.
3520 LWS_VISIBLE LWS_EXTERN size_t
3521 lws_get_peer_write_allowance(struct lws *wsi);
3525 * lws_rx_flow_control() - Enable and disable socket servicing for
3528 * If the output side of a server process becomes choked, this allows flow
3529 * control for the input side.
3531 * \param wsi: Websocket connection instance to get callback for
3532 * \param enable: 0 = disable read servicing for this connection, 1 = enable
3534 LWS_VISIBLE LWS_EXTERN int
3535 lws_rx_flow_control(struct lws *wsi, int enable);
3538 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
3540 * When the user server code realizes it can accept more input, it can
3541 * call this to have the RX flow restriction removed from all connections using
3542 * the given protocol.
3543 * \param context: lws_context
3544 * \param protocol: all connections using this protocol will be allowed to receive
3546 LWS_VISIBLE LWS_EXTERN void
3547 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
3548 const struct lws_protocols *protocol);
3551 * lws_remaining_packet_payload() - Bytes to come before "overall"
3552 * rx packet is complete
3553 * \param wsi: Websocket instance (available from user callback)
3555 * This function is intended to be called from the callback if the
3556 * user code is interested in "complete packets" from the client.
3557 * libwebsockets just passes through payload as it comes and issues a buffer
3558 * additionally when it hits a built-in limit. The LWS_CALLBACK_RECEIVE
3559 * callback handler can use this API to find out if the buffer it has just
3560 * been given is the last piece of a "complete packet" from the client --
3561 * when that is the case lws_remaining_packet_payload() will return
3564 * Many protocols won't care becuse their packets are always small.
3566 LWS_VISIBLE LWS_EXTERN size_t
3567 lws_remaining_packet_payload(struct lws *wsi);
3570 /** \defgroup sock-adopt Socket adoption helpers
3571 * ##Socket adoption helpers
3573 * When integrating with an external app with its own event loop, these can
3574 * be used to accept connections from someone else's listening socket.
3576 * When using lws own event loop, these are not needed.
3581 * lws_adopt_socket() - adopt foreign socket as if listen socket accepted it
3582 * \param context: lws context
3583 * \param accept_fd: fd of already-accepted socket to adopt
3585 * Either returns new wsi bound to accept_fd, or closes accept_fd and
3586 * returns NULL, having cleaned up any new wsi pieces.
3588 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
3589 * to ws or just serve http.
3591 LWS_VISIBLE LWS_EXTERN struct lws *
3592 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd);
3594 * lws_adopt_socket_readbuf() - adopt foreign socket and first rx as if listen socket accepted it
3595 * \param context: lws context
3596 * \param accept_fd: fd of already-accepted socket to adopt
3597 * \param readbuf: NULL or pointer to data that must be drained before reading from
3599 * \param len: The length of the data held at \param readbuf
3601 * Either returns new wsi bound to accept_fd, or closes accept_fd and
3602 * returns NULL, having cleaned up any new wsi pieces.
3604 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
3605 * to ws or just serve http.
3607 * If your external code did not already read from the socket, you can use
3608 * lws_adopt_socket() instead.
3610 * This api is guaranteed to use the data at \param readbuf first, before reading from
3613 * readbuf is limited to the size of the ah rx buf, currently 2048 bytes.
3615 LWS_VISIBLE LWS_EXTERN struct lws *
3616 lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
3617 const char *readbuf, size_t len);
3620 /** \defgroup net Network related helper APIs
3621 * ##Network related helper APIs
3623 * These wrap miscellaneous useful network-related functions
3628 * lws_canonical_hostname() - returns this host's hostname
3630 * This is typically used by client code to fill in the host parameter
3631 * when making a client connection. You can only call it after the context
3634 * \param context: Websocket context
3636 LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
3637 lws_canonical_hostname(struct lws_context *context);
3640 * lws_get_peer_addresses() - Get client address information
3641 * \param wsi: Local struct lws associated with
3642 * \param fd: Connection socket descriptor
3643 * \param name: Buffer to take client address name
3644 * \param name_len: Length of client address name buffer
3645 * \param rip: Buffer to take client address IP dotted quad
3646 * \param rip_len: Length of client address IP buffer
3648 * This function fills in name and rip with the name and IP of
3649 * the client connected with socket descriptor fd. Names may be
3650 * truncated if there is not enough room. If either cannot be
3651 * determined, they will be returned as valid zero-length strings.
3653 LWS_VISIBLE LWS_EXTERN void
3654 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
3655 int name_len, char *rip, int rip_len);
3658 * lws_get_peer_simple() - Get client address information without RDNS
3660 * \param wsi: Local struct lws associated with
3661 * \param name: Buffer to take client address name
3662 * \param namelen: Length of client address name buffer
3664 * This provides a 123.123.123.123 type IP address in name from the
3665 * peer that has connected to wsi
3667 LWS_VISIBLE LWS_EXTERN const char *
3668 lws_get_peer_simple(struct lws *wsi, char *name, int namelen);
3669 #ifndef LWS_WITH_ESP8266
3671 * lws_interface_to_sa() - Convert interface name or IP to sockaddr struct
3673 * \param ipv6: Allow IPV6 addresses
3674 * \param ifname: Interface name or IP
3675 * \param addr: struct sockaddr_in * to be written
3676 * \param addrlen: Length of addr
3678 * This converts a textual network interface name to a sockaddr usable by
3679 * other network functions
3681 LWS_VISIBLE LWS_EXTERN int
3682 lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr,
3687 /** \defgroup misc Miscellaneous APIs
3688 * ##Miscellaneous APIs
3690 * Various APIs outside of other categories
3695 * lws_snprintf(): snprintf that truncates the returned length too
3697 * \param str: destination buffer
3698 * \param size: bytes left in destination buffer
3699 * \param format: format string
3700 * \param ...: args for format
3702 * This lets you correctly truncate buffers by concatenating lengths, if you
3703 * reach the limit the reported length doesn't exceed the limit.
3705 LWS_VISIBLE LWS_EXTERN int
3706 lws_snprintf(char *str, size_t size, const char *format, ...);
3709 * lws_get_random(): fill a buffer with platform random data
3711 * \param context: the lws context
3712 * \param buf: buffer to fill
3713 * \param len: how much to fill
3715 * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
3716 * it's interested to see if the frame it's dealing with was sent in binary
3719 LWS_VISIBLE LWS_EXTERN int
3720 lws_get_random(struct lws_context *context, void *buf, int len);
3722 * lws_daemonize(): fill a buffer with platform random data
3724 * \param _lock_path: the filepath to write the lock file
3726 * Spawn lws as a background process, taking care of various things
3728 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3729 lws_daemonize(const char *_lock_path);
3731 * lws_get_library_version(): return string describing the version of lws
3733 * On unix, also includes the git describe
3735 LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
3736 lws_get_library_version(void);
3739 * lws_wsi_user() - get the user data associated with the connection
3740 * \param wsi: lws connection
3742 * Not normally needed since it's passed into the callback
3744 LWS_VISIBLE LWS_EXTERN void *
3745 lws_wsi_user(struct lws *wsi);
3748 * lws_parse_uri: cut up prot:/ads:port/path into pieces
3749 * Notice it does so by dropping '\0' into input string
3750 * and the leading / on the path is consequently lost
3752 * \param p: incoming uri string.. will get written to
3753 * \param prot: result pointer for protocol part (https://)
3754 * \param ads: result pointer for address part
3755 * \param port: result pointer for port part
3756 * \param path: result pointer for path part
3758 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3759 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
3763 * lws_now_secs(): return seconds since 1970-1-1
3765 LWS_VISIBLE LWS_EXTERN unsigned long
3769 * lws_get_context - Allow geting lws_context from a Websocket connection
3772 * With this function, users can access context in the callback function.
3773 * Otherwise users may have to declare context as a global variable.
3775 * \param wsi: Websocket connection instance
3777 LWS_VISIBLE LWS_EXTERN struct lws_context * LWS_WARN_UNUSED_RESULT
3778 lws_get_context(const struct lws *wsi);
3781 * lws_get_count_threads(): how many service threads the context uses
3783 * \param context: the lws context
3785 * By default this is always 1, if you asked for more than lws can handle it
3786 * will clip the number of threads. So you can use this to find out how many
3787 * threads are actually in use.
3789 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3790 lws_get_count_threads(struct lws_context *context);
3793 * lws_get_parent() - get parent wsi or NULL
3794 * \param wsi: lws connection
3796 * Specialized wsi like cgi stdin/out/err are associated to a parent wsi,
3797 * this allows you to get their parent.
3799 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
3800 lws_get_parent(const struct lws *wsi);
3803 * lws_get_child() - get child wsi or NULL
3804 * \param wsi: lws connection
3806 * Allows you to find a related wsi from the parent wsi.
3808 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
3809 lws_get_child(const struct lws *wsi);
3813 * \deprecated DEPRECATED Note: this is not normally needed as a user api.
3814 * It's provided in case it is
3815 * useful when integrating with other app poll loop service code.
3817 LWS_VISIBLE LWS_EXTERN int
3818 lws_read(struct lws *wsi, unsigned char *buf, size_t len);
3821 * lws_set_allocator() - custom allocator support
3825 * Allows you to replace the allocator (and deallocator) used by lws
3827 LWS_VISIBLE LWS_EXTERN void
3828 lws_set_allocator(void *(*realloc)(void *ptr, size_t size));
3831 /** \defgroup wsstatus Websocket status APIs
3832 * ##Websocket connection status APIs
3834 * These provide information about ws connection or message status
3838 * lws_send_pipe_choked() - tests if socket is writable or not
3839 * \param wsi: lws connection
3841 * Allows you to check if you can write more on the socket
3843 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3844 lws_send_pipe_choked(struct lws *wsi);
3847 * lws_is_final_fragment() - tests if last part of ws message
3848 * \param wsi: lws connection
3850 LWS_VISIBLE LWS_EXTERN int
3851 lws_is_final_fragment(struct lws *wsi);
3854 * lws_get_reserved_bits() - access reserved bits of ws frame
3855 * \param wsi: lws connection
3857 LWS_VISIBLE LWS_EXTERN unsigned char
3858 lws_get_reserved_bits(struct lws *wsi);
3861 * lws_partial_buffered() - find out if lws buffered the last write
3862 * \param wsi: websocket connection to check
3864 * Returns 1 if you cannot use lws_write because the last
3865 * write on this connection is still buffered, and can't be cleared without
3866 * returning to the service loop and waiting for the connection to be
3869 * If you will try to do >1 lws_write call inside a single
3870 * WRITEABLE callback, you must check this after every write and bail if
3871 * set, ask for a new writeable callback and continue writing from there.
3873 * This is never set at the start of a writeable callback, but any write
3876 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3877 lws_partial_buffered(struct lws *wsi);
3880 * lws_frame_is_binary(): true if the current frame was sent in binary mode
3882 * \param wsi: the connection we are inquiring about
3884 * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
3885 * it's interested to see if the frame it's dealing with was sent in binary
3888 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3889 lws_frame_is_binary(struct lws *wsi);
3892 * lws_is_ssl() - Find out if connection is using SSL
3893 * \param wsi: websocket connection to check
3895 * Returns 0 if the connection is not using SSL, 1 if using SSL and
3896 * using verified cert, and 2 if using SSL but the cert was not
3897 * checked (appears for client wsi told to skip check on connection)
3899 LWS_VISIBLE LWS_EXTERN int
3900 lws_is_ssl(struct lws *wsi);
3902 * lws_is_cgi() - find out if this wsi is running a cgi process
3903 * \param wsi: lws connection
3905 LWS_VISIBLE LWS_EXTERN int
3906 lws_is_cgi(struct lws *wsi);
3910 /** \defgroup sha SHA and B64 helpers
3911 * ##SHA and B64 helpers
3913 * These provide SHA-1 and B64 helper apis
3916 #ifdef LWS_SHA1_USE_OPENSSL_NAME
3917 #define lws_SHA1 SHA1
3920 * lws_SHA1(): make a SHA-1 digest of a buffer
3922 * \param d: incoming buffer
3923 * \param n: length of incoming buffer
3924 * \param md: buffer for message digest (must be >= 20 bytes)
3926 * Reduces any size buffer into a 20-byte SHA-1 hash.
3928 LWS_VISIBLE LWS_EXTERN unsigned char *
3929 lws_SHA1(const unsigned char *d, size_t n, unsigned char *md);
3932 * lws_b64_encode_string(): encode a string into base 64
3934 * \param in: incoming buffer
3935 * \param in_len: length of incoming buffer
3936 * \param out: result buffer
3937 * \param out_size: length of result buffer
3939 * Encodes a string using b64
3941 LWS_VISIBLE LWS_EXTERN int
3942 lws_b64_encode_string(const char *in, int in_len, char *out, int out_size);
3944 * lws_b64_decode_string(): decode a string from base 64
3946 * \param in: incoming buffer
3947 * \param out: result buffer
3948 * \param out_size: length of result buffer
3950 * Decodes a string using b64
3952 LWS_VISIBLE LWS_EXTERN int
3953 lws_b64_decode_string(const char *in, char *out, int out_size);
3957 /*! \defgroup cgi cgi handling
3961 * These functions allow low-level control over stdin/out/err of the cgi.
3963 * However for most cases, binding the cgi to http in and out, the default
3964 * lws implementation already does the right thing.
3967 enum lws_enum_stdinouterr {
3973 enum lws_cgi_hdr_state {
3983 struct lws_cgi_args {
3984 struct lws **stdwsi; /**< get fd with lws_get_socket_fd() */
3985 enum lws_enum_stdinouterr ch; /**< channel index */
3986 unsigned char *data; /**< for messages with payload */
3987 enum lws_cgi_hdr_state hdr_state; /**< track where we are in cgi headers */
3988 int len; /**< length */
3993 * lws_cgi: spawn network-connected cgi process
3995 * \param wsi: connection to own the process
3996 * \param exec_array: array of "exec-name" "arg1" ... "argn" NULL
3997 * \param script_uri_path_len: how many chars on the left of the uri are the path to the cgi
3998 * \param timeout_secs: seconds script should be allowed to run
3999 * \param mp_cgienv: pvo list with per-vhost cgi options to put in env
4001 LWS_VISIBLE LWS_EXTERN int
4002 lws_cgi(struct lws *wsi, const char * const *exec_array,
4003 int script_uri_path_len, int timeout_secs,
4004 const struct lws_protocol_vhost_options *mp_cgienv);
4007 * lws_cgi_write_split_stdout_headers: write cgi output accounting for header part
4009 * \param wsi: connection to own the process
4011 LWS_VISIBLE LWS_EXTERN int
4012 lws_cgi_write_split_stdout_headers(struct lws *wsi);
4015 * lws_cgi_kill: terminate cgi process associated with wsi
4017 * \param wsi: connection to own the process
4019 LWS_VISIBLE LWS_EXTERN int
4020 lws_cgi_kill(struct lws *wsi);
4025 /*! \defgroup fops file operation wrapping
4027 * ##File operation wrapping
4029 * Use these helper functions if you want to access a file from the perspective
4030 * of a specific wsi, which is usually the case. If you just want contextless
4031 * file access, use the fops callbacks directly with NULL wsi instead of these
4034 * If so, then it calls the platform handler or user overrides where present
4035 * (as defined in info->fops)
4037 * The advantage from all this is user code can be portable for file operations
4038 * without having to deal with differences between platforms.
4042 /** struct lws_plat_file_ops - Platform-specific file operations
4044 * These provide platform-agnostic ways to deal with filesystem access in the
4045 * library and in the user code.
4047 struct lws_plat_file_ops {
4048 lws_filefd_type (*open)(struct lws *wsi, const char *filename,
4049 unsigned long *filelen, int flags);
4050 /**< Open file (always binary access if plat supports it)
4051 * filelen is filled on exit to be the length of the file
4052 * flags should be set to O_RDONLY or O_RDWR */
4053 int (*close)(struct lws *wsi, lws_filefd_type fd);
4055 unsigned long (*seek_cur)(struct lws *wsi, lws_filefd_type fd,
4056 long offset_from_cur_pos);
4057 /**< seek from current position */
4058 int (*read)(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
4059 unsigned char *buf, unsigned long len);
4060 /**< Read from file, on exit *amount is set to amount actually read */
4061 int (*write)(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
4062 unsigned char *buf, unsigned long len);
4063 /**< Write to file, on exit *amount is set to amount actually written */
4065 /* Add new things just above here ---^
4066 * This is part of the ABI, don't needlessly break compatibility */
4070 * lws_get_fops() - get current file ops
4072 * \param context: context
4074 LWS_VISIBLE LWS_EXTERN struct lws_plat_file_ops * LWS_WARN_UNUSED_RESULT
4075 lws_get_fops(struct lws_context *context);
4078 * lws_plat_file_open() - file open operations
4080 * \param wsi: connection doing the opening
4081 * \param filename: filename to open
4082 * \param filelen: length of file (filled in by call)
4083 * \param flags: open flags
4085 static LWS_INLINE lws_filefd_type LWS_WARN_UNUSED_RESULT
4086 lws_plat_file_open(struct lws *wsi, const char *filename,
4087 unsigned long *filelen, int flags)
4089 return lws_get_fops(lws_get_context(wsi))->open(wsi, filename,
4094 * lws_plat_file_close() - close file
4096 * \param wsi: connection opened by
4097 * \param fd: file descriptor
4099 static LWS_INLINE int
4100 lws_plat_file_close(struct lws *wsi, lws_filefd_type fd)
4102 return lws_get_fops(lws_get_context(wsi))->close(wsi, fd);
4106 * lws_plat_file_seek_cur() - close file
4108 * \param wsi: connection opened by
4109 * \param fd: file descriptor
4110 * \param offset: position to seek to
4112 static LWS_INLINE unsigned long
4113 lws_plat_file_seek_cur(struct lws *wsi, lws_filefd_type fd, long offset)
4115 return lws_get_fops(lws_get_context(wsi))->seek_cur(wsi, fd, offset);
4118 * lws_plat_file_read() - read from file
4120 * \param wsi: connection opened by
4121 * \param fd: file descriptor
4122 * \param amount: how much to read (rewritten by call)
4123 * \param buf: buffer to write to
4124 * \param len: max length
4126 static LWS_INLINE int LWS_WARN_UNUSED_RESULT
4127 lws_plat_file_read(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
4128 unsigned char *buf, unsigned long len)
4130 return lws_get_fops(lws_get_context(wsi))->read(wsi, fd, amount, buf,
4134 * lws_plat_file_write() - write from file
4136 * \param wsi: connection opened by
4137 * \param fd: file descriptor
4138 * \param amount: how much to write (rewritten by call)
4139 * \param buf: buffer to read from
4140 * \param len: max length
4142 static LWS_INLINE int LWS_WARN_UNUSED_RESULT
4143 lws_plat_file_write(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
4144 unsigned char *buf, unsigned long len)
4146 return lws_get_fops(lws_get_context(wsi))->write(wsi, fd, amount, buf,
4153 * ##SMTP related functions
4155 * These apis let you communicate with a local SMTP server to send email from
4156 * lws. It handles all the SMTP sequencing and protocol actions.
4158 * Your system should have postfix, sendmail or another MTA listening on port
4159 * 25 and able to send email using the "mail" commandline app. Usually distro
4160 * MTAs are configured for this by default.
4162 * It runs via its own libuv events if initialized (which requires giving it
4163 * a libuv loop to attach to).
4165 * It operates using three callbacks, on_next() queries if there is a new email
4166 * to send, on_get_body() asks for the body of the email, and on_sent() is
4167 * called after the email is successfully sent.
4171 * - create an lws_email struct
4173 * - initialize data, loop, the email_* strings, max_content_size and
4176 * - call lws_email_init()
4178 * When you have at least one email to send, call lws_email_check() to
4179 * schedule starting to send it.
4182 #ifdef LWS_WITH_SMTP
4184 /** enum lwsgs_smtp_states - where we are in SMTP protocol sequence */
4185 enum lwsgs_smtp_states {
4186 LGSSMTP_IDLE, /**< awaiting new email */
4187 LGSSMTP_CONNECTING, /**< opening tcp connection to MTA */
4188 LGSSMTP_CONNECTED, /**< tcp connection to MTA is connected */
4189 LGSSMTP_SENT_HELO, /**< sent the HELO */
4190 LGSSMTP_SENT_FROM, /**< sent FROM */
4191 LGSSMTP_SENT_TO, /**< sent TO */
4192 LGSSMTP_SENT_DATA, /**< sent DATA request */
4193 LGSSMTP_SENT_BODY, /**< sent the email body */
4194 LGSSMTP_SENT_QUIT, /**< sent the session quit */
4197 /** struct lws_email - abstract context for performing SMTP operations */
4200 /**< opaque pointer set by user code and available to the callbacks */
4202 /**< the libuv loop we will work on */
4204 char email_smtp_ip[32]; /**< Fill before init, eg, "127.0.0.1" */
4205 char email_helo[32]; /**< Fill before init, eg, "myserver.com" */
4206 char email_from[100]; /**< Fill before init or on_next */
4207 char email_to[100]; /**< Fill before init or on_next */
4209 unsigned int max_content_size;
4210 /**< largest possible email body size */
4212 /* Fill all the callbacks before init */
4214 int (*on_next)(struct lws_email *email);
4215 /**< (Fill in before calling lws_email_init)
4216 * called when idle, 0 = another email to send, nonzero is idle.
4217 * If you return 0, all of the email_* char arrays must be set
4218 * to something useful. */
4219 int (*on_sent)(struct lws_email *email);
4220 /**< (Fill in before calling lws_email_init)
4221 * called when transfer of the email to the SMTP server was
4222 * successful, your callback would remove the current email
4224 int (*on_get_body)(struct lws_email *email, char *buf, int len);
4225 /**< (Fill in before calling lws_email_init)
4226 * called when the body part of the queued email is about to be
4227 * sent to the SMTP server. */
4230 /* private things */
4231 uv_timer_t timeout_email; /**< private */
4232 enum lwsgs_smtp_states estate; /**< private */
4233 uv_connect_t email_connect_req; /**< private */
4234 uv_tcp_t email_client; /**< private */
4235 time_t email_connect_started; /**< private */
4236 char email_buf[256]; /**< private */
4237 char *content; /**< private */
4241 * lws_email_init() - Initialize a struct lws_email
4243 * \param email: struct lws_email to init
4244 * \param loop: libuv loop to use
4245 * \param max_content: max email content size
4247 * Prepares a struct lws_email for use ending SMTP
4249 LWS_VISIBLE LWS_EXTERN int
4250 lws_email_init(struct lws_email *email, uv_loop_t *loop, int max_content);
4253 * lws_email_check() - Request check for new email
4255 * \param email: struct lws_email context to check
4257 * Schedules a check for new emails in 1s... call this when you have queued an
4260 LWS_VISIBLE LWS_EXTERN void
4261 lws_email_check(struct lws_email *email);
4263 * lws_email_destroy() - stop using the struct lws_email
4265 * \param email: the struct lws_email context
4267 * Stop sending email using email and free allocations
4269 LWS_VISIBLE LWS_EXTERN void
4270 lws_email_destroy(struct lws_email *email);