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
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(_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() { 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 /* Add new things just above here ---^
1712 * This is part of the ABI, don't needlessly break compatibility
1714 * The below is to ensure later library versions with new
1715 * members added above will see 0 (default) even if the app
1716 * was not built against the newer headers.
1719 void *_unused[8]; /**< dummy */
1723 * lws_create_context() - Create the websocket handler
1724 * \param info: pointer to struct with parameters
1726 * This function creates the listening socket (if serving) and takes care
1727 * of all initialization in one step.
1729 * If option LWS_SERVER_OPTION_EXPLICIT_VHOSTS is given, no vhost is
1730 * created; you're expected to create your own vhosts afterwards using
1731 * lws_create_vhost(). Otherwise a vhost named "default" is also created
1732 * using the information in the vhost-related members, for compatibility.
1734 * After initialization, it returns a struct lws_context * that
1735 * represents this server. After calling, user code needs to take care
1736 * of calling lws_service() with the context pointer to get the
1737 * server's sockets serviced. This must be done in the same process
1738 * context as the initialization call.
1740 * The protocol callback functions are called for a handful of events
1741 * including http requests coming in, websocket connections becoming
1742 * established, and data arriving; it's also called periodically to allow
1743 * async transmission.
1745 * HTTP requests are sent always to the FIRST protocol in protocol, since
1746 * at that time websocket protocol has not been negotiated. Other
1747 * protocols after the first one never see any HTTP callack activity.
1749 * The server created is a simple http server by default; part of the
1750 * websocket standard is upgrading this http connection to a websocket one.
1752 * This allows the same server to provide files like scripts and favicon /
1753 * images or whatever over http and dynamic data over websockets all in
1754 * one place; they're all handled in the user callback.
1756 LWS_VISIBLE LWS_EXTERN struct lws_context *
1757 lws_create_context(struct lws_context_creation_info *info);
1760 * lws_context_destroy() - Destroy the websocket context
1761 * \param context: Websocket context
1763 * This function closes any active connections and then frees the
1764 * context. After calling this, any further use of the context is
1767 LWS_VISIBLE LWS_EXTERN void
1768 lws_context_destroy(struct lws_context *context);
1771 * lws_set_proxy() - Setups proxy to lws_context.
1772 * \param vhost: pointer to struct lws_vhost you want set proxy for
1773 * \param proxy: pointer to c string containing proxy in format address:port
1775 * Returns 0 if proxy string was parsed and proxy was setup.
1776 * Returns -1 if proxy is NULL or has incorrect format.
1778 * This is only required if your OS does not provide the http_proxy
1779 * environment variable (eg, OSX)
1781 * IMPORTANT! You should call this function right after creation of the
1782 * lws_context and before call to connect. If you call this
1783 * function after connect behavior is undefined.
1784 * This function will override proxy settings made on lws_context
1785 * creation with genenv() call.
1787 LWS_VISIBLE LWS_EXTERN int
1788 lws_set_proxy(struct lws_vhost *vhost, const char *proxy);
1794 * lws_create_vhost() - Create a vhost (virtual server context)
1795 * \param context: pointer to result of lws_create_context()
1796 * \param info: pointer to struct with parameters
1798 * This function creates a virtual server (vhost) using the vhost-related
1799 * members of the info struct. You can create many vhosts inside one context
1800 * if you created the context with the option LWS_SERVER_OPTION_EXPLICIT_VHOSTS
1802 LWS_EXTERN LWS_VISIBLE struct lws_vhost *
1803 lws_create_vhost(struct lws_context *context,
1804 struct lws_context_creation_info *info);
1807 * lwsws_get_config_globals() - Parse a JSON server config file
1808 * \param info: pointer to struct with parameters
1809 * \param d: filepath of the config file
1810 * \param config_strings: storage for the config strings extracted from JSON,
1811 * the pointer is incremented as strings are stored
1812 * \param len: pointer to the remaining length left in config_strings
1813 * the value is decremented as strings are stored
1815 * This function prepares a n lws_context_creation_info struct with global
1816 * settings from a file d.
1818 * Requires CMake option LWS_WITH_LEJP_CONF to have been enabled
1820 LWS_VISIBLE LWS_EXTERN int
1821 lwsws_get_config_globals(struct lws_context_creation_info *info, const char *d,
1822 char **config_strings, int *len);
1825 * lwsws_get_config_vhosts() - Create vhosts from a JSON server config file
1826 * \param context: pointer to result of lws_create_context()
1827 * \param info: pointer to struct with parameters
1828 * \param d: filepath of the config file
1829 * \param config_strings: storage for the config strings extracted from JSON,
1830 * the pointer is incremented as strings are stored
1831 * \param len: pointer to the remaining length left in config_strings
1832 * the value is decremented as strings are stored
1834 * This function creates vhosts into a context according to the settings in
1835 *JSON files found in directory d.
1837 * Requires CMake option LWS_WITH_LEJP_CONF to have been enabled
1839 LWS_VISIBLE LWS_EXTERN int
1840 lwsws_get_config_vhosts(struct lws_context *context,
1841 struct lws_context_creation_info *info, const char *d,
1842 char **config_strings, int *len);
1844 /** lws_vhost_get() - \deprecated deprecated: use lws_get_vhost() */
1845 LWS_VISIBLE LWS_EXTERN struct lws_vhost *
1846 lws_vhost_get(struct lws *wsi) LWS_WARN_DEPRECATED;
1849 * lws_get_vhost() - return the vhost a wsi belongs to
1851 * \param wsi: which connection
1853 LWS_VISIBLE LWS_EXTERN struct lws_vhost *
1854 lws_get_vhost(struct lws *wsi);
1857 * lws_json_dump_vhost() - describe vhost state and stats in JSON
1859 * \param vh: the vhost
1860 * \param buf: buffer to fill with JSON
1861 * \param len: max length of buf
1863 LWS_VISIBLE LWS_EXTERN int
1864 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len);
1867 * lws_json_dump_context() - describe context state and stats in JSON
1869 * \param context: the context
1870 * \param buf: buffer to fill with JSON
1871 * \param len: max length of buf
1873 LWS_VISIBLE LWS_EXTERN int
1874 lws_json_dump_context(const struct lws_context *context, char *buf, int len);
1877 * lws_context_user() - get the user data associated with the context
1878 * \param context: Websocket context
1880 * This returns the optional user allocation that can be attached to
1881 * the context the sockets live in at context_create time. It's a way
1882 * to let all sockets serviced in the same context share data without
1883 * using globals statics in the user code.
1885 LWS_VISIBLE LWS_EXTERN void *
1886 lws_context_user(struct lws_context *context);
1888 /*! \defgroup vhost-mounts Vhost mounts and options
1889 * \ingroup context-and-vhost-creation
1891 * ##Vhost mounts and options
1894 /** struct lws_protocol_vhost_options - linked list of per-vhost protocol
1895 * name=value options
1897 * This provides a general way to attach a linked-list of name=value pairs,
1898 * which can also have an optional child link-list using the options member.
1900 struct lws_protocol_vhost_options {
1901 const struct lws_protocol_vhost_options *next; /**< linked list */
1902 const struct lws_protocol_vhost_options *options; /**< child linked-list of more options for this node */
1903 const char *name; /**< name of name=value pair */
1904 const char *value; /**< value of name=value pair */
1907 /** enum lws_mount_protocols
1908 * This specifies the mount protocol for a mountpoint, whether it is to be
1909 * served from a filesystem, or it is a cgi etc.
1911 enum lws_mount_protocols {
1912 LWSMPRO_HTTP = 0, /**< not supported yet */
1913 LWSMPRO_HTTPS = 1, /**< not supported yet */
1914 LWSMPRO_FILE = 2, /**< serve from filesystem directory */
1915 LWSMPRO_CGI = 3, /**< pass to CGI to handle */
1916 LWSMPRO_REDIR_HTTP = 4, /**< redirect to http:// url */
1917 LWSMPRO_REDIR_HTTPS = 5, /**< redirect to https:// url */
1918 LWSMPRO_CALLBACK = 6, /**< hand by named protocol's callback */
1921 /** struct lws_http_mount
1923 * arguments for mounting something in a vhost's url namespace
1925 struct lws_http_mount {
1926 const struct lws_http_mount *mount_next;
1927 /**< pointer to next struct lws_http_mount */
1928 const char *mountpoint;
1929 /**< mountpoint in http pathspace, eg, "/" */
1931 /**< path to be mounted, eg, "/var/www/warmcat.com" */
1933 /**< default target, eg, "index.html" */
1934 const char *protocol;
1935 /**<"protocol-name" to handle mount */
1937 const struct lws_protocol_vhost_options *cgienv;
1938 /**< optional linked-list of cgi options. These are created
1939 * as environment variables for the cgi process
1941 const struct lws_protocol_vhost_options *extra_mimetypes;
1942 /**< optional linked-list of mimetype mappings */
1943 const struct lws_protocol_vhost_options *interpret;
1944 /**< optional linked-list of files to be interpreted */
1947 /**< seconds cgi is allowed to live, if cgi://mount type */
1949 /**< max-age for reuse of client cache of files, seconds */
1950 unsigned int auth_mask;
1951 /**< bits set here must be set for authorized client session */
1953 unsigned int cache_reusable:1; /**< set if client cache may reuse this */
1954 unsigned int cache_revalidate:1; /**< set if client cache should revalidate on use */
1955 unsigned int cache_intermediaries:1; /**< set if intermediaries are allowed to cache */
1957 unsigned char origin_protocol; /**< one of enum lws_mount_protocols */
1958 unsigned char mountpoint_len; /**< length of mountpoint string */
1963 /*! \defgroup client
1966 * ##Client releated functions
1970 /** enum lws_client_connect_ssl_connection_flags - flags that may be used
1971 * with struct lws_client_connect_info ssl_connection member to control if
1972 * and how SSL checks apply to the client connection being created
1975 enum lws_client_connect_ssl_connection_flags {
1976 LCCSCF_USE_SSL = (1 << 0),
1977 LCCSCF_ALLOW_SELFSIGNED = (1 << 1),
1978 LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK = (1 << 2)
1981 /** struct lws_client_connect_info - parameters to connect with when using
1982 * lws_client_connect_via_info() */
1984 struct lws_client_connect_info {
1985 struct lws_context *context;
1986 /**< lws context to create connection in */
1987 const char *address;
1988 /**< remote address to connect to */
1990 /**< remote port to connect to */
1992 /**< nonzero for ssl */
1996 /**< content of host header */
1998 /**< content of origin header */
1999 const char *protocol;
2000 /**< list of ws protocols we could accept */
2001 int ietf_version_or_minus_one;
2002 /**< deprecated: currently leave at 0 or -1 */
2004 /**< if non-NULL, use this as wsi user_data instead of malloc it */
2005 const struct lws_extension *client_exts;
2006 /**< array of extensions that may be used on connection */
2008 /**< if non-NULL, do this http method instead of ws[s] upgrade.
2009 * use "GET" to be a simple http client connection */
2010 struct lws *parent_wsi;
2011 /**< if another wsi is responsible for this connection, give it here.
2012 * this is used to make sure if the parent closes so do any
2013 * child connections first. */
2014 const char *uri_replace_from;
2015 /**< if non-NULL, when this string is found in URIs in
2016 * text/html content-encoding, it's replaced with uri_replace_to */
2017 const char *uri_replace_to;
2018 /**< see uri_replace_from */
2019 struct lws_vhost *vhost;
2020 /**< vhost to bind to (used to determine related SSL_CTX) */
2022 /**< if not NULL, store the new wsi here early in the connection
2023 * process. Although we return the new wsi, the call to create the
2024 * client connection does progress the connection somewhat and may
2025 * meet an error that will result in the connection being scrubbed and
2026 * NULL returned. While the wsi exists though, he may process a
2027 * callback like CLIENT_CONNECTION_ERROR with his wsi: this gives the
2028 * user callback a way to identify which wsi it is that faced the error
2029 * even before the new wsi is returned and even if ultimately no wsi
2033 /* Add new things just above here ---^
2034 * This is part of the ABI, don't needlessly break compatibility
2036 * The below is to ensure later library versions with new
2037 * members added above will see 0 (default) even if the app
2038 * was not built against the newer headers.
2041 void *_unused[4]; /**< dummy */
2045 * lws_client_connect_via_info() - Connect to another websocket server
2046 * \param ccinfo: pointer to lws_client_connect_info struct
2048 * This function creates a connection to a remote server using the
2049 * information provided in ccinfo.
2051 LWS_VISIBLE LWS_EXTERN struct lws *
2052 lws_client_connect_via_info(struct lws_client_connect_info * ccinfo);
2055 * lws_client_connect() - Connect to another websocket server
2056 * \deprecated DEPRECATED use lws_client_connect_via_info
2057 * \param clients: Websocket context
2058 * \param address: Remote server address, eg, "myserver.com"
2059 * \param port: Port to connect to on the remote server, eg, 80
2060 * \param ssl_connection: 0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
2062 * \param path: Websocket path on server
2063 * \param host: Hostname on server
2064 * \param origin: Socket origin name
2065 * \param protocol: Comma-separated list of protocols being asked for from
2066 * the server, or just one. The server will pick the one it
2067 * likes best. If you don't want to specify a protocol, which is
2068 * legal, use NULL here.
2069 * \param ietf_version_or_minus_one: -1 to ask to connect using the default, latest
2070 * protocol supported, or the specific protocol ordinal
2072 * This function creates a connection to a remote server
2074 /* deprecated, use lws_client_connect_via_info() */
2075 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
2076 lws_client_connect(struct lws_context *clients, const char *address,
2077 int port, int ssl_connection, const char *path,
2078 const char *host, const char *origin, const char *protocol,
2079 int ietf_version_or_minus_one) LWS_WARN_DEPRECATED;
2080 /* deprecated, use lws_client_connect_via_info() */
2082 * lws_client_connect_extended() - Connect to another websocket server
2083 * \deprecated DEPRECATED use lws_client_connect_via_info
2084 * \param clients: Websocket context
2085 * \param address: Remote server address, eg, "myserver.com"
2086 * \param port: Port to connect to on the remote server, eg, 80
2087 * \param ssl_connection: 0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
2089 * \param path: Websocket path on server
2090 * \param host: Hostname on server
2091 * \param origin: Socket origin name
2092 * \param protocol: Comma-separated list of protocols being asked for from
2093 * the server, or just one. The server will pick the one it
2095 * \param ietf_version_or_minus_one: -1 to ask to connect using the default, latest
2096 * protocol supported, or the specific protocol ordinal
2097 * \param userdata: Pre-allocated user data
2099 * This function creates a connection to a remote server
2101 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
2102 lws_client_connect_extended(struct lws_context *clients, const char *address,
2103 int port, int ssl_connection, const char *path,
2104 const char *host, const char *origin,
2105 const char *protocol, int ietf_version_or_minus_one,
2106 void *userdata) LWS_WARN_DEPRECATED;
2109 * lws_init_vhost_client_ssl() - also enable client SSL on an existing vhost
2111 * \param info: client ssl related info
2112 * \param vhost: which vhost to initialize client ssl operations on
2114 * You only need to call this if you plan on using SSL client connections on
2115 * the vhost. For non-SSL client connections, it's not necessary to call this.
2117 * The following members of info are used during the call
2119 * - options must have LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT set,
2120 * otherwise the call does nothing
2121 * - provided_client_ssl_ctx must be NULL to get a generated client
2122 * ssl context, otherwise you can pass a prepared one in by setting it
2123 * - ssl_cipher_list may be NULL or set to the client valid cipher list
2124 * - ssl_ca_filepath may be NULL or client cert filepath
2125 * - ssl_cert_filepath may be NULL or client cert filepath
2126 * - ssl_private_key_filepath may be NULL or client cert private key
2128 * You must create your vhost explicitly if you want to use this, so you have
2129 * a pointer to the vhost. Create the context first with the option flag
2130 * LWS_SERVER_OPTION_EXPLICIT_VHOSTS and then call lws_create_vhost() with
2131 * the same info struct.
2133 LWS_VISIBLE LWS_EXTERN int
2134 lws_init_vhost_client_ssl(const struct lws_context_creation_info *info,
2135 struct lws_vhost *vhost);
2137 LWS_VISIBLE LWS_EXTERN int
2138 lws_http_client_read(struct lws *wsi, char **buf, int *len);
2140 LWS_VISIBLE LWS_EXTERN void
2141 lws_client_http_body_pending(struct lws *wsi, int something_left_to_send);
2144 * lws_client_http_body_pending() - control if client connection neeeds to send body
2146 * \param wsi: client connection
2147 * \param something_left_to_send: nonzero if need to send more body, 0 (default)
2148 * if nothing more to send
2150 * If you will send payload data with your HTTP client connection, eg, for POST,
2151 * when you set the related http headers in
2152 * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER callback you should also call
2153 * this API with something_left_to_send nonzero, and call
2154 * lws_callback_on_writable(wsi);
2156 * After sending the headers, lws will call your callback with
2157 * LWS_CALLBACK_CLIENT_HTTP_WRITEABLE reason when writable. You can send the
2158 * next part of the http body payload, calling lws_callback_on_writable(wsi);
2159 * if there is more to come, or lws_client_http_body_pending(wsi, 0); to
2160 * let lws know the last part is sent and the connection can move on.
2165 /** \defgroup service Built-in service loop entry
2167 * ##Built-in service loop entry
2169 * If you're not using libev / libuv, these apis are needed to enter the poll()
2170 * wait in lws and service any connections with pending events.
2175 * lws_service() - Service any pending websocket activity
2176 * \param context: Websocket context
2177 * \param timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
2178 * service otherwise block and service immediately, returning
2179 * after the timeout if nothing needed service.
2181 * This function deals with any pending websocket traffic, for three
2182 * kinds of event. It handles these events on both server and client
2183 * types of connection the same.
2185 * 1) Accept new connections to our context's server
2187 * 2) Call the receive callback for incoming frame data received by
2188 * server or client connections.
2190 * You need to call this service function periodically to all the above
2191 * functions to happen; if your application is single-threaded you can
2192 * just call it in your main event loop.
2194 * Alternatively you can fork a new process that asynchronously handles
2195 * calling this service in a loop. In that case you are happy if this
2196 * call blocks your thread until it needs to take care of something and
2197 * would call it with a large nonzero timeout. Your loop then takes no
2198 * CPU while there is nothing happening.
2200 * If you are calling it in a single-threaded app, you don't want it to
2201 * wait around blocking other things in your loop from happening, so you
2202 * would call it with a timeout_ms of 0, so it returns immediately if
2203 * nothing is pending, or as soon as it services whatever was pending.
2205 LWS_VISIBLE LWS_EXTERN int
2206 lws_service(struct lws_context *context, int timeout_ms);
2209 * lws_service() - Service any pending websocket activity
2211 * \param context: Websocket context
2212 * \param timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
2213 * service otherwise block and service immediately, returning
2214 * after the timeout if nothing needed service.
2216 * Same as lws_service(), but for a specific thread service index. Only needed
2217 * if you are spawning multiple service threads.
2219 LWS_VISIBLE LWS_EXTERN int
2220 lws_service_tsi(struct lws_context *context, int timeout_ms, int tsi);
2223 * lws_cancel_service_pt() - Cancel servicing of pending socket activity
2225 * \param wsi: Cancel service on the thread this wsi is serviced by
2227 * This function lets a call to lws_service() waiting for a timeout
2228 * immediately return.
2230 * It works by creating a phony event and then swallowing it silently.
2232 * The reason it may be needed is when waiting in poll(), changes to
2233 * the event masks are ignored by the OS until poll() is reentered. This
2234 * lets you halt the poll() wait and make the reentry happen immediately
2235 * instead of having the wait out the rest of the poll timeout.
2237 LWS_VISIBLE LWS_EXTERN void
2238 lws_cancel_service_pt(struct lws *wsi);
2241 * lws_cancel_service() - Cancel wait for new pending socket activity
2242 * \param context: Websocket context
2244 * This function let a call to lws_service() waiting for a timeout
2245 * immediately return.
2247 * What it basically does is provide a fake event that will be swallowed,
2248 * so the wait in poll() is ended. That's useful because poll() doesn't
2249 * attend to changes in POLLIN/OUT/ERR until it re-enters the wait.
2251 LWS_VISIBLE LWS_EXTERN void
2252 lws_cancel_service(struct lws_context *context);
2255 * lws_service_fd() - Service polled socket with something waiting
2256 * \param context: Websocket context
2257 * \param pollfd: The pollfd entry describing the socket fd and which events
2258 * happened, or NULL to tell lws to do only timeout servicing.
2260 * This function takes a pollfd that has POLLIN or POLLOUT activity and
2261 * services it according to the state of the associated
2264 * The one call deals with all "service" that might happen on a socket
2265 * including listen accepts, http files as well as websocket protocol.
2267 * If a pollfd says it has something, you can just pass it to
2268 * lws_service_fd() whether it is a socket handled by lws or not.
2269 * If it sees it is a lws socket, the traffic will be handled and
2270 * pollfd->revents will be zeroed now.
2272 * If the socket is foreign to lws, it leaves revents alone. So you can
2273 * see if you should service yourself by checking the pollfd revents
2274 * after letting lws try to service it.
2276 * You should also call this with pollfd = NULL to just allow the
2277 * once-per-second global timeout checks; if less than a second since the last
2278 * check it returns immediately then.
2280 LWS_VISIBLE LWS_EXTERN int
2281 lws_service_fd(struct lws_context *context, struct lws_pollfd *pollfd);
2284 * lws_service_fd_tsi() - Service polled socket in specific service thread
2285 * \param context: Websocket context
2286 * \param pollfd: The pollfd entry describing the socket fd and which events
2288 * \param tsi: thread service index
2290 * Same as lws_service_fd() but used with multiple service threads
2292 LWS_VISIBLE LWS_EXTERN int
2293 lws_service_fd_tsi(struct lws_context *context, struct lws_pollfd *pollfd,
2297 * lws_service_adjust_timeout() - Check for any connection needing forced service
2298 * \param context: Websocket context
2299 * \param timeout_ms: The original poll timeout value. You can just set this
2300 * to 1 if you don't really have a poll timeout.
2301 * \param tsi: thread service index
2303 * Under some conditions connections may need service even though there is no
2304 * pending network action on them, this is "forced service". For default
2305 * poll() and libuv / libev, the library takes care of calling this and
2306 * dealing with it for you. But for external poll() integration, you need
2307 * access to the apis.
2309 * If anybody needs "forced service", returned timeout is zero. In that case,
2310 * you can call lws_plat_service_tsi() with a timeout of -1 to only service
2311 * guys who need forced service.
2313 LWS_VISIBLE LWS_EXTERN int
2314 lws_service_adjust_timeout(struct lws_context *context, int timeout_ms, int tsi);
2317 * lws_plat_service_tsi() - Lowlevel platform-specific service api
2318 * \param context: Websocket context
2319 * \param timeout_ms: The original poll timeout value. You can just set this
2320 * to 1 if you don't really have a poll timeout.
2321 * \param tsi: thread service index
2323 * For default poll() and libuv/ev, lws takes care of using this for you. and
2324 * you can ignore it.
2326 * But for external poll() integration, you need access to this api to service
2327 * connections that need to be serviced but have no pending network activity.
2329 * See lws_service_adjust_timeout() for more info.
2331 LWS_EXTERN LWS_VISIBLE int
2332 lws_plat_service_tsi(struct lws_context *context, int timeout_ms, int tsi);
2336 /*! \defgroup http HTTP
2338 Modules related to handling HTTP
2342 /*! \defgroup httpft HTTP File transfer
2345 APIs for sending local files in response to HTTP requests
2350 * lws_get_mimetype() - Determine mimetype to use from filename
2352 * \param file: filename
2353 * \param m: NULL, or mount context
2355 * This uses a canned list of known filetypes first, if no match and m is
2356 * non-NULL, then tries a list of per-mount file suffix to mimtype mappings.
2358 * Returns either NULL or a pointer to the mimetype matching the file.
2360 LWS_VISIBLE LWS_EXTERN const char *
2361 lws_get_mimetype(const char *file, const struct lws_http_mount *m);
2364 * lws_serve_http_file() - Send a file back to the client using http
2365 * \param wsi: Websocket instance (available from user callback)
2366 * \param file: The file to issue over http
2367 * \param content_type: The http content type, eg, text/html
2368 * \param other_headers: NULL or pointer to header string
2369 * \param other_headers_len: length of the other headers if non-NULL
2371 * This function is intended to be called from the callback in response
2372 * to http requests from the client. It allows the callback to issue
2373 * local files down the http link in a single step.
2375 * Returning <0 indicates error and the wsi should be closed. Returning
2376 * >0 indicates the file was completely sent and
2377 * lws_http_transaction_completed() called on the wsi (and close if != 0)
2378 * ==0 indicates the file transfer is started and needs more service later,
2379 * the wsi should be left alone.
2381 LWS_VISIBLE LWS_EXTERN int
2382 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
2383 const char *other_headers, int other_headers_len);
2384 LWS_VISIBLE LWS_EXTERN int
2385 lws_serve_http_file_fragment(struct lws *wsi);
2388 /*! \defgroup html-chunked-substitution HTML Chunked Substitution
2391 * ##HTML chunked Substitution
2393 * APIs for receiving chunks of text, replacing a set of variable names via
2394 * a callback, and then prepending and appending HTML chunked encoding
2400 HTTP_STATUS_OK = 200,
2401 HTTP_STATUS_NO_CONTENT = 204,
2403 HTTP_STATUS_MOVED_PERMANENTLY = 301,
2404 HTTP_STATUS_FOUND = 302,
2405 HTTP_STATUS_SEE_OTHER = 303,
2407 HTTP_STATUS_BAD_REQUEST = 400,
2408 HTTP_STATUS_UNAUTHORIZED,
2409 HTTP_STATUS_PAYMENT_REQUIRED,
2410 HTTP_STATUS_FORBIDDEN,
2411 HTTP_STATUS_NOT_FOUND,
2412 HTTP_STATUS_METHOD_NOT_ALLOWED,
2413 HTTP_STATUS_NOT_ACCEPTABLE,
2414 HTTP_STATUS_PROXY_AUTH_REQUIRED,
2415 HTTP_STATUS_REQUEST_TIMEOUT,
2416 HTTP_STATUS_CONFLICT,
2418 HTTP_STATUS_LENGTH_REQUIRED,
2419 HTTP_STATUS_PRECONDITION_FAILED,
2420 HTTP_STATUS_REQ_ENTITY_TOO_LARGE,
2421 HTTP_STATUS_REQ_URI_TOO_LONG,
2422 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE,
2423 HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE,
2424 HTTP_STATUS_EXPECTATION_FAILED,
2426 HTTP_STATUS_INTERNAL_SERVER_ERROR = 500,
2427 HTTP_STATUS_NOT_IMPLEMENTED,
2428 HTTP_STATUS_BAD_GATEWAY,
2429 HTTP_STATUS_SERVICE_UNAVAILABLE,
2430 HTTP_STATUS_GATEWAY_TIMEOUT,
2431 HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED,
2434 struct lws_process_html_args {
2435 char *p; /**< pointer to the buffer containing the data */
2436 int len; /**< length of the original data at p */
2437 int max_len; /**< maximum length we can grow the data to */
2438 int final; /**< set if this is the last chunk of the file */
2441 typedef const char *(*lws_process_html_state_cb)(void *data, int index);
2443 struct lws_process_html_state {
2444 char *start; /**< pointer to start of match */
2445 char swallow[16]; /**< matched character buffer */
2446 int pos; /**< position in match */
2447 void *data; /**< opaque pointer */
2448 const char * const *vars; /**< list of variable names */
2449 int count_vars; /**< count of variable names */
2451 lws_process_html_state_cb replace; /**< called on match to perform substitution */
2454 /*! lws_chunked_html_process() - generic chunked substitution
2455 * \param args: buffer to process using chunked encoding
2456 * \param s: current processing state
2458 LWS_VISIBLE LWS_EXTERN int
2459 lws_chunked_html_process(struct lws_process_html_args *args,
2460 struct lws_process_html_state *s);
2463 /** \defgroup HTTP-headers-read HTTP headers: read
2466 * ##HTTP header releated functions
2468 * In lws the client http headers are temporarily stored in a pool, only for the
2469 * duration of the http part of the handshake. It's because in most cases,
2470 * the header content is ignored for the whole rest of the connection lifetime
2471 * and would then just be taking up space needlessly.
2473 * During LWS_CALLBACK_HTTP when the URI path is delivered is the last time
2474 * the http headers are still allocated, you can use these apis then to
2475 * look at and copy out interesting header content (cookies, etc)
2477 * Notice that the header total length reported does not include a terminating
2478 * '\0', however you must allocate for it when using the _copy apis. So the
2479 * length reported for a header containing "123" is 3, but you must provide
2480 * a buffer of length 4 so that "123\0" may be copied into it, or the copy
2481 * will fail with a nonzero return code.
2483 * In the special case of URL arguments, like ?x=1&y=2, the arguments are
2484 * stored in a token named for the method, eg, WSI_TOKEN_GET_URI if it
2485 * was a GET or WSI_TOKEN_POST_URI if POST. You can check the total
2486 * length to confirm the method.
2488 * For URL arguments, each argument is stored urldecoded in a "fragment", so
2489 * you can use the fragment-aware api lws_hdr_copy_fragment() to access each
2490 * argument in turn: the fragments contain urldecoded strings like x=1 or y=2.
2492 * As a convenience, lws has an api that will find the fragment with a
2493 * given name= part, lws_get_urlarg_by_name().
2497 /** struct lws_tokens
2498 * you need these to look at headers that have been parsed if using the
2499 * LWS_CALLBACK_FILTER_CONNECTION callback. If a header from the enum
2500 * list below is absent, .token = NULL and token_len = 0. Otherwise .token
2501 * points to .token_len chars containing that header content.
2504 char *token; /**< pointer to start of the token */
2505 int token_len; /**< length of the token's value */
2508 /* enum lws_token_indexes
2509 * these have to be kept in sync with lextable.h / minilex.c
2511 * NOTE: These public enums are part of the abi. If you want to add one,
2512 * add it at where specified so existing users are unaffected.
2514 enum lws_token_indexes {
2515 WSI_TOKEN_GET_URI = 0,
2516 WSI_TOKEN_POST_URI = 1,
2517 WSI_TOKEN_OPTIONS_URI = 2,
2519 WSI_TOKEN_CONNECTION = 4,
2520 WSI_TOKEN_UPGRADE = 5,
2521 WSI_TOKEN_ORIGIN = 6,
2522 WSI_TOKEN_DRAFT = 7,
2523 WSI_TOKEN_CHALLENGE = 8,
2524 WSI_TOKEN_EXTENSIONS = 9,
2525 WSI_TOKEN_KEY1 = 10,
2526 WSI_TOKEN_KEY2 = 11,
2527 WSI_TOKEN_PROTOCOL = 12,
2528 WSI_TOKEN_ACCEPT = 13,
2529 WSI_TOKEN_NONCE = 14,
2530 WSI_TOKEN_HTTP = 15,
2531 WSI_TOKEN_HTTP2_SETTINGS = 16,
2532 WSI_TOKEN_HTTP_ACCEPT = 17,
2533 WSI_TOKEN_HTTP_AC_REQUEST_HEADERS = 18,
2534 WSI_TOKEN_HTTP_IF_MODIFIED_SINCE = 19,
2535 WSI_TOKEN_HTTP_IF_NONE_MATCH = 20,
2536 WSI_TOKEN_HTTP_ACCEPT_ENCODING = 21,
2537 WSI_TOKEN_HTTP_ACCEPT_LANGUAGE = 22,
2538 WSI_TOKEN_HTTP_PRAGMA = 23,
2539 WSI_TOKEN_HTTP_CACHE_CONTROL = 24,
2540 WSI_TOKEN_HTTP_AUTHORIZATION = 25,
2541 WSI_TOKEN_HTTP_COOKIE = 26,
2542 WSI_TOKEN_HTTP_CONTENT_LENGTH = 27,
2543 WSI_TOKEN_HTTP_CONTENT_TYPE = 28,
2544 WSI_TOKEN_HTTP_DATE = 29,
2545 WSI_TOKEN_HTTP_RANGE = 30,
2546 WSI_TOKEN_HTTP_REFERER = 31,
2548 WSI_TOKEN_VERSION = 33,
2549 WSI_TOKEN_SWORIGIN = 34,
2551 WSI_TOKEN_HTTP_COLON_AUTHORITY = 35,
2552 WSI_TOKEN_HTTP_COLON_METHOD = 36,
2553 WSI_TOKEN_HTTP_COLON_PATH = 37,
2554 WSI_TOKEN_HTTP_COLON_SCHEME = 38,
2555 WSI_TOKEN_HTTP_COLON_STATUS = 39,
2557 WSI_TOKEN_HTTP_ACCEPT_CHARSET = 40,
2558 WSI_TOKEN_HTTP_ACCEPT_RANGES = 41,
2559 WSI_TOKEN_HTTP_ACCESS_CONTROL_ALLOW_ORIGIN = 42,
2560 WSI_TOKEN_HTTP_AGE = 43,
2561 WSI_TOKEN_HTTP_ALLOW = 44,
2562 WSI_TOKEN_HTTP_CONTENT_DISPOSITION = 45,
2563 WSI_TOKEN_HTTP_CONTENT_ENCODING = 46,
2564 WSI_TOKEN_HTTP_CONTENT_LANGUAGE = 47,
2565 WSI_TOKEN_HTTP_CONTENT_LOCATION = 48,
2566 WSI_TOKEN_HTTP_CONTENT_RANGE = 49,
2567 WSI_TOKEN_HTTP_ETAG = 50,
2568 WSI_TOKEN_HTTP_EXPECT = 51,
2569 WSI_TOKEN_HTTP_EXPIRES = 52,
2570 WSI_TOKEN_HTTP_FROM = 53,
2571 WSI_TOKEN_HTTP_IF_MATCH = 54,
2572 WSI_TOKEN_HTTP_IF_RANGE = 55,
2573 WSI_TOKEN_HTTP_IF_UNMODIFIED_SINCE = 56,
2574 WSI_TOKEN_HTTP_LAST_MODIFIED = 57,
2575 WSI_TOKEN_HTTP_LINK = 58,
2576 WSI_TOKEN_HTTP_LOCATION = 59,
2577 WSI_TOKEN_HTTP_MAX_FORWARDS = 60,
2578 WSI_TOKEN_HTTP_PROXY_AUTHENTICATE = 61,
2579 WSI_TOKEN_HTTP_PROXY_AUTHORIZATION = 62,
2580 WSI_TOKEN_HTTP_REFRESH = 63,
2581 WSI_TOKEN_HTTP_RETRY_AFTER = 64,
2582 WSI_TOKEN_HTTP_SERVER = 65,
2583 WSI_TOKEN_HTTP_SET_COOKIE = 66,
2584 WSI_TOKEN_HTTP_STRICT_TRANSPORT_SECURITY = 67,
2585 WSI_TOKEN_HTTP_TRANSFER_ENCODING = 68,
2586 WSI_TOKEN_HTTP_USER_AGENT = 69,
2587 WSI_TOKEN_HTTP_VARY = 70,
2588 WSI_TOKEN_HTTP_VIA = 71,
2589 WSI_TOKEN_HTTP_WWW_AUTHENTICATE = 72,
2591 WSI_TOKEN_PATCH_URI = 73,
2592 WSI_TOKEN_PUT_URI = 74,
2593 WSI_TOKEN_DELETE_URI = 75,
2595 WSI_TOKEN_HTTP_URI_ARGS = 76,
2596 WSI_TOKEN_PROXY = 77,
2597 WSI_TOKEN_HTTP_X_REAL_IP = 78,
2598 WSI_TOKEN_HTTP1_0 = 79,
2600 /****** add new things just above ---^ ******/
2602 /* use token storage to stash these internally, not for
2605 _WSI_TOKEN_CLIENT_SENT_PROTOCOLS,
2606 _WSI_TOKEN_CLIENT_PEER_ADDRESS,
2607 _WSI_TOKEN_CLIENT_URI,
2608 _WSI_TOKEN_CLIENT_HOST,
2609 _WSI_TOKEN_CLIENT_ORIGIN,
2610 _WSI_TOKEN_CLIENT_METHOD,
2612 /* always last real token index*/
2615 /* parser state additions, no storage associated */
2616 WSI_TOKEN_NAME_PART,
2618 WSI_TOKEN_SKIPPING_SAW_CR,
2619 WSI_PARSING_COMPLETE,
2620 WSI_INIT_TOKEN_MUXURL,
2623 struct lws_token_limits {
2624 unsigned short token_limit[WSI_TOKEN_COUNT]; /**< max chars for this token */
2628 * lws_token_to_string() - returns a textual representation of a hdr token index
2630 * \param: token index
2632 LWS_VISIBLE LWS_EXTERN const unsigned char *
2633 lws_token_to_string(enum lws_token_indexes token);
2637 * lws_hdr_total_length: report length of all fragments of a header totalled up
2638 * The returned length does not include the space for a
2641 * \param wsi: websocket connection
2642 * \param h: which header index we are interested in
2644 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2645 lws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h);
2648 * lws_hdr_fragment_length: report length of a single fragment of a header
2649 * The returned length does not include the space for a
2652 * \param wsi: websocket connection
2653 * \param h: which header index we are interested in
2654 * \param frag_idx: which fragment of h we want to get the length of
2656 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2657 lws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx);
2660 * lws_hdr_copy() - copy a single fragment of the given header to a buffer
2661 * The buffer length len must include space for an additional
2662 * terminating '\0', or it will fail returning -1.
2664 * \param wsi: websocket connection
2665 * \param dest: destination buffer
2666 * \param len: length of destination buffer
2667 * \param h: which header index we are interested in
2669 * copies the whole, aggregated header, even if it was delivered in
2670 * several actual headers piece by piece
2672 LWS_VISIBLE LWS_EXTERN int
2673 lws_hdr_copy(struct lws *wsi, char *dest, int len, enum lws_token_indexes h);
2676 * lws_hdr_copy_fragment() - copy a single fragment of the given header to a buffer
2677 * The buffer length len must include space for an additional
2678 * terminating '\0', or it will fail returning -1.
2679 * If the requested fragment index is not present, it fails
2682 * \param wsi: websocket connection
2683 * \param dest: destination buffer
2684 * \param len: length of destination buffer
2685 * \param h: which header index we are interested in
2686 * \param frag_idx: which fragment of h we want to copy
2688 * Normally this is only useful
2689 * to parse URI arguments like ?x=1&y=2, token index WSI_TOKEN_HTTP_URI_ARGS
2690 * fragment 0 will contain "x=1" and fragment 1 "y=2"
2692 LWS_VISIBLE LWS_EXTERN int
2693 lws_hdr_copy_fragment(struct lws *wsi, char *dest, int len,
2694 enum lws_token_indexes h, int frag_idx);
2697 * lws_get_urlarg_by_name() - return pointer to arg value if present
2698 * \param wsi: the connection to check
2699 * \param name: the arg name, like "token="
2700 * \param buf: the buffer to receive the urlarg (including the name= part)
2701 * \param len: the length of the buffer to receive the urlarg
2703 * Returns NULL if not found or a pointer inside buf to just after the
2706 LWS_VISIBLE LWS_EXTERN const char *
2707 lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len);
2710 /*! \defgroup HTTP-headers-create HTTP headers: create
2712 * ## HTTP headers: Create
2714 * These apis allow you to create HTTP response headers in a way compatible with
2715 * both HTTP/1.x and HTTP/2.
2717 * They each append to a buffer taking care about the buffer end, which is
2718 * passed in as a pointer. When data is written to the buffer, the current
2719 * position p is updated accordingly.
2721 * All of these apis are LWS_WARN_UNUSED_RESULT as they can run out of space
2722 * and fail with nonzero return.
2726 * lws_add_http_header_status() - add the HTTP response status code
2728 * \param wsi: the connection to check
2729 * \param code: an HTTP code like 200, 404 etc (see enum http_status)
2730 * \param p: pointer to current position in buffer pointer
2731 * \param end: pointer to end of buffer
2733 * Adds the initial response code, so should be called first
2735 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2736 lws_add_http_header_status(struct lws *wsi,
2737 unsigned int code, unsigned char **p,
2738 unsigned char *end);
2740 * lws_add_http_header_by_name() - append named header and value
2742 * \param wsi: the connection to check
2743 * \param name: the hdr name, like "my-header"
2744 * \param value: the value after the = for this header
2745 * \param length: the length of the value
2746 * \param p: pointer to current position in buffer pointer
2747 * \param end: pointer to end of buffer
2749 * Appends name: value to the headers
2751 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2752 lws_add_http_header_by_name(struct lws *wsi, const unsigned char *name,
2753 const unsigned char *value, int length,
2754 unsigned char **p, unsigned char *end);
2756 * lws_add_http_header_by_token() - append given header and value
2758 * \param wsi: the connection to check
2759 * \param token: the token index for the hdr
2760 * \param value: the value after the = for this header
2761 * \param length: the length of the value
2762 * \param p: pointer to current position in buffer pointer
2763 * \param end: pointer to end of buffer
2765 * Appends name=value to the headers, but is able to take advantage of better
2766 * HTTP/2 coding mechanisms where possible.
2768 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2769 lws_add_http_header_by_token(struct lws *wsi, enum lws_token_indexes token,
2770 const unsigned char *value, int length,
2771 unsigned char **p, unsigned char *end);
2773 * lws_add_http_header_by_name() - append content-length helper
2775 * \param wsi: the connection to check
2776 * \param content_length: the content length to use
2777 * \param p: pointer to current position in buffer pointer
2778 * \param end: pointer to end of buffer
2780 * Appends content-length: content_length to the headers
2782 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2783 lws_add_http_header_content_length(struct lws *wsi,
2784 unsigned long content_length,
2785 unsigned char **p, unsigned char *end);
2787 * lws_finalize_http_header() - terminate header block
2789 * \param wsi: the connection to check
2790 * \param p: pointer to current position in buffer pointer
2791 * \param end: pointer to end of buffer
2793 * Indicates no more headers will be added
2795 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2796 lws_finalize_http_header(struct lws *wsi, unsigned char **p,
2797 unsigned char *end);
2800 /** \defgroup form-parsing Form Parsing
2802 * ##POSTed form parsing functions
2804 * These lws_spa (stateful post arguments) apis let you parse and urldecode
2805 * POSTed form arguments, both using simple urlencoded and multipart transfer
2808 * It's capable of handling file uploads as well a named input parsing,
2809 * and the apis are the same for both form upload styles.
2811 * You feed it a list of parameter names and it creates pointers to the
2812 * urldecoded arguments: file upload parameters pass the file data in chunks to
2813 * a user-supplied callback as they come.
2815 * Since it's stateful, it handles the incoming data needing more than one
2816 * POST_BODY callback and has no limit on uploaded file size.
2820 /** enum lws_spa_fileupload_states */
2821 enum lws_spa_fileupload_states {
2823 /**< a chunk of file content has arrived */
2824 LWS_UFS_FINAL_CONTENT,
2825 /**< the last chunk (possibly zero length) of file content has arrived */
2827 /**< a new file is starting to arrive */
2831 * lws_spa_fileupload_cb() - callback to receive file upload data
2833 * \param data: opt_data pointer set in lws_spa_create
2834 * \param name: name of the form field being uploaded
2835 * \param filename: original filename from client
2836 * \param buf: start of data to receive
2837 * \param len: length of data to receive
2838 * \param state: information about how this call relates to file
2840 * Notice name and filename shouldn't be trusted, as they are passed from
2841 * HTTP provided by the client.
2843 typedef int (*lws_spa_fileupload_cb)(void *data, const char *name,
2844 const char *filename, char *buf, int len,
2845 enum lws_spa_fileupload_states state);
2847 /** struct lws_spa - opaque urldecode parser capable of handling multipart
2848 * and file uploads */
2852 * lws_spa_create() - create urldecode parser
2854 * \param wsi: lws connection (used to find Content Type)
2855 * \param param_names: array of form parameter names, like "username"
2856 * \param count_params: count of param_names
2857 * \param max_storage: total amount of form parameter values we can store
2858 * \param opt_cb: NULL, or callback to receive file upload data.
2859 * \param opt_data: NULL, or user pointer provided to opt_cb.
2861 * Creates a urldecode parser and initializes it.
2863 * opt_cb can be NULL if you just want normal name=value parsing, however
2864 * if one or more entries in your form are bulk data (file transfer), you
2865 * can provide this callback and filter on the name callback parameter to
2866 * treat that urldecoded data separately. The callback should return -1
2867 * in case of fatal error, and 0 if OK.
2869 LWS_VISIBLE LWS_EXTERN struct lws_spa *
2870 lws_spa_create(struct lws *wsi, const char * const *param_names,
2871 int count_params, int max_storage, lws_spa_fileupload_cb opt_cb,
2875 * lws_spa_process() - parses a chunk of input data
2877 * \param spa: the parser object previously created
2878 * \param in: incoming, urlencoded data
2879 * \param len: count of bytes valid at \param in
2881 LWS_VISIBLE LWS_EXTERN int
2882 lws_spa_process(struct lws_spa *spa, const char *in, int len);
2885 * lws_spa_finalize() - indicate incoming data completed
2887 * \param spa: the parser object previously created
2889 LWS_VISIBLE LWS_EXTERN int
2890 lws_spa_finalize(struct lws_spa *spa);
2893 * lws_spa_get_length() - return length of parameter value
2895 * \param spa: the parser object previously created
2896 * \param n: parameter ordinal to return length of value for
2898 LWS_VISIBLE LWS_EXTERN int
2899 lws_spa_get_length(struct lws_spa *spa, int n);
2902 * lws_spa_get_string() - return pointer to parameter value
2903 * \param spa: the parser object previously created
2904 * \param n: parameter ordinal to return pointer to value for
2906 LWS_VISIBLE LWS_EXTERN const char *
2907 lws_spa_get_string(struct lws_spa *spa, int n);
2910 * lws_spa_destroy() - destroy parser object
2912 * \param spa: the parser object previously created
2914 LWS_VISIBLE LWS_EXTERN int
2915 lws_spa_destroy(struct lws_spa *spa);
2918 /*! \defgroup urlendec Urlencode and Urldecode
2921 * ##HTML chunked Substitution
2923 * APIs for receiving chunks of text, replacing a set of variable names via
2924 * a callback, and then prepending and appending HTML chunked encoding
2930 * lws_urlencode() - like strncpy but with urlencoding
2932 * \param escaped: output buffer
2933 * \param string: input buffer ('/0' terminated)
2934 * \param len: output buffer max length
2936 * Because urlencoding expands the output string, it's not
2937 * possible to do it in-place, ie, with escaped == string
2939 LWS_VISIBLE LWS_EXTERN const char *
2940 lws_urlencode(char *escaped, const char *string, int len);
2945 * This simple urldecode only operates until the first '\0' and requires the
2946 * data to exist all at once
2949 * lws_urldecode() - like strncpy but with urldecoding
2951 * \param string: output buffer
2952 * \param escaped: input buffer ('\0' terminated)
2953 * \param len: output buffer max length
2955 * This is only useful for '\0' terminated strings
2957 * Since urldecoding only shrinks the output string, it is possible to
2958 * do it in-place, ie, string == escaped
2960 LWS_VISIBLE LWS_EXTERN int
2961 lws_urldecode(char *string, const char *escaped, int len);
2964 * lws_return_http_status() - Return simple http status
2965 * \param wsi: Websocket instance (available from user callback)
2966 * \param code: Status index, eg, 404
2967 * \param html_body: User-readable HTML description < 1KB, or NULL
2969 * Helper to report HTTP errors back to the client cleanly and
2972 LWS_VISIBLE LWS_EXTERN int
2973 lws_return_http_status(struct lws *wsi, unsigned int code,
2974 const char *html_body);
2977 * lws_http_redirect() - write http redirect into buffer
2979 * \param wsi: websocket connection
2980 * \param code: HTTP response code (eg, 301)
2981 * \param loc: where to redirect to
2982 * \param len: length of loc
2983 * \param p: pointer current position in buffer (updated as we write)
2984 * \param end: pointer to end of buffer
2986 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2987 lws_http_redirect(struct lws *wsi, int code, const unsigned char *loc, int len,
2988 unsigned char **p, unsigned char *end);
2991 * lws_http_transaction_completed() - wait for new http transaction or close
2992 * \param wsi: websocket connection
2994 * Returns 1 if the HTTP connection must close now
2995 * Returns 0 and resets connection to wait for new HTTP header /
2996 * transaction if possible
2998 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2999 lws_http_transaction_completed(struct lws *wsi);
3002 /*! \defgroup pur Sanitize / purify SQL and JSON helpers
3004 * ##Sanitize / purify SQL and JSON helpers
3006 * APIs for escaping untrusted JSON and SQL safely before use
3011 * lws_sql_purify() - like strncpy but with escaping for sql quotes
3013 * \param escaped: output buffer
3014 * \param string: input buffer ('/0' terminated)
3015 * \param len: output buffer max length
3017 * Because escaping expands the output string, it's not
3018 * possible to do it in-place, ie, with escaped == string
3020 LWS_VISIBLE LWS_EXTERN const char *
3021 lws_sql_purify(char *escaped, const char *string, int len);
3024 * lws_json_purify() - like strncpy but with escaping for json chars
3026 * \param escaped: output buffer
3027 * \param string: input buffer ('/0' terminated)
3028 * \param len: output buffer max length
3030 * Because escaping expands the output string, it's not
3031 * possible to do it in-place, ie, with escaped == string
3033 LWS_VISIBLE LWS_EXTERN const char *
3034 lws_json_purify(char *escaped, const char *string, int len);
3037 /*! \defgroup ev libev helpers
3041 * APIs specific to libev event loop itegration
3045 #ifdef LWS_USE_LIBEV
3046 typedef void (lws_ev_signal_cb_t)(EV_P_ struct ev_signal *w, int revents);
3048 LWS_VISIBLE LWS_EXTERN int
3049 lws_ev_sigint_cfg(struct lws_context *context, int use_ev_sigint,
3050 lws_ev_signal_cb_t *cb);
3052 LWS_VISIBLE LWS_EXTERN int
3053 lws_ev_initloop(struct lws_context *context, struct ev_loop *loop, int tsi);
3055 LWS_VISIBLE LWS_EXTERN void
3056 lws_ev_sigint_cb(struct ev_loop *loop, struct ev_signal *watcher, int revents);
3057 #endif /* LWS_USE_LIBEV */
3061 /*! \defgroup uv libuv helpers
3065 * APIs specific to libuv event loop itegration
3068 #ifdef LWS_USE_LIBUV
3069 LWS_VISIBLE LWS_EXTERN int
3070 lws_uv_sigint_cfg(struct lws_context *context, int use_uv_sigint,
3073 LWS_VISIBLE LWS_EXTERN void
3074 lws_libuv_run(const struct lws_context *context, int tsi);
3076 LWS_VISIBLE LWS_EXTERN void
3077 lws_libuv_stop(struct lws_context *context);
3079 LWS_VISIBLE LWS_EXTERN int
3080 lws_uv_initloop(struct lws_context *context, uv_loop_t *loop, int tsi);
3082 LWS_VISIBLE LWS_EXTERN uv_loop_t *
3083 lws_uv_getloop(struct lws_context *context, int tsi);
3085 LWS_VISIBLE LWS_EXTERN void
3086 lws_uv_sigint_cb(uv_signal_t *watcher, int signum);
3087 #endif /* LWS_USE_LIBUV */
3090 /*! \defgroup timeout Connection timeouts
3092 APIs related to setting connection timeouts
3097 * NOTE: These public enums are part of the abi. If you want to add one,
3098 * add it at where specified so existing users are unaffected.
3100 enum pending_timeout {
3101 NO_PENDING_TIMEOUT = 0,
3102 PENDING_TIMEOUT_AWAITING_PROXY_RESPONSE = 1,
3103 PENDING_TIMEOUT_AWAITING_CONNECT_RESPONSE = 2,
3104 PENDING_TIMEOUT_ESTABLISH_WITH_SERVER = 3,
3105 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE = 4,
3106 PENDING_TIMEOUT_AWAITING_PING = 5,
3107 PENDING_TIMEOUT_CLOSE_ACK = 6,
3108 PENDING_TIMEOUT_AWAITING_EXTENSION_CONNECT_RESPONSE = 7,
3109 PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE = 8,
3110 PENDING_TIMEOUT_SSL_ACCEPT = 9,
3111 PENDING_TIMEOUT_HTTP_CONTENT = 10,
3112 PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND = 11,
3113 PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE = 12,
3114 PENDING_TIMEOUT_SHUTDOWN_FLUSH = 13,
3115 PENDING_TIMEOUT_CGI = 14,
3116 PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE = 15,
3117 PENDING_TIMEOUT_WS_PONG_CHECK_SEND_PING = 16,
3118 PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG = 17,
3119 PENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD = 18,
3121 /****** add new things just above ---^ ******/
3125 * lws_set_timeout() - marks the wsi as subject to a timeout
3127 * You will not need this unless you are doing something special
3129 * \param wsi: Websocket connection instance
3130 * \param reason: timeout reason
3131 * \param secs: how many seconds
3133 LWS_VISIBLE LWS_EXTERN void
3134 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs);
3137 /*! \defgroup sending-data Sending data
3139 APIs related to writing data on a connection
3142 #if !defined(LWS_SIZEOFPTR)
3143 #define LWS_SIZEOFPTR (sizeof (void *))
3145 #if !defined(u_int64_t)
3146 #define u_int64_t unsigned long long
3149 #if defined(__x86_64__)
3150 #define _LWS_PAD_SIZE 16 /* Intel recommended for best performance */
3152 #define _LWS_PAD_SIZE LWS_SIZEOFPTR /* Size of a pointer on the target arch */
3154 #define _LWS_PAD(n) (((n) % _LWS_PAD_SIZE) ? \
3155 ((n) + (_LWS_PAD_SIZE - ((n) % _LWS_PAD_SIZE))) : (n))
3156 #define LWS_PRE _LWS_PAD(4 + 10)
3157 /* used prior to 1.7 and retained for backward compatibility */
3158 #define LWS_SEND_BUFFER_PRE_PADDING LWS_PRE
3159 #define LWS_SEND_BUFFER_POST_PADDING 0
3162 * NOTE: These public enums are part of the abi. If you want to add one,
3163 * add it at where specified so existing users are unaffected.
3165 enum lws_write_protocol {
3167 /**< Send a ws TEXT message,the pointer must have LWS_PRE valid
3168 * memory behind it. The receiver expects only valid utf-8 in the
3170 LWS_WRITE_BINARY = 1,
3171 /**< Send a ws BINARY message, the pointer must have LWS_PRE valid
3172 * memory behind it. Any sequence of bytes is valid */
3173 LWS_WRITE_CONTINUATION = 2,
3174 /**< Continue a previous ws message, the pointer must have LWS_PRE valid
3175 * memory behind it */
3177 /**< Send HTTP content */
3179 /* LWS_WRITE_CLOSE is handled by lws_close_reason() */
3183 /* Same as write_http but we know this write ends the transaction */
3184 LWS_WRITE_HTTP_FINAL = 7,
3188 LWS_WRITE_HTTP_HEADERS = 8,
3189 /**< Send http headers (http2 encodes this payload and LWS_WRITE_HTTP
3190 * payload differently, http 1.x links also handle this correctly. so
3191 * to be compatible with both in the future,header response part should
3192 * be sent using this regardless of http version expected)
3195 /****** add new things just above ---^ ******/
3199 LWS_WRITE_NO_FIN = 0x40,
3200 /**< This part of the message is not the end of the message */
3202 LWS_WRITE_CLIENT_IGNORE_XOR_MASK = 0x80
3203 /**< client packet payload goes out on wire unmunged
3204 * only useful for security tests since normal servers cannot
3205 * decode the content if used */
3210 * lws_write() - Apply protocol then write data to client
3211 * \param wsi: Websocket instance (available from user callback)
3212 * \param buf: The data to send. For data being sent on a websocket
3213 * connection (ie, not default http), this buffer MUST have
3214 * LWS_PRE bytes valid BEFORE the pointer.
3215 * This is so the protocol header data can be added in-situ.
3216 * \param len: Count of the data bytes in the payload starting from buf
3217 * \param protocol: Use LWS_WRITE_HTTP to reply to an http connection, and one
3218 * of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
3219 * data on a websockets connection. Remember to allow the extra
3220 * bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
3223 * This function provides the way to issue data back to the client
3224 * for both http and websocket protocols.
3228 * When sending with websocket protocol
3232 * LWS_WRITE_CONTINUATION,
3236 * the send buffer has to have LWS_PRE bytes valid BEFORE
3237 * the buffer pointer you pass to lws_write().
3239 * This allows us to add protocol info before and after the data, and send as
3240 * one packet on the network without payload copying, for maximum efficiency.
3242 * So for example you need this kind of code to use lws_write with a
3245 * char buf[LWS_PRE + 128];
3247 * // fill your part of the buffer... for example here it's all zeros
3248 * memset(&buf[LWS_PRE], 0, 128);
3250 * lws_write(wsi, &buf[LWS_PRE], 128, LWS_WRITE_TEXT);
3252 * When sending HTTP, with
3255 * LWS_WRITE_HTTP_HEADERS
3256 * LWS_WRITE_HTTP_FINAL
3258 * there is no protocol data prepended, and don't need to take care about the
3259 * LWS_PRE bytes valid before the buffer pointer.
3261 * LWS_PRE is at least the frame nonce + 2 header + 8 length
3262 * LWS_SEND_BUFFER_POST_PADDING is deprecated, it's now 0 and can be left off.
3263 * The example apps no longer use it.
3265 * Pad LWS_PRE to the CPU word size, so that word references
3266 * to the address immediately after the padding won't cause an unaligned access
3267 * error. Sometimes for performance reasons the recommended padding is even
3268 * larger than sizeof(void *).
3270 * In the case of sending using websocket protocol, be sure to allocate
3271 * valid storage before and after buf as explained above. This scheme
3272 * allows maximum efficiency of sending data and protocol in a single
3273 * packet while not burdening the user code with any protocol knowledge.
3275 * Return may be -1 for a fatal error needing connection close, or a
3276 * positive number reflecting the amount of bytes actually sent. This
3277 * can be less than the requested number of bytes due to OS memory
3278 * pressure at any given time.
3280 LWS_VISIBLE LWS_EXTERN int
3281 lws_write(struct lws *wsi, unsigned char *buf, size_t len,
3282 enum lws_write_protocol protocol);
3284 /* helper for case where buffer may be const */
3285 #define lws_write_http(wsi, buf, len) \
3286 lws_write(wsi, (unsigned char *)(buf), len, LWS_WRITE_HTTP)
3290 /** \defgroup callback-when-writeable Callback when writeable
3292 * ##Callback When Writeable
3294 * lws can only write data on a connection when it is able to accept more
3295 * data without blocking.
3297 * So a basic requirement is we should only use the lws_write() apis when the
3298 * connection we want to write on says that he can accept more data.
3300 * When lws cannot complete your send at the time, it will buffer the data
3301 * and send it in the background, suppressing any further WRITEABLE callbacks
3302 * on that connection until it completes. So it is important to write new
3303 * things in a new writeable callback.
3305 * These apis reflect the various ways we can indicate we would like to be
3306 * called back when one or more connections is writeable.
3311 * lws_callback_on_writable() - Request a callback when this socket
3312 * becomes able to be written to without
3315 * \param wsi: Websocket connection instance to get callback for
3317 * - Which: only this wsi
3318 * - When: when the individual connection becomes writeable
3319 * - What: LWS_CALLBACK_*_WRITEABLE
3321 LWS_VISIBLE LWS_EXTERN int
3322 lws_callback_on_writable(struct lws *wsi);
3325 * lws_callback_on_writable_all_protocol() - Request a callback for all
3326 * connections on same vhost using the given protocol when it
3327 * becomes possible to write to each socket without
3330 * \param context: lws_context
3331 * \param protocol: Protocol whose connections will get callbacks
3333 * - Which: connections using this protocol on ANY VHOST
3334 * - When: when the individual connection becomes writeable
3335 * - What: LWS_CALLBACK_*_WRITEABLE
3337 LWS_VISIBLE LWS_EXTERN int
3338 lws_callback_on_writable_all_protocol(const struct lws_context *context,
3339 const struct lws_protocols *protocol);
3342 * lws_callback_on_writable_all_protocol_vhost() - Request a callback for
3343 * all connections using the given protocol when it
3344 * becomes possible to write to each socket without
3347 * \param vhost: Only consider connections on this lws_vhost
3348 * \param protocol: Protocol whose connections will get callbacks
3350 * - Which: connections using this protocol on GIVEN VHOST ONLY
3351 * - When: when the individual connection becomes writeable
3352 * - What: LWS_CALLBACK_*_WRITEABLE
3354 LWS_VISIBLE LWS_EXTERN int
3355 lws_callback_on_writable_all_protocol_vhost(const struct lws_vhost *vhost,
3356 const struct lws_protocols *protocol);
3359 * lws_callback_all_protocol() - Callback all connections using
3360 * the given protocol with the given reason
3362 * \param context: lws_context
3363 * \param protocol: Protocol whose connections will get callbacks
3364 * \param reason: Callback reason index
3366 * - Which: connections using this protocol on ALL VHOSTS
3367 * - When: when the individual connection becomes writeable
3370 LWS_VISIBLE LWS_EXTERN int
3371 lws_callback_all_protocol(struct lws_context *context,
3372 const struct lws_protocols *protocol, int reason);
3375 * lws_callback_all_protocol_vhost() - Callback all connections using
3376 * the given protocol with the given reason
3378 * \param vh: Vhost whose connections will get callbacks
3379 * \param protocol: Which protocol to match
3380 * \param reason: Callback reason index
3382 * - Which: connections using this protocol on GIVEN VHOST ONLY
3386 LWS_VISIBLE LWS_EXTERN int
3387 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
3388 const struct lws_protocols *protocol, int reason);
3391 * lws_callback_vhost_protocols() - Callback all protocols enabled on a vhost
3392 * with the given reason
3394 * \param wsi: wsi whose vhost will get callbacks
3395 * \param reason: Callback reason index
3396 * \param in: in argument to callback
3397 * \param len: len argument to callback
3399 * - Which: connections using this protocol on same VHOST as wsi ONLY
3403 LWS_VISIBLE LWS_EXTERN int
3404 lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len);
3406 LWS_VISIBLE LWS_EXTERN int
3407 lws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason,
3408 void *user, void *in, size_t len);
3411 * lws_get_socket_fd() - returns the socket file descriptor
3413 * You will not need this unless you are doing something special
3415 * \param wsi: Websocket connection instance
3417 LWS_VISIBLE LWS_EXTERN int
3418 lws_get_socket_fd(struct lws *wsi);
3421 * lws_get_peer_write_allowance() - get the amount of data writeable to peer
3424 * \param wsi: Websocket connection instance
3426 * if the protocol does not have any guidance, returns -1. Currently only
3427 * http2 connections get send window information from this API. But your code
3428 * should use it so it can work properly with any protocol.
3430 * If nonzero return is the amount of payload data the peer or intermediary has
3431 * reported it has buffer space for. That has NO relationship with the amount
3432 * of buffer space your OS can accept on this connection for a write action.
3434 * This number represents the maximum you could send to the peer or intermediary
3435 * on this connection right now without the protocol complaining.
3437 * lws manages accounting for send window updates and payload writes
3438 * automatically, so this number reflects the situation at the peer or
3439 * intermediary dynamically.
3441 LWS_VISIBLE LWS_EXTERN size_t
3442 lws_get_peer_write_allowance(struct lws *wsi);
3446 * lws_rx_flow_control() - Enable and disable socket servicing for
3449 * If the output side of a server process becomes choked, this allows flow
3450 * control for the input side.
3452 * \param wsi: Websocket connection instance to get callback for
3453 * \param enable: 0 = disable read servicing for this connection, 1 = enable
3455 LWS_VISIBLE LWS_EXTERN int
3456 lws_rx_flow_control(struct lws *wsi, int enable);
3459 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
3461 * When the user server code realizes it can accept more input, it can
3462 * call this to have the RX flow restriction removed from all connections using
3463 * the given protocol.
3464 * \param context: lws_context
3465 * \param protocol: all connections using this protocol will be allowed to receive
3467 LWS_VISIBLE LWS_EXTERN void
3468 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
3469 const struct lws_protocols *protocol);
3472 * lws_remaining_packet_payload() - Bytes to come before "overall"
3473 * rx packet is complete
3474 * \param wsi: Websocket instance (available from user callback)
3476 * This function is intended to be called from the callback if the
3477 * user code is interested in "complete packets" from the client.
3478 * libwebsockets just passes through payload as it comes and issues a buffer
3479 * additionally when it hits a built-in limit. The LWS_CALLBACK_RECEIVE
3480 * callback handler can use this API to find out if the buffer it has just
3481 * been given is the last piece of a "complete packet" from the client --
3482 * when that is the case lws_remaining_packet_payload() will return
3485 * Many protocols won't care becuse their packets are always small.
3487 LWS_VISIBLE LWS_EXTERN size_t
3488 lws_remaining_packet_payload(struct lws *wsi);
3491 /** \defgroup sock-adopt Socket adoption helpers
3492 * ##Socket adoption helpers
3494 * When integrating with an external app with its own event loop, these can
3495 * be used to accept connections from someone else's listening socket.
3497 * When using lws own event loop, these are not needed.
3502 * lws_adopt_socket() - adopt foreign socket as if listen socket accepted it
3503 * \param context: lws context
3504 * \param accept_fd: fd of already-accepted socket to adopt
3506 * Either returns new wsi bound to accept_fd, or closes accept_fd and
3507 * returns NULL, having cleaned up any new wsi pieces.
3509 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
3510 * to ws or just serve http.
3512 LWS_VISIBLE LWS_EXTERN struct lws *
3513 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd);
3515 * lws_adopt_socket_readbuf() - adopt foreign socket and first rx as if listen socket accepted it
3516 * \param context: lws context
3517 * \param accept_fd: fd of already-accepted socket to adopt
3518 * \param readbuf: NULL or pointer to data that must be drained before reading from
3520 * \param len: The length of the data held at \param readbuf
3522 * Either returns new wsi bound to accept_fd, or closes accept_fd and
3523 * returns NULL, having cleaned up any new wsi pieces.
3525 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
3526 * to ws or just serve http.
3528 * If your external code did not already read from the socket, you can use
3529 * lws_adopt_socket() instead.
3531 * This api is guaranteed to use the data at \param readbuf first, before reading from
3534 * readbuf is limited to the size of the ah rx buf, currently 2048 bytes.
3536 LWS_VISIBLE LWS_EXTERN struct lws *
3537 lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
3538 const char *readbuf, size_t len);
3541 /** \defgroup net Network related helper APIs
3542 * ##Network related helper APIs
3544 * These wrap miscellaneous useful network-related functions
3549 * lws_canonical_hostname() - returns this host's hostname
3551 * This is typically used by client code to fill in the host parameter
3552 * when making a client connection. You can only call it after the context
3555 * \param context: Websocket context
3557 LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
3558 lws_canonical_hostname(struct lws_context *context);
3561 * lws_get_peer_addresses() - Get client address information
3562 * \param wsi: Local struct lws associated with
3563 * \param fd: Connection socket descriptor
3564 * \param name: Buffer to take client address name
3565 * \param name_len: Length of client address name buffer
3566 * \param rip: Buffer to take client address IP dotted quad
3567 * \param rip_len: Length of client address IP buffer
3569 * This function fills in name and rip with the name and IP of
3570 * the client connected with socket descriptor fd. Names may be
3571 * truncated if there is not enough room. If either cannot be
3572 * determined, they will be returned as valid zero-length strings.
3574 LWS_VISIBLE LWS_EXTERN void
3575 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
3576 int name_len, char *rip, int rip_len);
3579 * lws_get_peer_simple() - Get client address information without RDNS
3581 * \param wsi: Local struct lws associated with
3582 * \param name: Buffer to take client address name
3583 * \param namelen: Length of client address name buffer
3585 * This provides a 123.123.123.123 type IP address in name from the
3586 * peer that has connected to wsi
3588 LWS_VISIBLE LWS_EXTERN const char *
3589 lws_get_peer_simple(struct lws *wsi, char *name, int namelen);
3590 #ifndef LWS_WITH_ESP8266
3592 * lws_interface_to_sa() - Convert interface name or IP to sockaddr struct
3594 * \param ipv6: Allow IPV6 addresses
3595 * \param ifname: Interface name or IP
3596 * \param addr: struct sockaddr_in * to be written
3597 * \param addrlen: Length of addr
3599 * This converts a textual network interface name to a sockaddr usable by
3600 * other network functions
3602 LWS_VISIBLE LWS_EXTERN int
3603 lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr,
3608 /** \defgroup misc Miscellaneous APIs
3609 * ##Miscellaneous APIs
3611 * Various APIs outside of other categories
3616 * lws_snprintf(): snprintf that truncates the returned length too
3618 * \param str: destination buffer
3619 * \param size: bytes left in destination buffer
3620 * \param format: format string
3621 * \param ...: args for format
3623 * This lets you correctly truncate buffers by concatenating lengths, if you
3624 * reach the limit the reported length doesn't exceed the limit.
3626 LWS_VISIBLE LWS_EXTERN int
3627 lws_snprintf(char *str, size_t size, const char *format, ...);
3630 * lws_get_random(): fill a buffer with platform random data
3632 * \param context: the lws context
3633 * \param buf: buffer to fill
3634 * \param len: how much to fill
3636 * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
3637 * it's interested to see if the frame it's dealing with was sent in binary
3640 LWS_VISIBLE LWS_EXTERN int
3641 lws_get_random(struct lws_context *context, void *buf, int len);
3643 * lws_daemonize(): fill a buffer with platform random data
3645 * \param _lock_path: the filepath to write the lock file
3647 * Spawn lws as a background process, taking care of various things
3649 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3650 lws_daemonize(const char *_lock_path);
3652 * lws_get_library_version(): return string describing the version of lws
3654 * On unix, also includes the git describe
3656 LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
3657 lws_get_library_version(void);
3660 * lws_wsi_user() - get the user data associated with the connection
3661 * \param wsi: lws connection
3663 * Not normally needed since it's passed into the callback
3665 LWS_VISIBLE LWS_EXTERN void *
3666 lws_wsi_user(struct lws *wsi);
3669 * lws_parse_uri: cut up prot:/ads:port/path into pieces
3670 * Notice it does so by dropping '\0' into input string
3671 * and the leading / on the path is consequently lost
3673 * \param p: incoming uri string.. will get written to
3674 * \param prot: result pointer for protocol part (https://)
3675 * \param ads: result pointer for address part
3676 * \param port: result pointer for port part
3677 * \param path: result pointer for path part
3679 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3680 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
3684 * lws_now_secs(): return seconds since 1970-1-1
3686 LWS_VISIBLE LWS_EXTERN unsigned long
3690 * lws_get_context - Allow geting lws_context from a Websocket connection
3693 * With this function, users can access context in the callback function.
3694 * Otherwise users may have to declare context as a global variable.
3696 * \param wsi: Websocket connection instance
3698 LWS_VISIBLE LWS_EXTERN struct lws_context * LWS_WARN_UNUSED_RESULT
3699 lws_get_context(const struct lws *wsi);
3702 * lws_get_count_threads(): how many service threads the context uses
3704 * \param context: the lws context
3706 * By default this is always 1, if you asked for more than lws can handle it
3707 * will clip the number of threads. So you can use this to find out how many
3708 * threads are actually in use.
3710 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3711 lws_get_count_threads(struct lws_context *context);
3714 * lws_get_parent() - get parent wsi or NULL
3715 * \param wsi: lws connection
3717 * Specialized wsi like cgi stdin/out/err are associated to a parent wsi,
3718 * this allows you to get their parent.
3720 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
3721 lws_get_parent(const struct lws *wsi);
3724 * lws_get_child() - get child wsi or NULL
3725 * \param wsi: lws connection
3727 * Allows you to find a related wsi from the parent wsi.
3729 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
3730 lws_get_child(const struct lws *wsi);
3734 * \deprecated DEPRECATED Note: this is not normally needed as a user api.
3735 * It's provided in case it is
3736 * useful when integrating with other app poll loop service code.
3738 LWS_VISIBLE LWS_EXTERN int
3739 lws_read(struct lws *wsi, unsigned char *buf, size_t len);
3742 * lws_set_allocator() - custom allocator support
3746 * Allows you to replace the allocator (and deallocator) used by lws
3748 LWS_VISIBLE LWS_EXTERN void
3749 lws_set_allocator(void *(*realloc)(void *ptr, size_t size));
3752 /** \defgroup wsstatus Websocket status APIs
3753 * ##Websocket connection status APIs
3755 * These provide information about ws connection or message status
3759 * lws_send_pipe_choked() - tests if socket is writable or not
3760 * \param wsi: lws connection
3762 * Allows you to check if you can write more on the socket
3764 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3765 lws_send_pipe_choked(struct lws *wsi);
3768 * lws_is_final_fragment() - tests if last part of ws message
3769 * \param wsi: lws connection
3771 LWS_VISIBLE LWS_EXTERN int
3772 lws_is_final_fragment(struct lws *wsi);
3775 * lws_get_reserved_bits() - access reserved bits of ws frame
3776 * \param wsi: lws connection
3778 LWS_VISIBLE LWS_EXTERN unsigned char
3779 lws_get_reserved_bits(struct lws *wsi);
3782 * lws_partial_buffered() - find out if lws buffered the last write
3783 * \param wsi: websocket connection to check
3785 * Returns 1 if you cannot use lws_write because the last
3786 * write on this connection is still buffered, and can't be cleared without
3787 * returning to the service loop and waiting for the connection to be
3790 * If you will try to do >1 lws_write call inside a single
3791 * WRITEABLE callback, you must check this after every write and bail if
3792 * set, ask for a new writeable callback and continue writing from there.
3794 * This is never set at the start of a writeable callback, but any write
3797 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3798 lws_partial_buffered(struct lws *wsi);
3801 * lws_frame_is_binary(): true if the current frame was sent in binary mode
3803 * \param wsi: the connection we are inquiring about
3805 * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
3806 * it's interested to see if the frame it's dealing with was sent in binary
3809 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3810 lws_frame_is_binary(struct lws *wsi);
3813 * lws_is_ssl() - Find out if connection is using SSL
3814 * \param wsi: websocket connection to check
3816 * Returns 0 if the connection is not using SSL, 1 if using SSL and
3817 * using verified cert, and 2 if using SSL but the cert was not
3818 * checked (appears for client wsi told to skip check on connection)
3820 LWS_VISIBLE LWS_EXTERN int
3821 lws_is_ssl(struct lws *wsi);
3823 * lws_is_cgi() - find out if this wsi is running a cgi process
3824 * \param wsi: lws connection
3826 LWS_VISIBLE LWS_EXTERN int
3827 lws_is_cgi(struct lws *wsi);
3831 /** \defgroup sha SHA and B64 helpers
3832 * ##SHA and B64 helpers
3834 * These provide SHA-1 and B64 helper apis
3837 #ifdef LWS_SHA1_USE_OPENSSL_NAME
3838 #define lws_SHA1 SHA1
3841 * lws_SHA1(): make a SHA-1 digest of a buffer
3843 * \param d: incoming buffer
3844 * \param n: length of incoming buffer
3845 * \param md: buffer for message digest (must be >= 20 bytes)
3847 * Reduces any size buffer into a 20-byte SHA-1 hash.
3849 LWS_VISIBLE LWS_EXTERN unsigned char *
3850 lws_SHA1(const unsigned char *d, size_t n, unsigned char *md);
3853 * lws_b64_encode_string(): encode a string into base 64
3855 * \param in: incoming buffer
3856 * \param in_len: length of incoming buffer
3857 * \param out: result buffer
3858 * \param out_size: length of result buffer
3860 * Encodes a string using b64
3862 LWS_VISIBLE LWS_EXTERN int
3863 lws_b64_encode_string(const char *in, int in_len, char *out, int out_size);
3865 * lws_b64_decode_string(): decode a string from base 64
3867 * \param in: incoming buffer
3868 * \param out: result buffer
3869 * \param out_size: length of result buffer
3871 * Decodes a string using b64
3873 LWS_VISIBLE LWS_EXTERN int
3874 lws_b64_decode_string(const char *in, char *out, int out_size);
3878 /*! \defgroup cgi cgi handling
3882 * These functions allow low-level control over stdin/out/err of the cgi.
3884 * However for most cases, binding the cgi to http in and out, the default
3885 * lws implementation already does the right thing.
3888 enum lws_enum_stdinouterr {
3894 enum lws_cgi_hdr_state {
3904 struct lws_cgi_args {
3905 struct lws **stdwsi; /**< get fd with lws_get_socket_fd() */
3906 enum lws_enum_stdinouterr ch; /**< channel index */
3907 unsigned char *data; /**< for messages with payload */
3908 enum lws_cgi_hdr_state hdr_state; /**< track where we are in cgi headers */
3909 int len; /**< length */
3914 * lws_cgi: spawn network-connected cgi process
3916 * \param wsi: connection to own the process
3917 * \param exec_array: array of "exec-name" "arg1" ... "argn" NULL
3918 * \param script_uri_path_len: how many chars on the left of the uri are the path to the cgi
3919 * \param timeout_secs: seconds script should be allowed to run
3920 * \param mp_cgienv: pvo list with per-vhost cgi options to put in env
3922 LWS_VISIBLE LWS_EXTERN int
3923 lws_cgi(struct lws *wsi, const char * const *exec_array,
3924 int script_uri_path_len, int timeout_secs,
3925 const struct lws_protocol_vhost_options *mp_cgienv);
3928 * lws_cgi_write_split_stdout_headers: write cgi output accounting for header part
3930 * \param wsi: connection to own the process
3932 LWS_VISIBLE LWS_EXTERN int
3933 lws_cgi_write_split_stdout_headers(struct lws *wsi);
3936 * lws_cgi_kill: terminate cgi process associated with wsi
3938 * \param wsi: connection to own the process
3940 LWS_VISIBLE LWS_EXTERN int
3941 lws_cgi_kill(struct lws *wsi);
3946 /*! \defgroup fops file operation wrapping
3948 * ##File operation wrapping
3950 * Use these helper functions if you want to access a file from the perspective
3951 * of a specific wsi, which is usually the case. If you just want contextless
3952 * file access, use the fops callbacks directly with NULL wsi instead of these
3955 * If so, then it calls the platform handler or user overrides where present
3956 * (as defined in info->fops)
3958 * The advantage from all this is user code can be portable for file operations
3959 * without having to deal with differences between platforms.
3963 /** struct lws_plat_file_ops - Platform-specific file operations
3965 * These provide platform-agnostic ways to deal with filesystem access in the
3966 * library and in the user code.
3968 struct lws_plat_file_ops {
3969 lws_filefd_type (*open)(struct lws *wsi, const char *filename,
3970 unsigned long *filelen, int flags);
3971 /**< Open file (always binary access if plat supports it)
3972 * filelen is filled on exit to be the length of the file
3973 * flags should be set to O_RDONLY or O_RDWR */
3974 int (*close)(struct lws *wsi, lws_filefd_type fd);
3976 unsigned long (*seek_cur)(struct lws *wsi, lws_filefd_type fd,
3977 long offset_from_cur_pos);
3978 /**< seek from current position */
3979 int (*read)(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
3980 unsigned char *buf, unsigned long len);
3981 /**< Read from file, on exit *amount is set to amount actually read */
3982 int (*write)(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
3983 unsigned char *buf, unsigned long len);
3984 /**< Write to file, on exit *amount is set to amount actually written */
3986 /* Add new things just above here ---^
3987 * This is part of the ABI, don't needlessly break compatibility */
3991 * lws_get_fops() - get current file ops
3993 * \param context: context
3995 LWS_VISIBLE LWS_EXTERN struct lws_plat_file_ops * LWS_WARN_UNUSED_RESULT
3996 lws_get_fops(struct lws_context *context);
3999 * lws_plat_file_open() - file open operations
4001 * \param wsi: connection doing the opening
4002 * \param filename: filename to open
4003 * \param filelen: length of file (filled in by call)
4004 * \param flags: open flags
4006 static LWS_INLINE lws_filefd_type LWS_WARN_UNUSED_RESULT
4007 lws_plat_file_open(struct lws *wsi, const char *filename,
4008 unsigned long *filelen, int flags)
4010 return lws_get_fops(lws_get_context(wsi))->open(wsi, filename,
4015 * lws_plat_file_close() - close file
4017 * \param wsi: connection opened by
4018 * \param fd: file descriptor
4020 static LWS_INLINE int
4021 lws_plat_file_close(struct lws *wsi, lws_filefd_type fd)
4023 return lws_get_fops(lws_get_context(wsi))->close(wsi, fd);
4027 * lws_plat_file_seek_cur() - close file
4029 * \param wsi: connection opened by
4030 * \param fd: file descriptor
4031 * \param offset: position to seek to
4033 static LWS_INLINE unsigned long
4034 lws_plat_file_seek_cur(struct lws *wsi, lws_filefd_type fd, long offset)
4036 return lws_get_fops(lws_get_context(wsi))->seek_cur(wsi, fd, offset);
4039 * lws_plat_file_read() - read from file
4041 * \param wsi: connection opened by
4042 * \param fd: file descriptor
4043 * \param amount: how much to read (rewritten by call)
4044 * \param buf: buffer to write to
4045 * \param len: max length
4047 static LWS_INLINE int LWS_WARN_UNUSED_RESULT
4048 lws_plat_file_read(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
4049 unsigned char *buf, unsigned long len)
4051 return lws_get_fops(lws_get_context(wsi))->read(wsi, fd, amount, buf,
4055 * lws_plat_file_write() - write from file
4057 * \param wsi: connection opened by
4058 * \param fd: file descriptor
4059 * \param amount: how much to write (rewritten by call)
4060 * \param buf: buffer to read from
4061 * \param len: max length
4063 static LWS_INLINE int LWS_WARN_UNUSED_RESULT
4064 lws_plat_file_write(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
4065 unsigned char *buf, unsigned long len)
4067 return lws_get_fops(lws_get_context(wsi))->write(wsi, fd, amount, buf,
4074 * ##SMTP related functions
4076 * These apis let you communicate with a local SMTP server to send email from
4077 * lws. It handles all the SMTP sequencing and protocol actions.
4079 * Your system should have postfix, sendmail or another MTA listening on port
4080 * 25 and able to send email using the "mail" commandline app. Usually distro
4081 * MTAs are configured for this by default.
4083 * It runs via its own libuv events if initialized (which requires giving it
4084 * a libuv loop to attach to).
4086 * It operates using three callbacks, on_next() queries if there is a new email
4087 * to send, on_get_body() asks for the body of the email, and on_sent() is
4088 * called after the email is successfully sent.
4092 * - create an lws_email struct
4094 * - initialize data, loop, the email_* strings, max_content_size and
4097 * - call lws_email_init()
4099 * When you have at least one email to send, call lws_email_check() to
4100 * schedule starting to send it.
4103 #ifdef LWS_WITH_SMTP
4105 /** enum lwsgs_smtp_states - where we are in SMTP protocol sequence */
4106 enum lwsgs_smtp_states {
4107 LGSSMTP_IDLE, /**< awaiting new email */
4108 LGSSMTP_CONNECTING, /**< opening tcp connection to MTA */
4109 LGSSMTP_CONNECTED, /**< tcp connection to MTA is connected */
4110 LGSSMTP_SENT_HELO, /**< sent the HELO */
4111 LGSSMTP_SENT_FROM, /**< sent FROM */
4112 LGSSMTP_SENT_TO, /**< sent TO */
4113 LGSSMTP_SENT_DATA, /**< sent DATA request */
4114 LGSSMTP_SENT_BODY, /**< sent the email body */
4115 LGSSMTP_SENT_QUIT, /**< sent the session quit */
4118 /** struct lws_email - abstract context for performing SMTP operations */
4121 /**< opaque pointer set by user code and available to the callbacks */
4123 /**< the libuv loop we will work on */
4125 char email_smtp_ip[32]; /**< Fill before init, eg, "127.0.0.1" */
4126 char email_helo[32]; /**< Fill before init, eg, "myserver.com" */
4127 char email_from[100]; /**< Fill before init or on_next */
4128 char email_to[100]; /**< Fill before init or on_next */
4130 unsigned int max_content_size;
4131 /**< largest possible email body size */
4133 /* Fill all the callbacks before init */
4135 int (*on_next)(struct lws_email *email);
4136 /**< (Fill in before calling lws_email_init)
4137 * called when idle, 0 = another email to send, nonzero is idle.
4138 * If you return 0, all of the email_* char arrays must be set
4139 * to something useful. */
4140 int (*on_sent)(struct lws_email *email);
4141 /**< (Fill in before calling lws_email_init)
4142 * called when transfer of the email to the SMTP server was
4143 * successful, your callback would remove the current email
4145 int (*on_get_body)(struct lws_email *email, char *buf, int len);
4146 /**< (Fill in before calling lws_email_init)
4147 * called when the body part of the queued email is about to be
4148 * sent to the SMTP server. */
4151 /* private things */
4152 uv_timer_t timeout_email; /**< private */
4153 enum lwsgs_smtp_states estate; /**< private */
4154 uv_connect_t email_connect_req; /**< private */
4155 uv_tcp_t email_client; /**< private */
4156 time_t email_connect_started; /**< private */
4157 char email_buf[256]; /**< private */
4158 char *content; /**< private */
4162 * lws_email_init() - Initialize a struct lws_email
4164 * \param email: struct lws_email to init
4165 * \param loop: libuv loop to use
4166 * \param max_content: max email content size
4168 * Prepares a struct lws_email for use ending SMTP
4170 LWS_VISIBLE LWS_EXTERN int
4171 lws_email_init(struct lws_email *email, uv_loop_t *loop, int max_content);
4174 * lws_email_check() - Request check for new email
4176 * \param email: struct lws_email context to check
4178 * Schedules a check for new emails in 1s... call this when you have queued an
4181 LWS_VISIBLE LWS_EXTERN void
4182 lws_email_check(struct lws_email *email);
4184 * lws_email_destroy() - stop using the struct lws_email
4186 * \param email: the struct lws_email context
4188 * Stop sending email using email and free allocations
4190 LWS_VISIBLE LWS_EXTERN void
4191 lws_email_destroy(struct lws_email *email);