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"
1719 /* Add new things just above here ---^
1720 * This is part of the ABI, don't needlessly break compatibility
1722 * The below is to ensure later library versions with new
1723 * members added above will see 0 (default) even if the app
1724 * was not built against the newer headers.
1727 void *_unused[8]; /**< dummy */
1731 * lws_create_context() - Create the websocket handler
1732 * \param info: pointer to struct with parameters
1734 * This function creates the listening socket (if serving) and takes care
1735 * of all initialization in one step.
1737 * If option LWS_SERVER_OPTION_EXPLICIT_VHOSTS is given, no vhost is
1738 * created; you're expected to create your own vhosts afterwards using
1739 * lws_create_vhost(). Otherwise a vhost named "default" is also created
1740 * using the information in the vhost-related members, for compatibility.
1742 * After initialization, it returns a struct lws_context * that
1743 * represents this server. After calling, user code needs to take care
1744 * of calling lws_service() with the context pointer to get the
1745 * server's sockets serviced. This must be done in the same process
1746 * context as the initialization call.
1748 * The protocol callback functions are called for a handful of events
1749 * including http requests coming in, websocket connections becoming
1750 * established, and data arriving; it's also called periodically to allow
1751 * async transmission.
1753 * HTTP requests are sent always to the FIRST protocol in protocol, since
1754 * at that time websocket protocol has not been negotiated. Other
1755 * protocols after the first one never see any HTTP callback activity.
1757 * The server created is a simple http server by default; part of the
1758 * websocket standard is upgrading this http connection to a websocket one.
1760 * This allows the same server to provide files like scripts and favicon /
1761 * images or whatever over http and dynamic data over websockets all in
1762 * one place; they're all handled in the user callback.
1764 LWS_VISIBLE LWS_EXTERN struct lws_context *
1765 lws_create_context(struct lws_context_creation_info *info);
1768 * lws_context_destroy() - Destroy the websocket context
1769 * \param context: Websocket context
1771 * This function closes any active connections and then frees the
1772 * context. After calling this, any further use of the context is
1775 LWS_VISIBLE LWS_EXTERN void
1776 lws_context_destroy(struct lws_context *context);
1779 * lws_set_proxy() - Setups proxy to lws_context.
1780 * \param vhost: pointer to struct lws_vhost you want set proxy for
1781 * \param proxy: pointer to c string containing proxy in format address:port
1783 * Returns 0 if proxy string was parsed and proxy was setup.
1784 * Returns -1 if proxy is NULL or has incorrect format.
1786 * This is only required if your OS does not provide the http_proxy
1787 * environment variable (eg, OSX)
1789 * IMPORTANT! You should call this function right after creation of the
1790 * lws_context and before call to connect. If you call this
1791 * function after connect behavior is undefined.
1792 * This function will override proxy settings made on lws_context
1793 * creation with genenv() call.
1795 LWS_VISIBLE LWS_EXTERN int
1796 lws_set_proxy(struct lws_vhost *vhost, const char *proxy);
1802 * lws_create_vhost() - Create a vhost (virtual server context)
1803 * \param context: pointer to result of lws_create_context()
1804 * \param info: pointer to struct with parameters
1806 * This function creates a virtual server (vhost) using the vhost-related
1807 * members of the info struct. You can create many vhosts inside one context
1808 * if you created the context with the option LWS_SERVER_OPTION_EXPLICIT_VHOSTS
1810 LWS_EXTERN LWS_VISIBLE struct lws_vhost *
1811 lws_create_vhost(struct lws_context *context,
1812 struct lws_context_creation_info *info);
1815 * lwsws_get_config_globals() - Parse a JSON server config file
1816 * \param info: pointer to struct with parameters
1817 * \param d: filepath of the config file
1818 * \param config_strings: storage for the config strings extracted from JSON,
1819 * the pointer is incremented as strings are stored
1820 * \param len: pointer to the remaining length left in config_strings
1821 * the value is decremented as strings are stored
1823 * This function prepares a n lws_context_creation_info struct with global
1824 * settings from a file d.
1826 * Requires CMake option LWS_WITH_LEJP_CONF to have been enabled
1828 LWS_VISIBLE LWS_EXTERN int
1829 lwsws_get_config_globals(struct lws_context_creation_info *info, const char *d,
1830 char **config_strings, int *len);
1833 * lwsws_get_config_vhosts() - Create vhosts from a JSON server config file
1834 * \param context: pointer to result of lws_create_context()
1835 * \param info: pointer to struct with parameters
1836 * \param d: filepath of the config file
1837 * \param config_strings: storage for the config strings extracted from JSON,
1838 * the pointer is incremented as strings are stored
1839 * \param len: pointer to the remaining length left in config_strings
1840 * the value is decremented as strings are stored
1842 * This function creates vhosts into a context according to the settings in
1843 *JSON files found in directory d.
1845 * Requires CMake option LWS_WITH_LEJP_CONF to have been enabled
1847 LWS_VISIBLE LWS_EXTERN int
1848 lwsws_get_config_vhosts(struct lws_context *context,
1849 struct lws_context_creation_info *info, const char *d,
1850 char **config_strings, int *len);
1852 /** lws_vhost_get() - \deprecated deprecated: use lws_get_vhost() */
1853 LWS_VISIBLE LWS_EXTERN struct lws_vhost *
1854 lws_vhost_get(struct lws *wsi) LWS_WARN_DEPRECATED;
1857 * lws_get_vhost() - return the vhost a wsi belongs to
1859 * \param wsi: which connection
1861 LWS_VISIBLE LWS_EXTERN struct lws_vhost *
1862 lws_get_vhost(struct lws *wsi);
1865 * lws_json_dump_vhost() - describe vhost state and stats in JSON
1867 * \param vh: the vhost
1868 * \param buf: buffer to fill with JSON
1869 * \param len: max length of buf
1871 LWS_VISIBLE LWS_EXTERN int
1872 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len);
1875 * lws_json_dump_context() - describe context state and stats in JSON
1877 * \param context: the context
1878 * \param buf: buffer to fill with JSON
1879 * \param len: max length of buf
1881 LWS_VISIBLE LWS_EXTERN int
1882 lws_json_dump_context(const struct lws_context *context, char *buf, int len);
1885 * lws_context_user() - get the user data associated with the context
1886 * \param context: Websocket context
1888 * This returns the optional user allocation that can be attached to
1889 * the context the sockets live in at context_create time. It's a way
1890 * to let all sockets serviced in the same context share data without
1891 * using globals statics in the user code.
1893 LWS_VISIBLE LWS_EXTERN void *
1894 lws_context_user(struct lws_context *context);
1896 /*! \defgroup vhost-mounts Vhost mounts and options
1897 * \ingroup context-and-vhost-creation
1899 * ##Vhost mounts and options
1902 /** struct lws_protocol_vhost_options - linked list of per-vhost protocol
1903 * name=value options
1905 * This provides a general way to attach a linked-list of name=value pairs,
1906 * which can also have an optional child link-list using the options member.
1908 struct lws_protocol_vhost_options {
1909 const struct lws_protocol_vhost_options *next; /**< linked list */
1910 const struct lws_protocol_vhost_options *options; /**< child linked-list of more options for this node */
1911 const char *name; /**< name of name=value pair */
1912 const char *value; /**< value of name=value pair */
1915 /** enum lws_mount_protocols
1916 * This specifies the mount protocol for a mountpoint, whether it is to be
1917 * served from a filesystem, or it is a cgi etc.
1919 enum lws_mount_protocols {
1920 LWSMPRO_HTTP = 0, /**< not supported yet */
1921 LWSMPRO_HTTPS = 1, /**< not supported yet */
1922 LWSMPRO_FILE = 2, /**< serve from filesystem directory */
1923 LWSMPRO_CGI = 3, /**< pass to CGI to handle */
1924 LWSMPRO_REDIR_HTTP = 4, /**< redirect to http:// url */
1925 LWSMPRO_REDIR_HTTPS = 5, /**< redirect to https:// url */
1926 LWSMPRO_CALLBACK = 6, /**< hand by named protocol's callback */
1929 /** struct lws_http_mount
1931 * arguments for mounting something in a vhost's url namespace
1933 struct lws_http_mount {
1934 const struct lws_http_mount *mount_next;
1935 /**< pointer to next struct lws_http_mount */
1936 const char *mountpoint;
1937 /**< mountpoint in http pathspace, eg, "/" */
1939 /**< path to be mounted, eg, "/var/www/warmcat.com" */
1941 /**< default target, eg, "index.html" */
1942 const char *protocol;
1943 /**<"protocol-name" to handle mount */
1945 const struct lws_protocol_vhost_options *cgienv;
1946 /**< optional linked-list of cgi options. These are created
1947 * as environment variables for the cgi process
1949 const struct lws_protocol_vhost_options *extra_mimetypes;
1950 /**< optional linked-list of mimetype mappings */
1951 const struct lws_protocol_vhost_options *interpret;
1952 /**< optional linked-list of files to be interpreted */
1955 /**< seconds cgi is allowed to live, if cgi://mount type */
1957 /**< max-age for reuse of client cache of files, seconds */
1958 unsigned int auth_mask;
1959 /**< bits set here must be set for authorized client session */
1961 unsigned int cache_reusable:1; /**< set if client cache may reuse this */
1962 unsigned int cache_revalidate:1; /**< set if client cache should revalidate on use */
1963 unsigned int cache_intermediaries:1; /**< set if intermediaries are allowed to cache */
1965 unsigned char origin_protocol; /**< one of enum lws_mount_protocols */
1966 unsigned char mountpoint_len; /**< length of mountpoint string */
1971 /*! \defgroup client
1974 * ##Client releated functions
1978 /** enum lws_client_connect_ssl_connection_flags - flags that may be used
1979 * with struct lws_client_connect_info ssl_connection member to control if
1980 * and how SSL checks apply to the client connection being created
1983 enum lws_client_connect_ssl_connection_flags {
1984 LCCSCF_USE_SSL = (1 << 0),
1985 LCCSCF_ALLOW_SELFSIGNED = (1 << 1),
1986 LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK = (1 << 2),
1987 LCCSCF_ALLOW_EXPIRED = (1 << 3)
1990 /** struct lws_client_connect_info - parameters to connect with when using
1991 * lws_client_connect_via_info() */
1993 struct lws_client_connect_info {
1994 struct lws_context *context;
1995 /**< lws context to create connection in */
1996 const char *address;
1997 /**< remote address to connect to */
1999 /**< remote port to connect to */
2001 /**< nonzero for ssl */
2005 /**< content of host header */
2007 /**< content of origin header */
2008 const char *protocol;
2009 /**< list of ws protocols we could accept */
2010 int ietf_version_or_minus_one;
2011 /**< deprecated: currently leave at 0 or -1 */
2013 /**< if non-NULL, use this as wsi user_data instead of malloc it */
2014 const struct lws_extension *client_exts;
2015 /**< array of extensions that may be used on connection */
2017 /**< if non-NULL, do this http method instead of ws[s] upgrade.
2018 * use "GET" to be a simple http client connection */
2019 struct lws *parent_wsi;
2020 /**< if another wsi is responsible for this connection, give it here.
2021 * this is used to make sure if the parent closes so do any
2022 * child connections first. */
2023 const char *uri_replace_from;
2024 /**< if non-NULL, when this string is found in URIs in
2025 * text/html content-encoding, it's replaced with uri_replace_to */
2026 const char *uri_replace_to;
2027 /**< see uri_replace_from */
2028 struct lws_vhost *vhost;
2029 /**< vhost to bind to (used to determine related SSL_CTX) */
2031 /**< if not NULL, store the new wsi here early in the connection
2032 * process. Although we return the new wsi, the call to create the
2033 * client connection does progress the connection somewhat and may
2034 * meet an error that will result in the connection being scrubbed and
2035 * NULL returned. While the wsi exists though, he may process a
2036 * callback like CLIENT_CONNECTION_ERROR with his wsi: this gives the
2037 * user callback a way to identify which wsi it is that faced the error
2038 * even before the new wsi is returned and even if ultimately no wsi
2042 /* Add new things just above here ---^
2043 * This is part of the ABI, don't needlessly break compatibility
2045 * The below is to ensure later library versions with new
2046 * members added above will see 0 (default) even if the app
2047 * was not built against the newer headers.
2050 void *_unused[4]; /**< dummy */
2054 * lws_client_connect_via_info() - Connect to another websocket server
2055 * \param ccinfo: pointer to lws_client_connect_info struct
2057 * This function creates a connection to a remote server using the
2058 * information provided in ccinfo.
2060 LWS_VISIBLE LWS_EXTERN struct lws *
2061 lws_client_connect_via_info(struct lws_client_connect_info * ccinfo);
2064 * lws_client_connect() - Connect to another websocket server
2065 * \deprecated DEPRECATED use lws_client_connect_via_info
2066 * \param clients: Websocket context
2067 * \param address: Remote server address, eg, "myserver.com"
2068 * \param port: Port to connect to on the remote server, eg, 80
2069 * \param ssl_connection: 0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
2071 * \param path: Websocket path on server
2072 * \param host: Hostname on server
2073 * \param origin: Socket origin name
2074 * \param protocol: Comma-separated list of protocols being asked for from
2075 * the server, or just one. The server will pick the one it
2076 * likes best. If you don't want to specify a protocol, which is
2077 * legal, use NULL here.
2078 * \param ietf_version_or_minus_one: -1 to ask to connect using the default, latest
2079 * protocol supported, or the specific protocol ordinal
2081 * This function creates a connection to a remote server
2083 /* deprecated, use lws_client_connect_via_info() */
2084 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
2085 lws_client_connect(struct lws_context *clients, const char *address,
2086 int port, int ssl_connection, const char *path,
2087 const char *host, const char *origin, const char *protocol,
2088 int ietf_version_or_minus_one) LWS_WARN_DEPRECATED;
2089 /* deprecated, use lws_client_connect_via_info() */
2091 * lws_client_connect_extended() - Connect to another websocket server
2092 * \deprecated DEPRECATED use lws_client_connect_via_info
2093 * \param clients: Websocket context
2094 * \param address: Remote server address, eg, "myserver.com"
2095 * \param port: Port to connect to on the remote server, eg, 80
2096 * \param ssl_connection: 0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
2098 * \param path: Websocket path on server
2099 * \param host: Hostname on server
2100 * \param origin: Socket origin name
2101 * \param protocol: Comma-separated list of protocols being asked for from
2102 * the server, or just one. The server will pick the one it
2104 * \param ietf_version_or_minus_one: -1 to ask to connect using the default, latest
2105 * protocol supported, or the specific protocol ordinal
2106 * \param userdata: Pre-allocated user data
2108 * This function creates a connection to a remote server
2110 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
2111 lws_client_connect_extended(struct lws_context *clients, const char *address,
2112 int port, int ssl_connection, const char *path,
2113 const char *host, const char *origin,
2114 const char *protocol, int ietf_version_or_minus_one,
2115 void *userdata) LWS_WARN_DEPRECATED;
2118 * lws_init_vhost_client_ssl() - also enable client SSL on an existing vhost
2120 * \param info: client ssl related info
2121 * \param vhost: which vhost to initialize client ssl operations on
2123 * You only need to call this if you plan on using SSL client connections on
2124 * the vhost. For non-SSL client connections, it's not necessary to call this.
2126 * The following members of info are used during the call
2128 * - options must have LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT set,
2129 * otherwise the call does nothing
2130 * - provided_client_ssl_ctx must be NULL to get a generated client
2131 * ssl context, otherwise you can pass a prepared one in by setting it
2132 * - ssl_cipher_list may be NULL or set to the client valid cipher list
2133 * - ssl_ca_filepath may be NULL or client cert filepath
2134 * - ssl_cert_filepath may be NULL or client cert filepath
2135 * - ssl_private_key_filepath may be NULL or client cert private key
2137 * You must create your vhost explicitly if you want to use this, so you have
2138 * a pointer to the vhost. Create the context first with the option flag
2139 * LWS_SERVER_OPTION_EXPLICIT_VHOSTS and then call lws_create_vhost() with
2140 * the same info struct.
2142 LWS_VISIBLE LWS_EXTERN int
2143 lws_init_vhost_client_ssl(const struct lws_context_creation_info *info,
2144 struct lws_vhost *vhost);
2146 LWS_VISIBLE LWS_EXTERN int
2147 lws_http_client_read(struct lws *wsi, char **buf, int *len);
2150 * lws_http_client_http_response() - get last HTTP response code
2152 * \param wsi: client connection
2154 * Returns the last server response code, eg, 200 for client http connections.
2156 LWS_VISIBLE LWS_EXTERN unsigned int
2157 lws_http_client_http_response(struct lws *wsi);
2159 LWS_VISIBLE LWS_EXTERN void
2160 lws_client_http_body_pending(struct lws *wsi, int something_left_to_send);
2163 * lws_client_http_body_pending() - control if client connection neeeds to send body
2165 * \param wsi: client connection
2166 * \param something_left_to_send: nonzero if need to send more body, 0 (default)
2167 * if nothing more to send
2169 * If you will send payload data with your HTTP client connection, eg, for POST,
2170 * when you set the related http headers in
2171 * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER callback you should also call
2172 * this API with something_left_to_send nonzero, and call
2173 * lws_callback_on_writable(wsi);
2175 * After sending the headers, lws will call your callback with
2176 * LWS_CALLBACK_CLIENT_HTTP_WRITEABLE reason when writable. You can send the
2177 * next part of the http body payload, calling lws_callback_on_writable(wsi);
2178 * if there is more to come, or lws_client_http_body_pending(wsi, 0); to
2179 * let lws know the last part is sent and the connection can move on.
2184 /** \defgroup service Built-in service loop entry
2186 * ##Built-in service loop entry
2188 * If you're not using libev / libuv, these apis are needed to enter the poll()
2189 * wait in lws and service any connections with pending events.
2194 * lws_service() - Service any pending websocket activity
2195 * \param context: Websocket context
2196 * \param timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
2197 * service otherwise block and service immediately, returning
2198 * after the timeout if nothing needed service.
2200 * This function deals with any pending websocket traffic, for three
2201 * kinds of event. It handles these events on both server and client
2202 * types of connection the same.
2204 * 1) Accept new connections to our context's server
2206 * 2) Call the receive callback for incoming frame data received by
2207 * server or client connections.
2209 * You need to call this service function periodically to all the above
2210 * functions to happen; if your application is single-threaded you can
2211 * just call it in your main event loop.
2213 * Alternatively you can fork a new process that asynchronously handles
2214 * calling this service in a loop. In that case you are happy if this
2215 * call blocks your thread until it needs to take care of something and
2216 * would call it with a large nonzero timeout. Your loop then takes no
2217 * CPU while there is nothing happening.
2219 * If you are calling it in a single-threaded app, you don't want it to
2220 * wait around blocking other things in your loop from happening, so you
2221 * would call it with a timeout_ms of 0, so it returns immediately if
2222 * nothing is pending, or as soon as it services whatever was pending.
2224 LWS_VISIBLE LWS_EXTERN int
2225 lws_service(struct lws_context *context, int timeout_ms);
2228 * lws_service() - Service any pending websocket activity
2230 * \param context: Websocket context
2231 * \param timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
2232 * service otherwise block and service immediately, returning
2233 * after the timeout if nothing needed service.
2235 * Same as lws_service(), but for a specific thread service index. Only needed
2236 * if you are spawning multiple service threads.
2238 LWS_VISIBLE LWS_EXTERN int
2239 lws_service_tsi(struct lws_context *context, int timeout_ms, int tsi);
2242 * lws_cancel_service_pt() - Cancel servicing of pending socket activity
2244 * \param wsi: Cancel service on the thread this wsi is serviced by
2246 * This function lets a call to lws_service() waiting for a timeout
2247 * immediately return.
2249 * It works by creating a phony event and then swallowing it silently.
2251 * The reason it may be needed is when waiting in poll(), changes to
2252 * the event masks are ignored by the OS until poll() is reentered. This
2253 * lets you halt the poll() wait and make the reentry happen immediately
2254 * instead of having the wait out the rest of the poll timeout.
2256 LWS_VISIBLE LWS_EXTERN void
2257 lws_cancel_service_pt(struct lws *wsi);
2260 * lws_cancel_service() - Cancel wait for new pending socket activity
2261 * \param context: Websocket context
2263 * This function let a call to lws_service() waiting for a timeout
2264 * immediately return.
2266 * What it basically does is provide a fake event that will be swallowed,
2267 * so the wait in poll() is ended. That's useful because poll() doesn't
2268 * attend to changes in POLLIN/OUT/ERR until it re-enters the wait.
2270 LWS_VISIBLE LWS_EXTERN void
2271 lws_cancel_service(struct lws_context *context);
2274 * lws_service_fd() - Service polled socket with something waiting
2275 * \param context: Websocket context
2276 * \param pollfd: The pollfd entry describing the socket fd and which events
2277 * happened, or NULL to tell lws to do only timeout servicing.
2279 * This function takes a pollfd that has POLLIN or POLLOUT activity and
2280 * services it according to the state of the associated
2283 * The one call deals with all "service" that might happen on a socket
2284 * including listen accepts, http files as well as websocket protocol.
2286 * If a pollfd says it has something, you can just pass it to
2287 * lws_service_fd() whether it is a socket handled by lws or not.
2288 * If it sees it is a lws socket, the traffic will be handled and
2289 * pollfd->revents will be zeroed now.
2291 * If the socket is foreign to lws, it leaves revents alone. So you can
2292 * see if you should service yourself by checking the pollfd revents
2293 * after letting lws try to service it.
2295 * You should also call this with pollfd = NULL to just allow the
2296 * once-per-second global timeout checks; if less than a second since the last
2297 * check it returns immediately then.
2299 LWS_VISIBLE LWS_EXTERN int
2300 lws_service_fd(struct lws_context *context, struct lws_pollfd *pollfd);
2303 * lws_service_fd_tsi() - Service polled socket in specific service thread
2304 * \param context: Websocket context
2305 * \param pollfd: The pollfd entry describing the socket fd and which events
2307 * \param tsi: thread service index
2309 * Same as lws_service_fd() but used with multiple service threads
2311 LWS_VISIBLE LWS_EXTERN int
2312 lws_service_fd_tsi(struct lws_context *context, struct lws_pollfd *pollfd,
2316 * lws_service_adjust_timeout() - Check for any connection needing forced service
2317 * \param context: Websocket context
2318 * \param timeout_ms: The original poll timeout value. You can just set this
2319 * to 1 if you don't really have a poll timeout.
2320 * \param tsi: thread service index
2322 * Under some conditions connections may need service even though there is no
2323 * pending network action on them, this is "forced service". For default
2324 * poll() and libuv / libev, the library takes care of calling this and
2325 * dealing with it for you. But for external poll() integration, you need
2326 * access to the apis.
2328 * If anybody needs "forced service", returned timeout is zero. In that case,
2329 * you can call lws_service_tsi() with a timeout of -1 to only service
2330 * guys who need forced service.
2332 LWS_VISIBLE LWS_EXTERN int
2333 lws_service_adjust_timeout(struct lws_context *context, int timeout_ms, int tsi);
2335 /* Backwards compatibility */
2336 #define lws_plat_service_tsi lws_service_tsi
2340 /*! \defgroup http HTTP
2342 Modules related to handling HTTP
2346 /*! \defgroup httpft HTTP File transfer
2349 APIs for sending local files in response to HTTP requests
2354 * lws_get_mimetype() - Determine mimetype to use from filename
2356 * \param file: filename
2357 * \param m: NULL, or mount context
2359 * This uses a canned list of known filetypes first, if no match and m is
2360 * non-NULL, then tries a list of per-mount file suffix to mimtype mappings.
2362 * Returns either NULL or a pointer to the mimetype matching the file.
2364 LWS_VISIBLE LWS_EXTERN const char *
2365 lws_get_mimetype(const char *file, const struct lws_http_mount *m);
2368 * lws_serve_http_file() - Send a file back to the client using http
2369 * \param wsi: Websocket instance (available from user callback)
2370 * \param file: The file to issue over http
2371 * \param content_type: The http content type, eg, text/html
2372 * \param other_headers: NULL or pointer to header string
2373 * \param other_headers_len: length of the other headers if non-NULL
2375 * This function is intended to be called from the callback in response
2376 * to http requests from the client. It allows the callback to issue
2377 * local files down the http link in a single step.
2379 * Returning <0 indicates error and the wsi should be closed. Returning
2380 * >0 indicates the file was completely sent and
2381 * lws_http_transaction_completed() called on the wsi (and close if != 0)
2382 * ==0 indicates the file transfer is started and needs more service later,
2383 * the wsi should be left alone.
2385 LWS_VISIBLE LWS_EXTERN int
2386 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
2387 const char *other_headers, int other_headers_len);
2388 LWS_VISIBLE LWS_EXTERN int
2389 lws_serve_http_file_fragment(struct lws *wsi);
2392 /*! \defgroup html-chunked-substitution HTML Chunked Substitution
2395 * ##HTML chunked Substitution
2397 * APIs for receiving chunks of text, replacing a set of variable names via
2398 * a callback, and then prepending and appending HTML chunked encoding
2404 HTTP_STATUS_OK = 200,
2405 HTTP_STATUS_NO_CONTENT = 204,
2407 HTTP_STATUS_MOVED_PERMANENTLY = 301,
2408 HTTP_STATUS_FOUND = 302,
2409 HTTP_STATUS_SEE_OTHER = 303,
2411 HTTP_STATUS_BAD_REQUEST = 400,
2412 HTTP_STATUS_UNAUTHORIZED,
2413 HTTP_STATUS_PAYMENT_REQUIRED,
2414 HTTP_STATUS_FORBIDDEN,
2415 HTTP_STATUS_NOT_FOUND,
2416 HTTP_STATUS_METHOD_NOT_ALLOWED,
2417 HTTP_STATUS_NOT_ACCEPTABLE,
2418 HTTP_STATUS_PROXY_AUTH_REQUIRED,
2419 HTTP_STATUS_REQUEST_TIMEOUT,
2420 HTTP_STATUS_CONFLICT,
2422 HTTP_STATUS_LENGTH_REQUIRED,
2423 HTTP_STATUS_PRECONDITION_FAILED,
2424 HTTP_STATUS_REQ_ENTITY_TOO_LARGE,
2425 HTTP_STATUS_REQ_URI_TOO_LONG,
2426 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE,
2427 HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE,
2428 HTTP_STATUS_EXPECTATION_FAILED,
2430 HTTP_STATUS_INTERNAL_SERVER_ERROR = 500,
2431 HTTP_STATUS_NOT_IMPLEMENTED,
2432 HTTP_STATUS_BAD_GATEWAY,
2433 HTTP_STATUS_SERVICE_UNAVAILABLE,
2434 HTTP_STATUS_GATEWAY_TIMEOUT,
2435 HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED,
2438 struct lws_process_html_args {
2439 char *p; /**< pointer to the buffer containing the data */
2440 int len; /**< length of the original data at p */
2441 int max_len; /**< maximum length we can grow the data to */
2442 int final; /**< set if this is the last chunk of the file */
2445 typedef const char *(*lws_process_html_state_cb)(void *data, int index);
2447 struct lws_process_html_state {
2448 char *start; /**< pointer to start of match */
2449 char swallow[16]; /**< matched character buffer */
2450 int pos; /**< position in match */
2451 void *data; /**< opaque pointer */
2452 const char * const *vars; /**< list of variable names */
2453 int count_vars; /**< count of variable names */
2455 lws_process_html_state_cb replace; /**< called on match to perform substitution */
2458 /*! lws_chunked_html_process() - generic chunked substitution
2459 * \param args: buffer to process using chunked encoding
2460 * \param s: current processing state
2462 LWS_VISIBLE LWS_EXTERN int
2463 lws_chunked_html_process(struct lws_process_html_args *args,
2464 struct lws_process_html_state *s);
2467 /** \defgroup HTTP-headers-read HTTP headers: read
2470 * ##HTTP header releated functions
2472 * In lws the client http headers are temporarily stored in a pool, only for the
2473 * duration of the http part of the handshake. It's because in most cases,
2474 * the header content is ignored for the whole rest of the connection lifetime
2475 * and would then just be taking up space needlessly.
2477 * During LWS_CALLBACK_HTTP when the URI path is delivered is the last time
2478 * the http headers are still allocated, you can use these apis then to
2479 * look at and copy out interesting header content (cookies, etc)
2481 * Notice that the header total length reported does not include a terminating
2482 * '\0', however you must allocate for it when using the _copy apis. So the
2483 * length reported for a header containing "123" is 3, but you must provide
2484 * a buffer of length 4 so that "123\0" may be copied into it, or the copy
2485 * will fail with a nonzero return code.
2487 * In the special case of URL arguments, like ?x=1&y=2, the arguments are
2488 * stored in a token named for the method, eg, WSI_TOKEN_GET_URI if it
2489 * was a GET or WSI_TOKEN_POST_URI if POST. You can check the total
2490 * length to confirm the method.
2492 * For URL arguments, each argument is stored urldecoded in a "fragment", so
2493 * you can use the fragment-aware api lws_hdr_copy_fragment() to access each
2494 * argument in turn: the fragments contain urldecoded strings like x=1 or y=2.
2496 * As a convenience, lws has an api that will find the fragment with a
2497 * given name= part, lws_get_urlarg_by_name().
2501 /** struct lws_tokens
2502 * you need these to look at headers that have been parsed if using the
2503 * LWS_CALLBACK_FILTER_CONNECTION callback. If a header from the enum
2504 * list below is absent, .token = NULL and token_len = 0. Otherwise .token
2505 * points to .token_len chars containing that header content.
2508 char *token; /**< pointer to start of the token */
2509 int token_len; /**< length of the token's value */
2512 /* enum lws_token_indexes
2513 * these have to be kept in sync with lextable.h / minilex.c
2515 * NOTE: These public enums are part of the abi. If you want to add one,
2516 * add it at where specified so existing users are unaffected.
2518 enum lws_token_indexes {
2519 WSI_TOKEN_GET_URI = 0,
2520 WSI_TOKEN_POST_URI = 1,
2521 WSI_TOKEN_OPTIONS_URI = 2,
2523 WSI_TOKEN_CONNECTION = 4,
2524 WSI_TOKEN_UPGRADE = 5,
2525 WSI_TOKEN_ORIGIN = 6,
2526 WSI_TOKEN_DRAFT = 7,
2527 WSI_TOKEN_CHALLENGE = 8,
2528 WSI_TOKEN_EXTENSIONS = 9,
2529 WSI_TOKEN_KEY1 = 10,
2530 WSI_TOKEN_KEY2 = 11,
2531 WSI_TOKEN_PROTOCOL = 12,
2532 WSI_TOKEN_ACCEPT = 13,
2533 WSI_TOKEN_NONCE = 14,
2534 WSI_TOKEN_HTTP = 15,
2535 WSI_TOKEN_HTTP2_SETTINGS = 16,
2536 WSI_TOKEN_HTTP_ACCEPT = 17,
2537 WSI_TOKEN_HTTP_AC_REQUEST_HEADERS = 18,
2538 WSI_TOKEN_HTTP_IF_MODIFIED_SINCE = 19,
2539 WSI_TOKEN_HTTP_IF_NONE_MATCH = 20,
2540 WSI_TOKEN_HTTP_ACCEPT_ENCODING = 21,
2541 WSI_TOKEN_HTTP_ACCEPT_LANGUAGE = 22,
2542 WSI_TOKEN_HTTP_PRAGMA = 23,
2543 WSI_TOKEN_HTTP_CACHE_CONTROL = 24,
2544 WSI_TOKEN_HTTP_AUTHORIZATION = 25,
2545 WSI_TOKEN_HTTP_COOKIE = 26,
2546 WSI_TOKEN_HTTP_CONTENT_LENGTH = 27,
2547 WSI_TOKEN_HTTP_CONTENT_TYPE = 28,
2548 WSI_TOKEN_HTTP_DATE = 29,
2549 WSI_TOKEN_HTTP_RANGE = 30,
2550 WSI_TOKEN_HTTP_REFERER = 31,
2552 WSI_TOKEN_VERSION = 33,
2553 WSI_TOKEN_SWORIGIN = 34,
2555 WSI_TOKEN_HTTP_COLON_AUTHORITY = 35,
2556 WSI_TOKEN_HTTP_COLON_METHOD = 36,
2557 WSI_TOKEN_HTTP_COLON_PATH = 37,
2558 WSI_TOKEN_HTTP_COLON_SCHEME = 38,
2559 WSI_TOKEN_HTTP_COLON_STATUS = 39,
2561 WSI_TOKEN_HTTP_ACCEPT_CHARSET = 40,
2562 WSI_TOKEN_HTTP_ACCEPT_RANGES = 41,
2563 WSI_TOKEN_HTTP_ACCESS_CONTROL_ALLOW_ORIGIN = 42,
2564 WSI_TOKEN_HTTP_AGE = 43,
2565 WSI_TOKEN_HTTP_ALLOW = 44,
2566 WSI_TOKEN_HTTP_CONTENT_DISPOSITION = 45,
2567 WSI_TOKEN_HTTP_CONTENT_ENCODING = 46,
2568 WSI_TOKEN_HTTP_CONTENT_LANGUAGE = 47,
2569 WSI_TOKEN_HTTP_CONTENT_LOCATION = 48,
2570 WSI_TOKEN_HTTP_CONTENT_RANGE = 49,
2571 WSI_TOKEN_HTTP_ETAG = 50,
2572 WSI_TOKEN_HTTP_EXPECT = 51,
2573 WSI_TOKEN_HTTP_EXPIRES = 52,
2574 WSI_TOKEN_HTTP_FROM = 53,
2575 WSI_TOKEN_HTTP_IF_MATCH = 54,
2576 WSI_TOKEN_HTTP_IF_RANGE = 55,
2577 WSI_TOKEN_HTTP_IF_UNMODIFIED_SINCE = 56,
2578 WSI_TOKEN_HTTP_LAST_MODIFIED = 57,
2579 WSI_TOKEN_HTTP_LINK = 58,
2580 WSI_TOKEN_HTTP_LOCATION = 59,
2581 WSI_TOKEN_HTTP_MAX_FORWARDS = 60,
2582 WSI_TOKEN_HTTP_PROXY_AUTHENTICATE = 61,
2583 WSI_TOKEN_HTTP_PROXY_AUTHORIZATION = 62,
2584 WSI_TOKEN_HTTP_REFRESH = 63,
2585 WSI_TOKEN_HTTP_RETRY_AFTER = 64,
2586 WSI_TOKEN_HTTP_SERVER = 65,
2587 WSI_TOKEN_HTTP_SET_COOKIE = 66,
2588 WSI_TOKEN_HTTP_STRICT_TRANSPORT_SECURITY = 67,
2589 WSI_TOKEN_HTTP_TRANSFER_ENCODING = 68,
2590 WSI_TOKEN_HTTP_USER_AGENT = 69,
2591 WSI_TOKEN_HTTP_VARY = 70,
2592 WSI_TOKEN_HTTP_VIA = 71,
2593 WSI_TOKEN_HTTP_WWW_AUTHENTICATE = 72,
2595 WSI_TOKEN_PATCH_URI = 73,
2596 WSI_TOKEN_PUT_URI = 74,
2597 WSI_TOKEN_DELETE_URI = 75,
2599 WSI_TOKEN_HTTP_URI_ARGS = 76,
2600 WSI_TOKEN_PROXY = 77,
2601 WSI_TOKEN_HTTP_X_REAL_IP = 78,
2602 WSI_TOKEN_HTTP1_0 = 79,
2604 /****** add new things just above ---^ ******/
2606 /* use token storage to stash these internally, not for
2609 _WSI_TOKEN_CLIENT_SENT_PROTOCOLS,
2610 _WSI_TOKEN_CLIENT_PEER_ADDRESS,
2611 _WSI_TOKEN_CLIENT_URI,
2612 _WSI_TOKEN_CLIENT_HOST,
2613 _WSI_TOKEN_CLIENT_ORIGIN,
2614 _WSI_TOKEN_CLIENT_METHOD,
2616 /* always last real token index*/
2619 /* parser state additions, no storage associated */
2620 WSI_TOKEN_NAME_PART,
2622 WSI_TOKEN_SKIPPING_SAW_CR,
2623 WSI_PARSING_COMPLETE,
2624 WSI_INIT_TOKEN_MUXURL,
2627 struct lws_token_limits {
2628 unsigned short token_limit[WSI_TOKEN_COUNT]; /**< max chars for this token */
2632 * lws_token_to_string() - returns a textual representation of a hdr token index
2634 * \param: token index
2636 LWS_VISIBLE LWS_EXTERN const unsigned char *
2637 lws_token_to_string(enum lws_token_indexes token);
2641 * lws_hdr_total_length: report length of all fragments of a header totalled up
2642 * The returned length does not include the space for a
2645 * \param wsi: websocket connection
2646 * \param h: which header index we are interested in
2648 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2649 lws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h);
2652 * lws_hdr_fragment_length: report length of a single fragment of a header
2653 * The returned length does not include the space for a
2656 * \param wsi: websocket connection
2657 * \param h: which header index we are interested in
2658 * \param frag_idx: which fragment of h we want to get the length of
2660 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2661 lws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx);
2664 * lws_hdr_copy() - copy a single fragment of the given header to a buffer
2665 * The buffer length len must include space for an additional
2666 * terminating '\0', or it will fail returning -1.
2668 * \param wsi: websocket connection
2669 * \param dest: destination buffer
2670 * \param len: length of destination buffer
2671 * \param h: which header index we are interested in
2673 * copies the whole, aggregated header, even if it was delivered in
2674 * several actual headers piece by piece
2676 LWS_VISIBLE LWS_EXTERN int
2677 lws_hdr_copy(struct lws *wsi, char *dest, int len, enum lws_token_indexes h);
2680 * lws_hdr_copy_fragment() - copy a single fragment of the given header to a buffer
2681 * The buffer length len must include space for an additional
2682 * terminating '\0', or it will fail returning -1.
2683 * If the requested fragment index is not present, it fails
2686 * \param wsi: websocket connection
2687 * \param dest: destination buffer
2688 * \param len: length of destination buffer
2689 * \param h: which header index we are interested in
2690 * \param frag_idx: which fragment of h we want to copy
2692 * Normally this is only useful
2693 * to parse URI arguments like ?x=1&y=2, token index WSI_TOKEN_HTTP_URI_ARGS
2694 * fragment 0 will contain "x=1" and fragment 1 "y=2"
2696 LWS_VISIBLE LWS_EXTERN int
2697 lws_hdr_copy_fragment(struct lws *wsi, char *dest, int len,
2698 enum lws_token_indexes h, int frag_idx);
2701 * lws_get_urlarg_by_name() - return pointer to arg value if present
2702 * \param wsi: the connection to check
2703 * \param name: the arg name, like "token="
2704 * \param buf: the buffer to receive the urlarg (including the name= part)
2705 * \param len: the length of the buffer to receive the urlarg
2707 * Returns NULL if not found or a pointer inside buf to just after the
2710 LWS_VISIBLE LWS_EXTERN const char *
2711 lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len);
2714 /*! \defgroup HTTP-headers-create HTTP headers: create
2716 * ## HTTP headers: Create
2718 * These apis allow you to create HTTP response headers in a way compatible with
2719 * both HTTP/1.x and HTTP/2.
2721 * They each append to a buffer taking care about the buffer end, which is
2722 * passed in as a pointer. When data is written to the buffer, the current
2723 * position p is updated accordingly.
2725 * All of these apis are LWS_WARN_UNUSED_RESULT as they can run out of space
2726 * and fail with nonzero return.
2730 * lws_add_http_header_status() - add the HTTP response status code
2732 * \param wsi: the connection to check
2733 * \param code: an HTTP code like 200, 404 etc (see enum http_status)
2734 * \param p: pointer to current position in buffer pointer
2735 * \param end: pointer to end of buffer
2737 * Adds the initial response code, so should be called first
2739 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2740 lws_add_http_header_status(struct lws *wsi,
2741 unsigned int code, unsigned char **p,
2742 unsigned char *end);
2744 * lws_add_http_header_by_name() - append named header and value
2746 * \param wsi: the connection to check
2747 * \param name: the hdr name, like "my-header"
2748 * \param value: the value after the = for this header
2749 * \param length: the length of the value
2750 * \param p: pointer to current position in buffer pointer
2751 * \param end: pointer to end of buffer
2753 * Appends name: value to the headers
2755 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2756 lws_add_http_header_by_name(struct lws *wsi, const unsigned char *name,
2757 const unsigned char *value, int length,
2758 unsigned char **p, unsigned char *end);
2760 * lws_add_http_header_by_token() - append given header and value
2762 * \param wsi: the connection to check
2763 * \param token: the token index for the hdr
2764 * \param value: the value after the = for this header
2765 * \param length: the length of the value
2766 * \param p: pointer to current position in buffer pointer
2767 * \param end: pointer to end of buffer
2769 * Appends name=value to the headers, but is able to take advantage of better
2770 * HTTP/2 coding mechanisms where possible.
2772 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2773 lws_add_http_header_by_token(struct lws *wsi, enum lws_token_indexes token,
2774 const unsigned char *value, int length,
2775 unsigned char **p, unsigned char *end);
2777 * lws_add_http_header_by_name() - append content-length helper
2779 * \param wsi: the connection to check
2780 * \param content_length: the content length to use
2781 * \param p: pointer to current position in buffer pointer
2782 * \param end: pointer to end of buffer
2784 * Appends content-length: content_length to the headers
2786 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2787 lws_add_http_header_content_length(struct lws *wsi,
2788 unsigned long content_length,
2789 unsigned char **p, unsigned char *end);
2791 * lws_finalize_http_header() - terminate header block
2793 * \param wsi: the connection to check
2794 * \param p: pointer to current position in buffer pointer
2795 * \param end: pointer to end of buffer
2797 * Indicates no more headers will be added
2799 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2800 lws_finalize_http_header(struct lws *wsi, unsigned char **p,
2801 unsigned char *end);
2804 /** \defgroup form-parsing Form Parsing
2806 * ##POSTed form parsing functions
2808 * These lws_spa (stateful post arguments) apis let you parse and urldecode
2809 * POSTed form arguments, both using simple urlencoded and multipart transfer
2812 * It's capable of handling file uploads as well a named input parsing,
2813 * and the apis are the same for both form upload styles.
2815 * You feed it a list of parameter names and it creates pointers to the
2816 * urldecoded arguments: file upload parameters pass the file data in chunks to
2817 * a user-supplied callback as they come.
2819 * Since it's stateful, it handles the incoming data needing more than one
2820 * POST_BODY callback and has no limit on uploaded file size.
2824 /** enum lws_spa_fileupload_states */
2825 enum lws_spa_fileupload_states {
2827 /**< a chunk of file content has arrived */
2828 LWS_UFS_FINAL_CONTENT,
2829 /**< the last chunk (possibly zero length) of file content has arrived */
2831 /**< a new file is starting to arrive */
2835 * lws_spa_fileupload_cb() - callback to receive file upload data
2837 * \param data: opt_data pointer set in lws_spa_create
2838 * \param name: name of the form field being uploaded
2839 * \param filename: original filename from client
2840 * \param buf: start of data to receive
2841 * \param len: length of data to receive
2842 * \param state: information about how this call relates to file
2844 * Notice name and filename shouldn't be trusted, as they are passed from
2845 * HTTP provided by the client.
2847 typedef int (*lws_spa_fileupload_cb)(void *data, const char *name,
2848 const char *filename, char *buf, int len,
2849 enum lws_spa_fileupload_states state);
2851 /** struct lws_spa - opaque urldecode parser capable of handling multipart
2852 * and file uploads */
2856 * lws_spa_create() - create urldecode parser
2858 * \param wsi: lws connection (used to find Content Type)
2859 * \param param_names: array of form parameter names, like "username"
2860 * \param count_params: count of param_names
2861 * \param max_storage: total amount of form parameter values we can store
2862 * \param opt_cb: NULL, or callback to receive file upload data.
2863 * \param opt_data: NULL, or user pointer provided to opt_cb.
2865 * Creates a urldecode parser and initializes it.
2867 * opt_cb can be NULL if you just want normal name=value parsing, however
2868 * if one or more entries in your form are bulk data (file transfer), you
2869 * can provide this callback and filter on the name callback parameter to
2870 * treat that urldecoded data separately. The callback should return -1
2871 * in case of fatal error, and 0 if OK.
2873 LWS_VISIBLE LWS_EXTERN struct lws_spa *
2874 lws_spa_create(struct lws *wsi, const char * const *param_names,
2875 int count_params, int max_storage, lws_spa_fileupload_cb opt_cb,
2879 * lws_spa_process() - parses a chunk of input data
2881 * \param spa: the parser object previously created
2882 * \param in: incoming, urlencoded data
2883 * \param len: count of bytes valid at \param in
2885 LWS_VISIBLE LWS_EXTERN int
2886 lws_spa_process(struct lws_spa *spa, const char *in, int len);
2889 * lws_spa_finalize() - indicate incoming data completed
2891 * \param spa: the parser object previously created
2893 LWS_VISIBLE LWS_EXTERN int
2894 lws_spa_finalize(struct lws_spa *spa);
2897 * lws_spa_get_length() - return length of parameter value
2899 * \param spa: the parser object previously created
2900 * \param n: parameter ordinal to return length of value for
2902 LWS_VISIBLE LWS_EXTERN int
2903 lws_spa_get_length(struct lws_spa *spa, int n);
2906 * lws_spa_get_string() - return pointer to parameter value
2907 * \param spa: the parser object previously created
2908 * \param n: parameter ordinal to return pointer to value for
2910 LWS_VISIBLE LWS_EXTERN const char *
2911 lws_spa_get_string(struct lws_spa *spa, int n);
2914 * lws_spa_destroy() - destroy parser object
2916 * \param spa: the parser object previously created
2918 LWS_VISIBLE LWS_EXTERN int
2919 lws_spa_destroy(struct lws_spa *spa);
2922 /*! \defgroup urlendec Urlencode and Urldecode
2925 * ##HTML chunked Substitution
2927 * APIs for receiving chunks of text, replacing a set of variable names via
2928 * a callback, and then prepending and appending HTML chunked encoding
2934 * lws_urlencode() - like strncpy but with urlencoding
2936 * \param escaped: output buffer
2937 * \param string: input buffer ('/0' terminated)
2938 * \param len: output buffer max length
2940 * Because urlencoding expands the output string, it's not
2941 * possible to do it in-place, ie, with escaped == string
2943 LWS_VISIBLE LWS_EXTERN const char *
2944 lws_urlencode(char *escaped, const char *string, int len);
2949 * This simple urldecode only operates until the first '\0' and requires the
2950 * data to exist all at once
2953 * lws_urldecode() - like strncpy but with urldecoding
2955 * \param string: output buffer
2956 * \param escaped: input buffer ('\0' terminated)
2957 * \param len: output buffer max length
2959 * This is only useful for '\0' terminated strings
2961 * Since urldecoding only shrinks the output string, it is possible to
2962 * do it in-place, ie, string == escaped
2964 LWS_VISIBLE LWS_EXTERN int
2965 lws_urldecode(char *string, const char *escaped, int len);
2968 * lws_return_http_status() - Return simple http status
2969 * \param wsi: Websocket instance (available from user callback)
2970 * \param code: Status index, eg, 404
2971 * \param html_body: User-readable HTML description < 1KB, or NULL
2973 * Helper to report HTTP errors back to the client cleanly and
2976 LWS_VISIBLE LWS_EXTERN int
2977 lws_return_http_status(struct lws *wsi, unsigned int code,
2978 const char *html_body);
2981 * lws_http_redirect() - write http redirect into buffer
2983 * \param wsi: websocket connection
2984 * \param code: HTTP response code (eg, 301)
2985 * \param loc: where to redirect to
2986 * \param len: length of loc
2987 * \param p: pointer current position in buffer (updated as we write)
2988 * \param end: pointer to end of buffer
2990 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2991 lws_http_redirect(struct lws *wsi, int code, const unsigned char *loc, int len,
2992 unsigned char **p, unsigned char *end);
2995 * lws_http_transaction_completed() - wait for new http transaction or close
2996 * \param wsi: websocket connection
2998 * Returns 1 if the HTTP connection must close now
2999 * Returns 0 and resets connection to wait for new HTTP header /
3000 * transaction if possible
3002 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3003 lws_http_transaction_completed(struct lws *wsi);
3006 /*! \defgroup pur Sanitize / purify SQL and JSON helpers
3008 * ##Sanitize / purify SQL and JSON helpers
3010 * APIs for escaping untrusted JSON and SQL safely before use
3015 * lws_sql_purify() - like strncpy but with escaping for sql quotes
3017 * \param escaped: output buffer
3018 * \param string: input buffer ('/0' terminated)
3019 * \param len: output buffer max length
3021 * Because escaping expands the output string, it's not
3022 * possible to do it in-place, ie, with escaped == string
3024 LWS_VISIBLE LWS_EXTERN const char *
3025 lws_sql_purify(char *escaped, const char *string, int len);
3028 * lws_json_purify() - like strncpy but with escaping for json chars
3030 * \param escaped: output buffer
3031 * \param string: input buffer ('/0' terminated)
3032 * \param len: output buffer max length
3034 * Because escaping expands the output string, it's not
3035 * possible to do it in-place, ie, with escaped == string
3037 LWS_VISIBLE LWS_EXTERN const char *
3038 lws_json_purify(char *escaped, const char *string, int len);
3041 /*! \defgroup ev libev helpers
3045 * APIs specific to libev event loop itegration
3049 #ifdef LWS_USE_LIBEV
3050 typedef void (lws_ev_signal_cb_t)(EV_P_ struct ev_signal *w, int revents);
3052 LWS_VISIBLE LWS_EXTERN int
3053 lws_ev_sigint_cfg(struct lws_context *context, int use_ev_sigint,
3054 lws_ev_signal_cb_t *cb);
3056 LWS_VISIBLE LWS_EXTERN int
3057 lws_ev_initloop(struct lws_context *context, struct ev_loop *loop, int tsi);
3059 LWS_VISIBLE LWS_EXTERN void
3060 lws_ev_sigint_cb(struct ev_loop *loop, struct ev_signal *watcher, int revents);
3061 #endif /* LWS_USE_LIBEV */
3065 /*! \defgroup uv libuv helpers
3069 * APIs specific to libuv event loop itegration
3072 #ifdef LWS_USE_LIBUV
3073 LWS_VISIBLE LWS_EXTERN int
3074 lws_uv_sigint_cfg(struct lws_context *context, int use_uv_sigint,
3077 LWS_VISIBLE LWS_EXTERN void
3078 lws_libuv_run(const struct lws_context *context, int tsi);
3080 LWS_VISIBLE LWS_EXTERN void
3081 lws_libuv_stop(struct lws_context *context);
3083 LWS_VISIBLE LWS_EXTERN int
3084 lws_uv_initloop(struct lws_context *context, uv_loop_t *loop, int tsi);
3086 LWS_VISIBLE LWS_EXTERN uv_loop_t *
3087 lws_uv_getloop(struct lws_context *context, int tsi);
3089 LWS_VISIBLE LWS_EXTERN void
3090 lws_uv_sigint_cb(uv_signal_t *watcher, int signum);
3091 #endif /* LWS_USE_LIBUV */
3094 /*! \defgroup timeout Connection timeouts
3096 APIs related to setting connection timeouts
3101 * NOTE: These public enums are part of the abi. If you want to add one,
3102 * add it at where specified so existing users are unaffected.
3104 enum pending_timeout {
3105 NO_PENDING_TIMEOUT = 0,
3106 PENDING_TIMEOUT_AWAITING_PROXY_RESPONSE = 1,
3107 PENDING_TIMEOUT_AWAITING_CONNECT_RESPONSE = 2,
3108 PENDING_TIMEOUT_ESTABLISH_WITH_SERVER = 3,
3109 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE = 4,
3110 PENDING_TIMEOUT_AWAITING_PING = 5,
3111 PENDING_TIMEOUT_CLOSE_ACK = 6,
3112 PENDING_TIMEOUT_AWAITING_EXTENSION_CONNECT_RESPONSE = 7,
3113 PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE = 8,
3114 PENDING_TIMEOUT_SSL_ACCEPT = 9,
3115 PENDING_TIMEOUT_HTTP_CONTENT = 10,
3116 PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND = 11,
3117 PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE = 12,
3118 PENDING_TIMEOUT_SHUTDOWN_FLUSH = 13,
3119 PENDING_TIMEOUT_CGI = 14,
3120 PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE = 15,
3121 PENDING_TIMEOUT_WS_PONG_CHECK_SEND_PING = 16,
3122 PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG = 17,
3123 PENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD = 18,
3125 /****** add new things just above ---^ ******/
3129 * lws_set_timeout() - marks the wsi as subject to a timeout
3131 * You will not need this unless you are doing something special
3133 * \param wsi: Websocket connection instance
3134 * \param reason: timeout reason
3135 * \param secs: how many seconds
3137 LWS_VISIBLE LWS_EXTERN void
3138 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs);
3141 /*! \defgroup sending-data Sending data
3143 APIs related to writing data on a connection
3146 #if !defined(LWS_SIZEOFPTR)
3147 #define LWS_SIZEOFPTR (sizeof (void *))
3149 #if !defined(u_int64_t)
3150 #define u_int64_t unsigned long long
3153 #if defined(__x86_64__)
3154 #define _LWS_PAD_SIZE 16 /* Intel recommended for best performance */
3156 #define _LWS_PAD_SIZE LWS_SIZEOFPTR /* Size of a pointer on the target arch */
3158 #define _LWS_PAD(n) (((n) % _LWS_PAD_SIZE) ? \
3159 ((n) + (_LWS_PAD_SIZE - ((n) % _LWS_PAD_SIZE))) : (n))
3160 #define LWS_PRE _LWS_PAD(4 + 10)
3161 /* used prior to 1.7 and retained for backward compatibility */
3162 #define LWS_SEND_BUFFER_PRE_PADDING LWS_PRE
3163 #define LWS_SEND_BUFFER_POST_PADDING 0
3166 * NOTE: These public enums are part of the abi. If you want to add one,
3167 * add it at where specified so existing users are unaffected.
3169 enum lws_write_protocol {
3171 /**< Send a ws TEXT message,the pointer must have LWS_PRE valid
3172 * memory behind it. The receiver expects only valid utf-8 in the
3174 LWS_WRITE_BINARY = 1,
3175 /**< Send a ws BINARY message, the pointer must have LWS_PRE valid
3176 * memory behind it. Any sequence of bytes is valid */
3177 LWS_WRITE_CONTINUATION = 2,
3178 /**< Continue a previous ws message, the pointer must have LWS_PRE valid
3179 * memory behind it */
3181 /**< Send HTTP content */
3183 /* LWS_WRITE_CLOSE is handled by lws_close_reason() */
3187 /* Same as write_http but we know this write ends the transaction */
3188 LWS_WRITE_HTTP_FINAL = 7,
3192 LWS_WRITE_HTTP_HEADERS = 8,
3193 /**< Send http headers (http2 encodes this payload and LWS_WRITE_HTTP
3194 * payload differently, http 1.x links also handle this correctly. so
3195 * to be compatible with both in the future,header response part should
3196 * be sent using this regardless of http version expected)
3199 /****** add new things just above ---^ ******/
3203 LWS_WRITE_NO_FIN = 0x40,
3204 /**< This part of the message is not the end of the message */
3206 LWS_WRITE_CLIENT_IGNORE_XOR_MASK = 0x80
3207 /**< client packet payload goes out on wire unmunged
3208 * only useful for security tests since normal servers cannot
3209 * decode the content if used */
3214 * lws_write() - Apply protocol then write data to client
3215 * \param wsi: Websocket instance (available from user callback)
3216 * \param buf: The data to send. For data being sent on a websocket
3217 * connection (ie, not default http), this buffer MUST have
3218 * LWS_PRE bytes valid BEFORE the pointer.
3219 * This is so the protocol header data can be added in-situ.
3220 * \param len: Count of the data bytes in the payload starting from buf
3221 * \param protocol: Use LWS_WRITE_HTTP to reply to an http connection, and one
3222 * of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
3223 * data on a websockets connection. Remember to allow the extra
3224 * bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
3227 * This function provides the way to issue data back to the client
3228 * for both http and websocket protocols.
3232 * When sending with websocket protocol
3236 * LWS_WRITE_CONTINUATION,
3240 * the send buffer has to have LWS_PRE bytes valid BEFORE
3241 * the buffer pointer you pass to lws_write().
3243 * This allows us to add protocol info before and after the data, and send as
3244 * one packet on the network without payload copying, for maximum efficiency.
3246 * So for example you need this kind of code to use lws_write with a
3249 * char buf[LWS_PRE + 128];
3251 * // fill your part of the buffer... for example here it's all zeros
3252 * memset(&buf[LWS_PRE], 0, 128);
3254 * lws_write(wsi, &buf[LWS_PRE], 128, LWS_WRITE_TEXT);
3256 * When sending HTTP, with
3259 * LWS_WRITE_HTTP_HEADERS
3260 * LWS_WRITE_HTTP_FINAL
3262 * there is no protocol data prepended, and don't need to take care about the
3263 * LWS_PRE bytes valid before the buffer pointer.
3265 * LWS_PRE is at least the frame nonce + 2 header + 8 length
3266 * LWS_SEND_BUFFER_POST_PADDING is deprecated, it's now 0 and can be left off.
3267 * The example apps no longer use it.
3269 * Pad LWS_PRE to the CPU word size, so that word references
3270 * to the address immediately after the padding won't cause an unaligned access
3271 * error. Sometimes for performance reasons the recommended padding is even
3272 * larger than sizeof(void *).
3274 * In the case of sending using websocket protocol, be sure to allocate
3275 * valid storage before and after buf as explained above. This scheme
3276 * allows maximum efficiency of sending data and protocol in a single
3277 * packet while not burdening the user code with any protocol knowledge.
3279 * Return may be -1 for a fatal error needing connection close, or the
3280 * number of bytes sent.
3285 * The OS may not accept everything you asked to write on the connection.
3287 * Posix defines POLLOUT indication from poll() to show that the connection
3288 * will accept more write data, but it doesn't specifiy how much. It may just
3289 * accept one byte of whatever you wanted to send.
3291 * LWS will buffer the remainder automatically, and send it out autonomously.
3293 * During that time, WRITABLE callbacks will be suppressed.
3295 * This is to handle corner cases where unexpectedly the OS refuses what we
3296 * usually expect it to accept. You should try to send in chunks that are
3297 * almost always accepted in order to avoid the inefficiency of the buffering.
3299 LWS_VISIBLE LWS_EXTERN int
3300 lws_write(struct lws *wsi, unsigned char *buf, size_t len,
3301 enum lws_write_protocol protocol);
3303 /* helper for case where buffer may be const */
3304 #define lws_write_http(wsi, buf, len) \
3305 lws_write(wsi, (unsigned char *)(buf), len, LWS_WRITE_HTTP)
3308 /** \defgroup callback-when-writeable Callback when writeable
3310 * ##Callback When Writeable
3312 * lws can only write data on a connection when it is able to accept more
3313 * data without blocking.
3315 * So a basic requirement is we should only use the lws_write() apis when the
3316 * connection we want to write on says that he can accept more data.
3318 * When lws cannot complete your send at the time, it will buffer the data
3319 * and send it in the background, suppressing any further WRITEABLE callbacks
3320 * on that connection until it completes. So it is important to write new
3321 * things in a new writeable callback.
3323 * These apis reflect the various ways we can indicate we would like to be
3324 * called back when one or more connections is writeable.
3329 * lws_callback_on_writable() - Request a callback when this socket
3330 * becomes able to be written to without
3333 * \param wsi: Websocket connection instance to get callback for
3335 * - Which: only this wsi
3336 * - When: when the individual connection becomes writeable
3337 * - What: LWS_CALLBACK_*_WRITEABLE
3339 LWS_VISIBLE LWS_EXTERN int
3340 lws_callback_on_writable(struct lws *wsi);
3343 * lws_callback_on_writable_all_protocol() - Request a callback for all
3344 * connections on same vhost using the given protocol when it
3345 * becomes possible to write to each socket without
3348 * \param context: lws_context
3349 * \param protocol: Protocol whose connections will get callbacks
3351 * - Which: connections using this protocol on ANY VHOST
3352 * - When: when the individual connection becomes writeable
3353 * - What: LWS_CALLBACK_*_WRITEABLE
3355 LWS_VISIBLE LWS_EXTERN int
3356 lws_callback_on_writable_all_protocol(const struct lws_context *context,
3357 const struct lws_protocols *protocol);
3360 * lws_callback_on_writable_all_protocol_vhost() - Request a callback for
3361 * all connections using the given protocol when it
3362 * becomes possible to write to each socket without
3365 * \param vhost: Only consider connections on this lws_vhost
3366 * \param protocol: Protocol whose connections will get callbacks
3368 * - Which: connections using this protocol on GIVEN VHOST ONLY
3369 * - When: when the individual connection becomes writeable
3370 * - What: LWS_CALLBACK_*_WRITEABLE
3372 LWS_VISIBLE LWS_EXTERN int
3373 lws_callback_on_writable_all_protocol_vhost(const struct lws_vhost *vhost,
3374 const struct lws_protocols *protocol);
3377 * lws_callback_all_protocol() - Callback all connections using
3378 * the given protocol with the given reason
3380 * \param context: lws_context
3381 * \param protocol: Protocol whose connections will get callbacks
3382 * \param reason: Callback reason index
3384 * - Which: connections using this protocol on ALL VHOSTS
3385 * - When: when the individual connection becomes writeable
3388 LWS_VISIBLE LWS_EXTERN int
3389 lws_callback_all_protocol(struct lws_context *context,
3390 const struct lws_protocols *protocol, int reason);
3393 * lws_callback_all_protocol_vhost() - Callback all connections using
3394 * the given protocol with the given reason
3396 * \param vh: Vhost whose connections will get callbacks
3397 * \param protocol: Which protocol to match
3398 * \param reason: Callback reason index
3400 * - Which: connections using this protocol on GIVEN VHOST ONLY
3404 LWS_VISIBLE LWS_EXTERN int
3405 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
3406 const struct lws_protocols *protocol, int reason);
3409 * lws_callback_vhost_protocols() - Callback all protocols enabled on a vhost
3410 * with the given reason
3412 * \param wsi: wsi whose vhost will get callbacks
3413 * \param reason: Callback reason index
3414 * \param in: in argument to callback
3415 * \param len: len argument to callback
3417 * - Which: connections using this protocol on same VHOST as wsi ONLY
3421 LWS_VISIBLE LWS_EXTERN int
3422 lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len);
3424 LWS_VISIBLE LWS_EXTERN int
3425 lws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason,
3426 void *user, void *in, size_t len);
3429 * lws_get_socket_fd() - returns the socket file descriptor
3431 * You will not need this unless you are doing something special
3433 * \param wsi: Websocket connection instance
3435 LWS_VISIBLE LWS_EXTERN int
3436 lws_get_socket_fd(struct lws *wsi);
3439 * lws_get_peer_write_allowance() - get the amount of data writeable to peer
3442 * \param wsi: Websocket connection instance
3444 * if the protocol does not have any guidance, returns -1. Currently only
3445 * http2 connections get send window information from this API. But your code
3446 * should use it so it can work properly with any protocol.
3448 * If nonzero return is the amount of payload data the peer or intermediary has
3449 * reported it has buffer space for. That has NO relationship with the amount
3450 * of buffer space your OS can accept on this connection for a write action.
3452 * This number represents the maximum you could send to the peer or intermediary
3453 * on this connection right now without the protocol complaining.
3455 * lws manages accounting for send window updates and payload writes
3456 * automatically, so this number reflects the situation at the peer or
3457 * intermediary dynamically.
3459 LWS_VISIBLE LWS_EXTERN size_t
3460 lws_get_peer_write_allowance(struct lws *wsi);
3464 * lws_rx_flow_control() - Enable and disable socket servicing for
3467 * If the output side of a server process becomes choked, this allows flow
3468 * control for the input side.
3470 * \param wsi: Websocket connection instance to get callback for
3471 * \param enable: 0 = disable read servicing for this connection, 1 = enable
3473 LWS_VISIBLE LWS_EXTERN int
3474 lws_rx_flow_control(struct lws *wsi, int enable);
3477 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
3479 * When the user server code realizes it can accept more input, it can
3480 * call this to have the RX flow restriction removed from all connections using
3481 * the given protocol.
3482 * \param context: lws_context
3483 * \param protocol: all connections using this protocol will be allowed to receive
3485 LWS_VISIBLE LWS_EXTERN void
3486 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
3487 const struct lws_protocols *protocol);
3490 * lws_remaining_packet_payload() - Bytes to come before "overall"
3491 * rx packet is complete
3492 * \param wsi: Websocket instance (available from user callback)
3494 * This function is intended to be called from the callback if the
3495 * user code is interested in "complete packets" from the client.
3496 * libwebsockets just passes through payload as it comes and issues a buffer
3497 * additionally when it hits a built-in limit. The LWS_CALLBACK_RECEIVE
3498 * callback handler can use this API to find out if the buffer it has just
3499 * been given is the last piece of a "complete packet" from the client --
3500 * when that is the case lws_remaining_packet_payload() will return
3503 * Many protocols won't care becuse their packets are always small.
3505 LWS_VISIBLE LWS_EXTERN size_t
3506 lws_remaining_packet_payload(struct lws *wsi);
3509 /** \defgroup sock-adopt Socket adoption helpers
3510 * ##Socket adoption helpers
3512 * When integrating with an external app with its own event loop, these can
3513 * be used to accept connections from someone else's listening socket.
3515 * When using lws own event loop, these are not needed.
3520 * lws_adopt_socket() - adopt foreign socket as if listen socket accepted it
3521 * \param context: lws context
3522 * \param accept_fd: fd of already-accepted socket to adopt
3524 * Either returns new wsi bound to accept_fd, or closes accept_fd and
3525 * returns NULL, having cleaned up any new wsi pieces.
3527 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
3528 * to ws or just serve http.
3530 LWS_VISIBLE LWS_EXTERN struct lws *
3531 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd);
3533 * lws_adopt_socket_readbuf() - adopt foreign socket and first rx as if listen socket accepted it
3534 * \param context: lws context
3535 * \param accept_fd: fd of already-accepted socket to adopt
3536 * \param readbuf: NULL or pointer to data that must be drained before reading from
3538 * \param len: The length of the data held at \param readbuf
3540 * Either returns new wsi bound to accept_fd, or closes accept_fd and
3541 * returns NULL, having cleaned up any new wsi pieces.
3543 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
3544 * to ws or just serve http.
3546 * If your external code did not already read from the socket, you can use
3547 * lws_adopt_socket() instead.
3549 * This api is guaranteed to use the data at \param readbuf first, before reading from
3552 * readbuf is limited to the size of the ah rx buf, currently 2048 bytes.
3554 LWS_VISIBLE LWS_EXTERN struct lws *
3555 lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
3556 const char *readbuf, size_t len);
3559 /** \defgroup net Network related helper APIs
3560 * ##Network related helper APIs
3562 * These wrap miscellaneous useful network-related functions
3567 * lws_canonical_hostname() - returns this host's hostname
3569 * This is typically used by client code to fill in the host parameter
3570 * when making a client connection. You can only call it after the context
3573 * \param context: Websocket context
3575 LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
3576 lws_canonical_hostname(struct lws_context *context);
3579 * lws_get_peer_addresses() - Get client address information
3580 * \param wsi: Local struct lws associated with
3581 * \param fd: Connection socket descriptor
3582 * \param name: Buffer to take client address name
3583 * \param name_len: Length of client address name buffer
3584 * \param rip: Buffer to take client address IP dotted quad
3585 * \param rip_len: Length of client address IP buffer
3587 * This function fills in name and rip with the name and IP of
3588 * the client connected with socket descriptor fd. Names may be
3589 * truncated if there is not enough room. If either cannot be
3590 * determined, they will be returned as valid zero-length strings.
3592 LWS_VISIBLE LWS_EXTERN void
3593 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
3594 int name_len, char *rip, int rip_len);
3597 * lws_get_peer_simple() - Get client address information without RDNS
3599 * \param wsi: Local struct lws associated with
3600 * \param name: Buffer to take client address name
3601 * \param namelen: Length of client address name buffer
3603 * This provides a 123.123.123.123 type IP address in name from the
3604 * peer that has connected to wsi
3606 LWS_VISIBLE LWS_EXTERN const char *
3607 lws_get_peer_simple(struct lws *wsi, char *name, int namelen);
3608 #ifndef LWS_WITH_ESP8266
3610 * lws_interface_to_sa() - Convert interface name or IP to sockaddr struct
3612 * \param ipv6: Allow IPV6 addresses
3613 * \param ifname: Interface name or IP
3614 * \param addr: struct sockaddr_in * to be written
3615 * \param addrlen: Length of addr
3617 * This converts a textual network interface name to a sockaddr usable by
3618 * other network functions
3620 LWS_VISIBLE LWS_EXTERN int
3621 lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr,
3626 /** \defgroup misc Miscellaneous APIs
3627 * ##Miscellaneous APIs
3629 * Various APIs outside of other categories
3634 * lws_snprintf(): snprintf that truncates the returned length too
3636 * \param str: destination buffer
3637 * \param size: bytes left in destination buffer
3638 * \param format: format string
3639 * \param ...: args for format
3641 * This lets you correctly truncate buffers by concatenating lengths, if you
3642 * reach the limit the reported length doesn't exceed the limit.
3644 LWS_VISIBLE LWS_EXTERN int
3645 lws_snprintf(char *str, size_t size, const char *format, ...);
3648 * lws_get_random(): fill a buffer with platform random data
3650 * \param context: the lws context
3651 * \param buf: buffer to fill
3652 * \param len: how much to fill
3654 * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
3655 * it's interested to see if the frame it's dealing with was sent in binary
3658 LWS_VISIBLE LWS_EXTERN int
3659 lws_get_random(struct lws_context *context, void *buf, int len);
3661 * lws_daemonize(): fill a buffer with platform random data
3663 * \param _lock_path: the filepath to write the lock file
3665 * Spawn lws as a background process, taking care of various things
3667 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3668 lws_daemonize(const char *_lock_path);
3670 * lws_get_library_version(): return string describing the version of lws
3672 * On unix, also includes the git describe
3674 LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
3675 lws_get_library_version(void);
3678 * lws_wsi_user() - get the user data associated with the connection
3679 * \param wsi: lws connection
3681 * Not normally needed since it's passed into the callback
3683 LWS_VISIBLE LWS_EXTERN void *
3684 lws_wsi_user(struct lws *wsi);
3687 * lws_parse_uri: cut up prot:/ads:port/path into pieces
3688 * Notice it does so by dropping '\0' into input string
3689 * and the leading / on the path is consequently lost
3691 * \param p: incoming uri string.. will get written to
3692 * \param prot: result pointer for protocol part (https://)
3693 * \param ads: result pointer for address part
3694 * \param port: result pointer for port part
3695 * \param path: result pointer for path part
3697 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3698 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
3702 * lws_now_secs(): return seconds since 1970-1-1
3704 LWS_VISIBLE LWS_EXTERN unsigned long
3708 * lws_get_context - Allow geting lws_context from a Websocket connection
3711 * With this function, users can access context in the callback function.
3712 * Otherwise users may have to declare context as a global variable.
3714 * \param wsi: Websocket connection instance
3716 LWS_VISIBLE LWS_EXTERN struct lws_context * LWS_WARN_UNUSED_RESULT
3717 lws_get_context(const struct lws *wsi);
3720 * lws_get_count_threads(): how many service threads the context uses
3722 * \param context: the lws context
3724 * By default this is always 1, if you asked for more than lws can handle it
3725 * will clip the number of threads. So you can use this to find out how many
3726 * threads are actually in use.
3728 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3729 lws_get_count_threads(struct lws_context *context);
3732 * lws_get_parent() - get parent wsi or NULL
3733 * \param wsi: lws connection
3735 * Specialized wsi like cgi stdin/out/err are associated to a parent wsi,
3736 * this allows you to get their parent.
3738 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
3739 lws_get_parent(const struct lws *wsi);
3742 * lws_get_child() - get child wsi or NULL
3743 * \param wsi: lws connection
3745 * Allows you to find a related wsi from the parent wsi.
3747 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
3748 lws_get_child(const struct lws *wsi);
3752 * \deprecated DEPRECATED Note: this is not normally needed as a user api.
3753 * It's provided in case it is
3754 * useful when integrating with other app poll loop service code.
3756 LWS_VISIBLE LWS_EXTERN int
3757 lws_read(struct lws *wsi, unsigned char *buf, size_t len);
3760 * lws_set_allocator() - custom allocator support
3764 * Allows you to replace the allocator (and deallocator) used by lws
3766 LWS_VISIBLE LWS_EXTERN void
3767 lws_set_allocator(void *(*realloc)(void *ptr, size_t size));
3770 /** \defgroup wsstatus Websocket status APIs
3771 * ##Websocket connection status APIs
3773 * These provide information about ws connection or message status
3777 * lws_send_pipe_choked() - tests if socket is writable or not
3778 * \param wsi: lws connection
3780 * Allows you to check if you can write more on the socket
3782 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3783 lws_send_pipe_choked(struct lws *wsi);
3786 * lws_is_final_fragment() - tests if last part of ws message
3787 * \param wsi: lws connection
3789 LWS_VISIBLE LWS_EXTERN int
3790 lws_is_final_fragment(struct lws *wsi);
3793 * lws_get_reserved_bits() - access reserved bits of ws frame
3794 * \param wsi: lws connection
3796 LWS_VISIBLE LWS_EXTERN unsigned char
3797 lws_get_reserved_bits(struct lws *wsi);
3800 * lws_partial_buffered() - find out if lws buffered the last write
3801 * \param wsi: websocket connection to check
3803 * Returns 1 if you cannot use lws_write because the last
3804 * write on this connection is still buffered, and can't be cleared without
3805 * returning to the service loop and waiting for the connection to be
3808 * If you will try to do >1 lws_write call inside a single
3809 * WRITEABLE callback, you must check this after every write and bail if
3810 * set, ask for a new writeable callback and continue writing from there.
3812 * This is never set at the start of a writeable callback, but any write
3815 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3816 lws_partial_buffered(struct lws *wsi);
3819 * lws_frame_is_binary(): true if the current frame was sent in binary mode
3821 * \param wsi: the connection we are inquiring about
3823 * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
3824 * it's interested to see if the frame it's dealing with was sent in binary
3827 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3828 lws_frame_is_binary(struct lws *wsi);
3831 * lws_is_ssl() - Find out if connection is using SSL
3832 * \param wsi: websocket connection to check
3834 * Returns 0 if the connection is not using SSL, 1 if using SSL and
3835 * using verified cert, and 2 if using SSL but the cert was not
3836 * checked (appears for client wsi told to skip check on connection)
3838 LWS_VISIBLE LWS_EXTERN int
3839 lws_is_ssl(struct lws *wsi);
3841 * lws_is_cgi() - find out if this wsi is running a cgi process
3842 * \param wsi: lws connection
3844 LWS_VISIBLE LWS_EXTERN int
3845 lws_is_cgi(struct lws *wsi);
3849 /** \defgroup sha SHA and B64 helpers
3850 * ##SHA and B64 helpers
3852 * These provide SHA-1 and B64 helper apis
3855 #ifdef LWS_SHA1_USE_OPENSSL_NAME
3856 #define lws_SHA1 SHA1
3859 * lws_SHA1(): make a SHA-1 digest of a buffer
3861 * \param d: incoming buffer
3862 * \param n: length of incoming buffer
3863 * \param md: buffer for message digest (must be >= 20 bytes)
3865 * Reduces any size buffer into a 20-byte SHA-1 hash.
3867 LWS_VISIBLE LWS_EXTERN unsigned char *
3868 lws_SHA1(const unsigned char *d, size_t n, unsigned char *md);
3871 * lws_b64_encode_string(): encode a string into base 64
3873 * \param in: incoming buffer
3874 * \param in_len: length of incoming buffer
3875 * \param out: result buffer
3876 * \param out_size: length of result buffer
3878 * Encodes a string using b64
3880 LWS_VISIBLE LWS_EXTERN int
3881 lws_b64_encode_string(const char *in, int in_len, char *out, int out_size);
3883 * lws_b64_decode_string(): decode a string from base 64
3885 * \param in: incoming buffer
3886 * \param out: result buffer
3887 * \param out_size: length of result buffer
3889 * Decodes a string using b64
3891 LWS_VISIBLE LWS_EXTERN int
3892 lws_b64_decode_string(const char *in, char *out, int out_size);
3896 /*! \defgroup cgi cgi handling
3900 * These functions allow low-level control over stdin/out/err of the cgi.
3902 * However for most cases, binding the cgi to http in and out, the default
3903 * lws implementation already does the right thing.
3906 enum lws_enum_stdinouterr {
3912 enum lws_cgi_hdr_state {
3922 struct lws_cgi_args {
3923 struct lws **stdwsi; /**< get fd with lws_get_socket_fd() */
3924 enum lws_enum_stdinouterr ch; /**< channel index */
3925 unsigned char *data; /**< for messages with payload */
3926 enum lws_cgi_hdr_state hdr_state; /**< track where we are in cgi headers */
3927 int len; /**< length */
3932 * lws_cgi: spawn network-connected cgi process
3934 * \param wsi: connection to own the process
3935 * \param exec_array: array of "exec-name" "arg1" ... "argn" NULL
3936 * \param script_uri_path_len: how many chars on the left of the uri are the path to the cgi
3937 * \param timeout_secs: seconds script should be allowed to run
3938 * \param mp_cgienv: pvo list with per-vhost cgi options to put in env
3940 LWS_VISIBLE LWS_EXTERN int
3941 lws_cgi(struct lws *wsi, const char * const *exec_array,
3942 int script_uri_path_len, int timeout_secs,
3943 const struct lws_protocol_vhost_options *mp_cgienv);
3946 * lws_cgi_write_split_stdout_headers: write cgi output accounting for header part
3948 * \param wsi: connection to own the process
3950 LWS_VISIBLE LWS_EXTERN int
3951 lws_cgi_write_split_stdout_headers(struct lws *wsi);
3954 * lws_cgi_kill: terminate cgi process associated with wsi
3956 * \param wsi: connection to own the process
3958 LWS_VISIBLE LWS_EXTERN int
3959 lws_cgi_kill(struct lws *wsi);
3964 /*! \defgroup fops file operation wrapping
3966 * ##File operation wrapping
3968 * Use these helper functions if you want to access a file from the perspective
3969 * of a specific wsi, which is usually the case. If you just want contextless
3970 * file access, use the fops callbacks directly with NULL wsi instead of these
3973 * If so, then it calls the platform handler or user overrides where present
3974 * (as defined in info->fops)
3976 * The advantage from all this is user code can be portable for file operations
3977 * without having to deal with differences between platforms.
3981 /** struct lws_plat_file_ops - Platform-specific file operations
3983 * These provide platform-agnostic ways to deal with filesystem access in the
3984 * library and in the user code.
3986 struct lws_plat_file_ops {
3987 lws_filefd_type (*open)(struct lws *wsi, const char *filename,
3988 unsigned long *filelen, int flags);
3989 /**< Open file (always binary access if plat supports it)
3990 * filelen is filled on exit to be the length of the file
3991 * flags should be set to O_RDONLY or O_RDWR */
3992 int (*close)(struct lws *wsi, lws_filefd_type fd);
3994 unsigned long (*seek_cur)(struct lws *wsi, lws_filefd_type fd,
3995 long offset_from_cur_pos);
3996 /**< seek from current position */
3997 int (*read)(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
3998 unsigned char *buf, unsigned long len);
3999 /**< Read from file, on exit *amount is set to amount actually read */
4000 int (*write)(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
4001 unsigned char *buf, unsigned long len);
4002 /**< Write to file, on exit *amount is set to amount actually written */
4004 /* Add new things just above here ---^
4005 * This is part of the ABI, don't needlessly break compatibility */
4009 * lws_get_fops() - get current file ops
4011 * \param context: context
4013 LWS_VISIBLE LWS_EXTERN struct lws_plat_file_ops * LWS_WARN_UNUSED_RESULT
4014 lws_get_fops(struct lws_context *context);
4017 * lws_plat_file_open() - file open operations
4019 * \param wsi: connection doing the opening
4020 * \param filename: filename to open
4021 * \param filelen: length of file (filled in by call)
4022 * \param flags: open flags
4024 static LWS_INLINE lws_filefd_type LWS_WARN_UNUSED_RESULT
4025 lws_plat_file_open(struct lws *wsi, const char *filename,
4026 unsigned long *filelen, int flags)
4028 return lws_get_fops(lws_get_context(wsi))->open(wsi, filename,
4033 * lws_plat_file_close() - close file
4035 * \param wsi: connection opened by
4036 * \param fd: file descriptor
4038 static LWS_INLINE int
4039 lws_plat_file_close(struct lws *wsi, lws_filefd_type fd)
4041 return lws_get_fops(lws_get_context(wsi))->close(wsi, fd);
4045 * lws_plat_file_seek_cur() - close file
4047 * \param wsi: connection opened by
4048 * \param fd: file descriptor
4049 * \param offset: position to seek to
4051 static LWS_INLINE unsigned long
4052 lws_plat_file_seek_cur(struct lws *wsi, lws_filefd_type fd, long offset)
4054 return lws_get_fops(lws_get_context(wsi))->seek_cur(wsi, fd, offset);
4057 * lws_plat_file_read() - read from file
4059 * \param wsi: connection opened by
4060 * \param fd: file descriptor
4061 * \param amount: how much to read (rewritten by call)
4062 * \param buf: buffer to write to
4063 * \param len: max length
4065 static LWS_INLINE int LWS_WARN_UNUSED_RESULT
4066 lws_plat_file_read(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
4067 unsigned char *buf, unsigned long len)
4069 return lws_get_fops(lws_get_context(wsi))->read(wsi, fd, amount, buf,
4073 * lws_plat_file_write() - write from file
4075 * \param wsi: connection opened by
4076 * \param fd: file descriptor
4077 * \param amount: how much to write (rewritten by call)
4078 * \param buf: buffer to read from
4079 * \param len: max length
4081 static LWS_INLINE int LWS_WARN_UNUSED_RESULT
4082 lws_plat_file_write(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
4083 unsigned char *buf, unsigned long len)
4085 return lws_get_fops(lws_get_context(wsi))->write(wsi, fd, amount, buf,
4092 * ##SMTP related functions
4094 * These apis let you communicate with a local SMTP server to send email from
4095 * lws. It handles all the SMTP sequencing and protocol actions.
4097 * Your system should have postfix, sendmail or another MTA listening on port
4098 * 25 and able to send email using the "mail" commandline app. Usually distro
4099 * MTAs are configured for this by default.
4101 * It runs via its own libuv events if initialized (which requires giving it
4102 * a libuv loop to attach to).
4104 * It operates using three callbacks, on_next() queries if there is a new email
4105 * to send, on_get_body() asks for the body of the email, and on_sent() is
4106 * called after the email is successfully sent.
4110 * - create an lws_email struct
4112 * - initialize data, loop, the email_* strings, max_content_size and
4115 * - call lws_email_init()
4117 * When you have at least one email to send, call lws_email_check() to
4118 * schedule starting to send it.
4121 #ifdef LWS_WITH_SMTP
4123 /** enum lwsgs_smtp_states - where we are in SMTP protocol sequence */
4124 enum lwsgs_smtp_states {
4125 LGSSMTP_IDLE, /**< awaiting new email */
4126 LGSSMTP_CONNECTING, /**< opening tcp connection to MTA */
4127 LGSSMTP_CONNECTED, /**< tcp connection to MTA is connected */
4128 LGSSMTP_SENT_HELO, /**< sent the HELO */
4129 LGSSMTP_SENT_FROM, /**< sent FROM */
4130 LGSSMTP_SENT_TO, /**< sent TO */
4131 LGSSMTP_SENT_DATA, /**< sent DATA request */
4132 LGSSMTP_SENT_BODY, /**< sent the email body */
4133 LGSSMTP_SENT_QUIT, /**< sent the session quit */
4136 /** struct lws_email - abstract context for performing SMTP operations */
4139 /**< opaque pointer set by user code and available to the callbacks */
4141 /**< the libuv loop we will work on */
4143 char email_smtp_ip[32]; /**< Fill before init, eg, "127.0.0.1" */
4144 char email_helo[32]; /**< Fill before init, eg, "myserver.com" */
4145 char email_from[100]; /**< Fill before init or on_next */
4146 char email_to[100]; /**< Fill before init or on_next */
4148 unsigned int max_content_size;
4149 /**< largest possible email body size */
4151 /* Fill all the callbacks before init */
4153 int (*on_next)(struct lws_email *email);
4154 /**< (Fill in before calling lws_email_init)
4155 * called when idle, 0 = another email to send, nonzero is idle.
4156 * If you return 0, all of the email_* char arrays must be set
4157 * to something useful. */
4158 int (*on_sent)(struct lws_email *email);
4159 /**< (Fill in before calling lws_email_init)
4160 * called when transfer of the email to the SMTP server was
4161 * successful, your callback would remove the current email
4163 int (*on_get_body)(struct lws_email *email, char *buf, int len);
4164 /**< (Fill in before calling lws_email_init)
4165 * called when the body part of the queued email is about to be
4166 * sent to the SMTP server. */
4169 /* private things */
4170 uv_timer_t timeout_email; /**< private */
4171 enum lwsgs_smtp_states estate; /**< private */
4172 uv_connect_t email_connect_req; /**< private */
4173 uv_tcp_t email_client; /**< private */
4174 time_t email_connect_started; /**< private */
4175 char email_buf[256]; /**< private */
4176 char *content; /**< private */
4180 * lws_email_init() - Initialize a struct lws_email
4182 * \param email: struct lws_email to init
4183 * \param loop: libuv loop to use
4184 * \param max_content: max email content size
4186 * Prepares a struct lws_email for use ending SMTP
4188 LWS_VISIBLE LWS_EXTERN int
4189 lws_email_init(struct lws_email *email, uv_loop_t *loop, int max_content);
4192 * lws_email_check() - Request check for new email
4194 * \param email: struct lws_email context to check
4196 * Schedules a check for new emails in 1s... call this when you have queued an
4199 LWS_VISIBLE LWS_EXTERN void
4200 lws_email_check(struct lws_email *email);
4202 * lws_email_destroy() - stop using the struct lws_email
4204 * \param email: the struct lws_email context
4206 * Stop sending email using email and free allocations
4208 LWS_VISIBLE LWS_EXTERN void
4209 lws_email_destroy(struct lws_email *email);