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
36 #if defined(LWS_HAS_INTPTR_T)
38 #define lws_intptr_t intptr_t
40 typedef unsigned long long lws_intptr_t;
43 #if defined(LWS_WITH_ESP8266)
50 #include "lws_config.h"
52 #if defined(WIN32) || defined(_WIN32)
53 #ifndef WIN32_LEAN_AND_MEAN
54 #define WIN32_LEAN_AND_MEAN
64 #define _O_RDONLY 0x0000
65 #define O_RDONLY _O_RDONLY
68 // Visual studio older than 2015 and WIN_CE has only _stricmp
69 #if (defined(_MSC_VER) && _MSC_VER < 1900) || defined(_WIN32_WCE)
70 #define strcasecmp _stricmp
71 #elif !defined(__MINGW32__)
72 #define strcasecmp stricmp
74 #define getdtablesize() 30000
76 #define LWS_INLINE __inline
78 #define LWS_WARN_UNUSED_RESULT
79 #define LWS_WARN_DEPRECATED
80 #define LWS_FORMAT(string_index)
84 #define LWS_EXTERN extern __declspec(dllexport)
86 #define LWS_EXTERN extern __declspec(dllimport)
92 #define LWS_INVALID_FILE INVALID_HANDLE_VALUE
93 #define LWS_O_RDONLY _O_RDONLY
94 #define LWS_O_WRONLY _O_WRONLY
95 #define LWS_O_CREAT _O_CREAT
96 #define LWS_O_TRUNC _O_TRUNC
98 #if !defined(__MINGW32__) && (!defined(_MSC_VER) || _MSC_VER < 1900) /* Visual Studio 2015 already defines this in <stdio.h> */
99 #define lws_snprintf _snprintf
103 #define __func__ __FUNCTION__
106 #if !defined(__MINGW32__) &&(!defined(_MSC_VER) || _MSC_VER < 1900) && !defined(snprintf)
107 #define snprintf(buf,len, format,...) _snprintf_s(buf, len,len, format, __VA_ARGS__)
110 #else /* NOT WIN32 */
112 #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
113 #include <sys/capability.h>
116 #if defined(__NetBSD__) || defined(__FreeBSD__)
117 #include <netinet/in.h>
120 #define LWS_INLINE inline
121 #define LWS_O_RDONLY O_RDONLY
122 #define LWS_O_WRONLY O_WRONLY
123 #define LWS_O_CREAT O_CREAT
124 #define LWS_O_TRUNC O_TRUNC
126 #if !defined(LWS_WITH_ESP8266) && !defined(OPTEE_TA) && !defined(LWS_WITH_ESP32)
129 #define LWS_INVALID_FILE -1
131 #define getdtablesize() (30)
132 #if defined(LWS_WITH_ESP32)
133 #define LWS_INVALID_FILE NULL
135 #define LWS_INVALID_FILE NULL
139 #if defined(__GNUC__)
141 /* warn_unused_result attribute only supported by GCC 3.4 or later */
142 #if __GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
143 #define LWS_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
145 #define LWS_WARN_UNUSED_RESULT
148 #define LWS_VISIBLE __attribute__((visibility("default")))
149 #define LWS_WARN_DEPRECATED __attribute__ ((deprecated))
150 #define LWS_FORMAT(string_index) __attribute__ ((format(printf, string_index, string_index+1)))
153 #define LWS_WARN_UNUSED_RESULT
154 #define LWS_WARN_DEPRECATED
155 #define LWS_FORMAT(string_index)
158 #if defined(__ANDROID__)
160 #define getdtablesize() sysconf(_SC_OPEN_MAX)
167 #endif /* LWS_USE_LIBEV */
170 #ifdef LWS_HAVE_UV_VERSION_H
171 #include <uv-version.h>
173 #endif /* LWS_USE_LIBUV */
174 #ifdef LWS_USE_LIBEVENT
175 #include <event2/event.h>
176 #endif /* LWS_USE_LIBEVENT */
179 #define LWS_EXTERN extern
185 #if !defined(OPTEE_TA)
186 #include <sys/time.h>
191 #ifdef LWS_OPENSSL_SUPPORT
194 #ifdef USE_OLD_CYASSL
195 #include <cyassl/openssl/ssl.h>
196 #include <cyassl/error-ssl.h>
198 #include <wolfssl/openssl/ssl.h>
199 #include <wolfssl/error-ssl.h>
200 #endif /* not USE_OLD_CYASSL */
202 #include <openssl/ssl.h>
203 #if !defined(LWS_WITH_ESP32)
204 #include <openssl/err.h>
206 #endif /* not USE_WOLFSSL */
210 #define CONTEXT_PORT_NO_LISTEN -1
211 #define CONTEXT_PORT_NO_LISTEN_SERVER -2
213 /** \defgroup log Logging
217 * Lws provides flexible and filterable logging facilities, which can be
218 * used inside lws and in user code.
220 * Log categories may be individually filtered bitwise, and directed to built-in
221 * sinks for syslog-compatible logging, or a user-defined function.
225 enum lws_log_levels {
235 LLL_LATENCY = 1 << 9,
238 LLL_COUNT = 11 /* set to count of valid flags */
241 LWS_VISIBLE LWS_EXTERN void _lws_log(int filter, const char *format, ...) LWS_FORMAT(2);
242 LWS_VISIBLE LWS_EXTERN void _lws_logv(int filter, const char *format, va_list vl);
244 * lwsl_timestamp: generate logging timestamp string
246 * \param level: logging level
247 * \param p: char * buffer to take timestamp
248 * \param len: length of p
250 * returns length written in p
252 LWS_VISIBLE LWS_EXTERN int
253 lwsl_timestamp(int level, char *p, int len);
255 /* these guys are unconditionally included */
257 #define lwsl_err(...) _lws_log(LLL_ERR, __VA_ARGS__)
258 #define lwsl_user(...) _lws_log(LLL_USER, __VA_ARGS__)
260 #if !defined(LWS_WITH_NO_LOGS)
261 /* notice and warn are usually included by being compiled in */
262 #define lwsl_warn(...) _lws_log(LLL_WARN, __VA_ARGS__)
263 #define lwsl_notice(...) _lws_log(LLL_NOTICE, __VA_ARGS__)
266 * weaker logging can be deselected by telling CMake to build in RELEASE mode
267 * that gets rid of the overhead of checking while keeping _warn and _err
271 #if defined(LWS_WITH_ESP8266)
276 #if defined(LWS_WITH_NO_LOGS)
277 /* notice, warn and log are always compiled in */
278 #define lwsl_warn(...) _lws_log(LLL_WARN, __VA_ARGS__)
279 #define lwsl_notice(...) _lws_log(LLL_NOTICE, __VA_ARGS__)
281 #define lwsl_info(...) _lws_log(LLL_INFO, __VA_ARGS__)
282 #define lwsl_debug(...) _lws_log(LLL_DEBUG, __VA_ARGS__)
283 #define lwsl_parser(...) _lws_log(LLL_PARSER, __VA_ARGS__)
284 #define lwsl_header(...) _lws_log(LLL_HEADER, __VA_ARGS__)
285 #define lwsl_ext(...) _lws_log(LLL_EXT, __VA_ARGS__)
286 #define lwsl_client(...) _lws_log(LLL_CLIENT, __VA_ARGS__)
287 #define lwsl_latency(...) _lws_log(LLL_LATENCY, __VA_ARGS__)
289 * lwsl_hexdump() - helper to hexdump a buffer (DEBUG builds only)
291 * \param buf: buffer start to dump
292 * \param len: length of buffer to dump
294 LWS_VISIBLE LWS_EXTERN void lwsl_hexdump(void *buf, size_t len);
297 #if defined(LWS_WITH_NO_LOGS)
298 #define lwsl_warn(...) do {} while(0)
299 #define lwsl_notice(...) do {} while(0)
301 #define lwsl_info(...) do {} while(0)
302 #define lwsl_debug(...) do {} while(0)
303 #define lwsl_parser(...) do {} while(0)
304 #define lwsl_header(...) do {} while(0)
305 #define lwsl_ext(...) do {} while(0)
306 #define lwsl_client(...) do {} while(0)
307 #define lwsl_latency(...) do {} while(0)
308 #define lwsl_hexdump(a, b)
312 static LWS_INLINE int lws_is_be(void) {
313 const int probe = ~0xff;
315 return *(const char *)&probe;
319 * lws_set_log_level() - Set the logging bitfield
320 * \param level: OR together the LLL_ debug contexts you want output from
321 * \param log_emit_function: NULL to leave it as it is, or a user-supplied
322 * function to perform log string emission instead of
323 * the default stderr one.
325 * log level defaults to "err", "warn" and "notice" contexts enabled and
326 * emission on stderr.
328 LWS_VISIBLE LWS_EXTERN void
329 lws_set_log_level(int level,
330 void (*log_emit_function)(int level, const char *line));
333 * lwsl_emit_syslog() - helper log emit function writes to system log
335 * \param level: one of LLL_ log level indexes
336 * \param line: log string
338 * You use this by passing the function pointer to lws_set_log_level(), to set
339 * it as the log emit function, it is not called directly.
341 LWS_VISIBLE LWS_EXTERN void
342 lwsl_emit_syslog(int level, const char *line);
345 * lwsl_visible() - returns true if the log level should be printed
347 * \param level: one of LLL_ log level indexes
349 * This is useful if you have to do work to generate the log content, you
350 * can skip the work if the log level used to print it is not actually
351 * enabled at runtime.
353 LWS_VISIBLE LWS_EXTERN int
354 lwsl_visible(int level);
361 #ifndef lws_container_of
362 #define lws_container_of(P,T,M) ((T *)((char *)(P) - offsetof(T, M)))
368 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
371 /* api change list for user code to test against */
373 #define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_ARG
375 /* the struct lws_protocols has the id field present */
376 #define LWS_FEATURE_PROTOCOLS_HAS_ID_FIELD
378 /* you can call lws_get_peer_write_allowance */
379 #define LWS_FEATURE_PROTOCOLS_HAS_PEER_WRITE_ALLOWANCE
381 /* extra parameter introduced in 917f43ab821 */
382 #define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_LEN
384 /* File operations stuff exists */
385 #define LWS_FEATURE_FOPS
389 typedef SOCKET lws_sockfd_type;
390 typedef HANDLE lws_filefd_type;
391 #define lws_sockfd_valid(sfd) (!!sfd)
393 lws_sockfd_type fd; /**< file descriptor */
394 SHORT events; /**< which events to respond to */
395 SHORT revents; /**< which events happened */
397 #define LWS_POLLHUP (FD_CLOSE)
398 #define LWS_POLLIN (FD_READ | FD_ACCEPT)
399 #define LWS_POLLOUT (FD_WRITE)
403 #if defined(LWS_WITH_ESP8266)
405 #include <user_interface.h>
408 typedef struct espconn * lws_sockfd_type;
409 typedef void * lws_filefd_type;
410 #define lws_sockfd_valid(sfd) (!!sfd)
412 lws_sockfd_type fd; /**< fd related to */
413 short events; /**< which POLL... events to respond to */
414 short revents; /**< which POLL... events occurred */
416 #define POLLIN 0x0001
417 #define POLLPRI 0x0002
418 #define POLLOUT 0x0004
419 #define POLLERR 0x0008
420 #define POLLHUP 0x0010
421 #define POLLNVAL 0x0020
425 lws_sockfd_type esp8266_create_tcp_listen_socket(struct lws_vhost *vh);
426 void esp8266_tcp_stream_accept(lws_sockfd_type fd, struct lws *wsi);
432 int ets_snprintf(char *str, size_t size, const char *format, ...) LWS_FORMAT(3);
433 #define snprintf ets_snprintf
435 typedef os_timer_t uv_timer_t;
436 typedef void uv_cb_t(uv_timer_t *);
438 void os_timer_disarm(void *);
439 void os_timer_setfn(os_timer_t *, os_timer_func_t *, void *);
441 void ets_timer_arm_new(os_timer_t *, int, int, int);
443 //void os_timer_arm(os_timer_t *, int, int);
445 #define UV_VERSION_MAJOR 1
447 #define lws_uv_getloop(a, b) (NULL)
449 static inline void uv_timer_init(void *l, uv_timer_t *t)
452 memset(t, 0, sizeof(*t));
456 static inline void uv_timer_start(uv_timer_t *t, uv_cb_t *cb, int first, int rep)
458 os_timer_setfn(t, (os_timer_func_t *)cb, t);
460 os_timer_arm(t, first, !!rep);
463 static inline void uv_timer_stop(uv_timer_t *t)
469 #if defined(LWS_WITH_ESP32)
471 typedef int lws_sockfd_type;
472 typedef int lws_filefd_type;
473 #define lws_sockfd_valid(sfd) (sfd >= 0)
475 lws_sockfd_type fd; /**< fd related to */
476 short events; /**< which POLL... events to respond to */
477 short revents; /**< which POLL... events occurred */
479 #define POLLIN 0x0001
480 #define POLLPRI 0x0002
481 #define POLLOUT 0x0004
482 #define POLLERR 0x0008
483 #define POLLHUP 0x0010
484 #define POLLNVAL 0x0020
486 #include <freertos/FreeRTOS.h>
487 #include <freertos/event_groups.h>
489 #include "esp_wifi.h"
490 #include "esp_system.h"
491 #include "esp_event.h"
492 #include "esp_event_loop.h"
494 #include "driver/gpio.h"
495 #include "esp_spi_flash.h"
496 #include "freertos/timers.h"
498 #if !defined(CONFIG_FREERTOS_HZ)
499 #define CONFIG_FREERTOS_HZ 100
502 typedef TimerHandle_t uv_timer_t;
503 typedef void uv_cb_t(uv_timer_t *);
504 typedef void * uv_handle_t;
506 struct timer_mapping {
511 #define UV_VERSION_MAJOR 1
513 #define lws_uv_getloop(a, b) (NULL)
515 static inline void uv_timer_init(void *l, uv_timer_t *t)
521 extern void esp32_uvtimer_cb(TimerHandle_t t);
523 static inline void uv_timer_start(uv_timer_t *t, uv_cb_t *cb, int first, int rep)
525 struct timer_mapping *tm = (struct timer_mapping *)malloc(sizeof(*tm));
533 *t = xTimerCreate("x", pdMS_TO_TICKS(first), !!rep, tm,
534 (TimerCallbackFunction_t)esp32_uvtimer_cb);
538 static inline void uv_timer_stop(uv_timer_t *t)
543 static inline void uv_close(uv_handle_t *h, void *v)
545 free(pvTimerGetTimerID((uv_timer_t)h));
546 xTimerDelete(*(uv_timer_t *)h, 0);
549 /* ESP32 helper declarations */
552 #include <esp_partition.h>
554 #define LWS_PLUGIN_STATIC
555 #define LWS_MAGIC_REBOOT_TYPE_ADS 0x50001ffc
556 #define LWS_MAGIC_REBOOT_TYPE_REQ_FACTORY 0xb00bcafe
557 #define LWS_MAGIC_REBOOT_TYPE_FORCED_FACTORY 0xfaceb00b
558 #define LWS_MAGIC_REBOOT_TYPE_FORCED_FACTORY_BUTTON 0xf0cedfac
561 /* user code provides these */
564 lws_esp32_identify_physical_device(void);
566 /* lws-plat-esp32 provides these */
568 typedef void (*lws_cb_scan_done)(uint16_t count, wifi_ap_record_t *recs, void *arg);
571 LWSESP32_GENLED__INIT,
572 LWSESP32_GENLED__LOST_NETWORK,
573 LWSESP32_GENLED__NO_NETWORK,
574 LWSESP32_GENLED__CONN_AP,
575 LWSESP32_GENLED__GOT_IP,
579 struct lws_group_member {
580 struct lws_group_member *next;
587 struct ip4_addr addr;
588 struct ip6_addr addrv6;
592 #define LWS_SYSTEM_GROUP_MEMBER_ADD 1
593 #define LWS_SYSTEM_GROUP_MEMBER_CHANGE 2
594 #define LWS_SYSTEM_GROUP_MEMBER_REMOVE 3
596 #define LWS_GROUP_FLAG_SELF 1
608 char password[4][32];
609 char active_ssid[32];
618 enum genled_state genled;
621 lws_cb_scan_done scan_consumer;
622 void *scan_consumer_arg;
623 struct lws_group_member *first;
624 int extant_group_members;
627 struct lws_esp32_image {
634 extern struct lws_esp32 lws_esp32;
637 lws_esp32_event_passthru(void *ctx, system_event_t *event);
639 lws_esp32_wlan_config(void);
641 lws_esp32_wlan_start_ap(void);
643 lws_esp32_wlan_start_station(void);
644 struct lws_context_creation_info;
646 lws_esp32_set_creation_defaults(struct lws_context_creation_info *info);
647 extern struct lws_context *
648 lws_esp32_init(struct lws_context_creation_info *);
650 lws_esp32_wlan_nvs_get(int retry);
652 lws_nvs_set_str(nvs_handle handle, const char* key, const char* value);
654 lws_esp32_restart_guided(uint32_t type);
655 extern const esp_partition_t *
656 lws_esp_ota_get_boot_partition(void);
658 lws_esp32_get_image_info(const esp_partition_t *part, struct lws_esp32_image *i, char *json, int json_len);
660 lws_esp32_leds_network_indication(void);
662 extern uint32_t lws_esp32_get_reboot_type(void);
663 extern uint16_t lws_esp32_sine_interp(int n);
665 /* required in external code by esp32 plat (may just return if no leds) */
666 extern void lws_esp32_leds_timer_cb(TimerHandle_t th);
668 typedef int lws_sockfd_type;
669 typedef int lws_filefd_type;
670 #define lws_sockfd_valid(sfd) (sfd >= 0)
674 #define lws_pollfd pollfd
675 #define LWS_POLLHUP (POLLHUP|POLLERR)
676 #define LWS_POLLIN (POLLIN)
677 #define LWS_POLLOUT (POLLOUT)
681 #if (defined(WIN32) || defined(_WIN32)) && !defined(__MINGW32__)
683 #define ssize_t SSIZE_T
686 #if defined(WIN32) && defined(LWS_HAVE__STAT32I64)
687 #include <sys/types.h>
688 #include <sys/stat.h>
691 #if defined(LWS_HAVE_STDINT_H)
694 #if defined(WIN32) || defined(_WIN32)
696 typedef unsigned __int32 uint32_t;
697 typedef unsigned __int16 uint16_t;
698 typedef unsigned __int8 uint8_t;
700 typedef unsigned int uint32_t;
701 typedef unsigned short uint16_t;
702 typedef unsigned char uint8_t;
706 typedef unsigned long long lws_filepos_t;
707 typedef long long lws_fileofs_t;
708 typedef uint32_t lws_fop_flags_t;
710 /** struct lws_pollargs - argument structure for all external poll related calls
711 * passed in via 'in' */
712 struct lws_pollargs {
713 lws_sockfd_type fd; /**< applicable socket descriptor */
714 int events; /**< the new event mask */
715 int prev_events; /**< the previous event mask */
719 struct lws_token_limits;
721 /*! \defgroup wsclose Websocket Close
723 * ##Websocket close frame control
725 * When we close a ws connection, we can send a reason code and a short
726 * UTF-8 description back with the close packet.
731 * NOTE: These public enums are part of the abi. If you want to add one,
732 * add it at where specified so existing users are unaffected.
734 /** enum lws_close_status - RFC6455 close status codes */
735 enum lws_close_status {
736 LWS_CLOSE_STATUS_NOSTATUS = 0,
737 LWS_CLOSE_STATUS_NORMAL = 1000,
738 /**< 1000 indicates a normal closure, meaning that the purpose for
739 which the connection was established has been fulfilled. */
740 LWS_CLOSE_STATUS_GOINGAWAY = 1001,
741 /**< 1001 indicates that an endpoint is "going away", such as a server
742 going down or a browser having navigated away from a page. */
743 LWS_CLOSE_STATUS_PROTOCOL_ERR = 1002,
744 /**< 1002 indicates that an endpoint is terminating the connection due
745 to a protocol error. */
746 LWS_CLOSE_STATUS_UNACCEPTABLE_OPCODE = 1003,
747 /**< 1003 indicates that an endpoint is terminating the connection
748 because it has received a type of data it cannot accept (e.g., an
749 endpoint that understands only text data MAY send this if it
750 receives a binary message). */
751 LWS_CLOSE_STATUS_RESERVED = 1004,
752 /**< Reserved. The specific meaning might be defined in the future. */
753 LWS_CLOSE_STATUS_NO_STATUS = 1005,
754 /**< 1005 is a reserved value and MUST NOT be set as a status code in a
755 Close control frame by an endpoint. It is designated for use in
756 applications expecting a status code to indicate that no status
757 code was actually present. */
758 LWS_CLOSE_STATUS_ABNORMAL_CLOSE = 1006,
759 /**< 1006 is a reserved value and MUST NOT be set as a status code in a
760 Close control frame by an endpoint. It is designated for use in
761 applications expecting a status code to indicate that the
762 connection was closed abnormally, e.g., without sending or
763 receiving a Close control frame. */
764 LWS_CLOSE_STATUS_INVALID_PAYLOAD = 1007,
765 /**< 1007 indicates that an endpoint is terminating the connection
766 because it has received data within a message that was not
767 consistent with the type of the message (e.g., non-UTF-8 [RFC3629]
768 data within a text message). */
769 LWS_CLOSE_STATUS_POLICY_VIOLATION = 1008,
770 /**< 1008 indicates that an endpoint is terminating the connection
771 because it has received a message that violates its policy. This
772 is a generic status code that can be returned when there is no
773 other more suitable status code (e.g., 1003 or 1009) or if there
774 is a need to hide specific details about the policy. */
775 LWS_CLOSE_STATUS_MESSAGE_TOO_LARGE = 1009,
776 /**< 1009 indicates that an endpoint is terminating the connection
777 because it has received a message that is too big for it to
779 LWS_CLOSE_STATUS_EXTENSION_REQUIRED = 1010,
780 /**< 1010 indicates that an endpoint (client) is terminating the
781 connection because it has expected the server to negotiate one or
782 more extension, but the server didn't return them in the response
783 message of the WebSocket handshake. The list of extensions that
784 are needed SHOULD appear in the /reason/ part of the Close frame.
785 Note that this status code is not used by the server, because it
786 can fail the WebSocket handshake instead */
787 LWS_CLOSE_STATUS_UNEXPECTED_CONDITION = 1011,
788 /**< 1011 indicates that a server is terminating the connection because
789 it encountered an unexpected condition that prevented it from
790 fulfilling the request. */
791 LWS_CLOSE_STATUS_TLS_FAILURE = 1015,
792 /**< 1015 is a reserved value and MUST NOT be set as a status code in a
793 Close control frame by an endpoint. It is designated for use in
794 applications expecting a status code to indicate that the
795 connection was closed due to a failure to perform a TLS handshake
796 (e.g., the server certificate can't be verified). */
798 /****** add new things just above ---^ ******/
800 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY = 9999,
804 * lws_close_reason - Set reason and aux data to send with Close packet
805 * If you are going to return nonzero from the callback
806 * requesting the connection to close, you can optionally
807 * call this to set the reason the peer will be told if
810 * \param wsi: The websocket connection to set the close reason on
811 * \param status: A valid close status from websocket standard
812 * \param buf: NULL or buffer containing up to 124 bytes of auxiliary data
813 * \param len: Length of data in \param buf to send
815 LWS_VISIBLE LWS_EXTERN void
816 lws_close_reason(struct lws *wsi, enum lws_close_status status,
817 unsigned char *buf, size_t len);
823 /* needed even with extensions disabled for create context */
824 struct lws_extension;
826 /*! \defgroup usercb User Callback
828 * ##User protocol callback
830 * The protocol callback is the primary way lws interacts with
831 * user code. For one of a list of a few dozen reasons the callback gets
832 * called at some event to be handled.
834 * All of the events can be ignored, returning 0 is taken as "OK" and returning
835 * nonzero in most cases indicates that the connection should be closed.
839 struct lws_ssl_info {
845 * NOTE: These public enums are part of the abi. If you want to add one,
846 * add it at where specified so existing users are unaffected.
848 /** enum lws_callback_reasons - reason you're getting a protocol callback */
849 enum lws_callback_reasons {
850 LWS_CALLBACK_ESTABLISHED = 0,
851 /**< (VH) after the server completes a handshake with an incoming
852 * client. If you built the library with ssl support, in is a
853 * pointer to the ssl struct associated with the connection or NULL.*/
854 LWS_CALLBACK_CLIENT_CONNECTION_ERROR = 1,
855 /**< the request client connection has been unable to complete a
856 * handshake with the remote server. If in is non-NULL, you can
857 * find an error string of length len where it points to
859 * Diagnostic strings that may be returned include
861 * "getaddrinfo (ipv6) failed"
862 * "unknown address family"
863 * "getaddrinfo (ipv4) failed"
864 * "set socket opts failed"
865 * "insert wsi failed"
866 * "lws_ssl_client_connect1 failed"
867 * "lws_ssl_client_connect2 failed"
871 * "HS: Redirect code but no Location"
872 * "HS: URI did not parse"
873 * "HS: Redirect failed"
874 * "HS: Server did not return 200"
876 * "HS: disallowed by client filter"
877 * "HS: disallowed at ESTABLISHED"
878 * "HS: ACCEPT missing"
879 * "HS: ws upgrade response not 101"
880 * "HS: UPGRADE missing"
881 * "HS: Upgrade to something other than websocket"
882 * "HS: CONNECTION missing"
883 * "HS: UPGRADE malformed"
884 * "HS: PROTOCOL malformed"
885 * "HS: Cannot match protocol"
886 * "HS: EXT: list too big"
887 * "HS: EXT: failed setting defaults"
888 * "HS: EXT: failed parsing defaults"
889 * "HS: EXT: failed parsing options"
890 * "HS: EXT: Rejects server options"
891 * "HS: EXT: unknown ext"
892 * "HS: Accept hash wrong"
893 * "HS: Rejected by filter cb"
895 * "HS: SO_SNDBUF failed"
896 * "HS: Rejected at CLIENT_ESTABLISHED"
898 LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH = 2,
899 /**< this is the last chance for the client user code to examine the
900 * http headers and decide to reject the connection. If the
901 * content in the headers is interesting to the
902 * client (url, etc) it needs to copy it out at
903 * this point since it will be destroyed before
904 * the CLIENT_ESTABLISHED call */
905 LWS_CALLBACK_CLIENT_ESTABLISHED = 3,
906 /**< after your client connection completed
907 * a handshake with the remote server */
908 LWS_CALLBACK_CLOSED = 4,
909 /**< when the websocket session ends */
910 LWS_CALLBACK_CLOSED_HTTP = 5,
911 /**< when a HTTP (non-websocket) session ends */
912 LWS_CALLBACK_RECEIVE = 6,
913 /**< data has appeared for this server endpoint from a
914 * remote client, it can be found at *in and is
916 LWS_CALLBACK_RECEIVE_PONG = 7,
917 /**< servers receive PONG packets with this callback reason */
918 LWS_CALLBACK_CLIENT_RECEIVE = 8,
919 /**< data has appeared from the server for the client connection, it
920 * can be found at *in and is len bytes long */
921 LWS_CALLBACK_CLIENT_RECEIVE_PONG = 9,
922 /**< clients receive PONG packets with this callback reason */
923 LWS_CALLBACK_CLIENT_WRITEABLE = 10,
924 /**< If you call lws_callback_on_writable() on a connection, you will
925 * get one of these callbacks coming when the connection socket
926 * is able to accept another write packet without blocking.
927 * If it already was able to take another packet without blocking,
928 * you'll get this callback at the next call to the service loop
929 * function. Notice that CLIENTs get LWS_CALLBACK_CLIENT_WRITEABLE
930 * and servers get LWS_CALLBACK_SERVER_WRITEABLE. */
931 LWS_CALLBACK_SERVER_WRITEABLE = 11,
932 /**< See LWS_CALLBACK_CLIENT_WRITEABLE */
933 LWS_CALLBACK_HTTP = 12,
934 /**< an http request has come from a client that is not
935 * asking to upgrade the connection to a websocket
936 * one. This is a chance to serve http content,
937 * for example, to send a script to the client
938 * which will then open the websockets connection.
939 * in points to the URI path requested and
940 * lws_serve_http_file() makes it very
941 * simple to send back a file to the client.
942 * Normally after sending the file you are done
943 * with the http connection, since the rest of the
944 * activity will come by websockets from the script
945 * that was delivered by http, so you will want to
946 * return 1; to close and free up the connection. */
947 LWS_CALLBACK_HTTP_BODY = 13,
948 /**< the next len bytes data from the http
949 * request body HTTP connection is now available in in. */
950 LWS_CALLBACK_HTTP_BODY_COMPLETION = 14,
951 /**< the expected amount of http request body has been delivered */
952 LWS_CALLBACK_HTTP_FILE_COMPLETION = 15,
953 /**< a file requested to be sent down http link has completed. */
954 LWS_CALLBACK_HTTP_WRITEABLE = 16,
955 /**< you can write more down the http protocol link now. */
956 LWS_CALLBACK_FILTER_NETWORK_CONNECTION = 17,
957 /**< called when a client connects to
958 * the server at network level; the connection is accepted but then
959 * passed to this callback to decide whether to hang up immediately
960 * or not, based on the client IP. in contains the connection
961 * socket's descriptor. Since the client connection information is
962 * not available yet, wsi still pointing to the main server socket.
963 * Return non-zero to terminate the connection before sending or
964 * receiving anything. Because this happens immediately after the
965 * network connection from the client, there's no websocket protocol
966 * selected yet so this callback is issued only to protocol 0. */
967 LWS_CALLBACK_FILTER_HTTP_CONNECTION = 18,
968 /**< called when the request has
969 * been received and parsed from the client, but the response is
970 * not sent yet. Return non-zero to disallow the connection.
971 * user is a pointer to the connection user space allocation,
972 * in is the URI, eg, "/"
973 * In your handler you can use the public APIs
974 * lws_hdr_total_length() / lws_hdr_copy() to access all of the
975 * headers using the header enums lws_token_indexes from
976 * libwebsockets.h to check for and read the supported header
977 * presence and content before deciding to allow the http
978 * connection to proceed or to kill the connection. */
979 LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED = 19,
980 /**< A new client just had
981 * been connected, accepted, and instantiated into the pool. This
982 * callback allows setting any relevant property to it. Because this
983 * happens immediately after the instantiation of a new client,
984 * there's no websocket protocol selected yet so this callback is
985 * issued only to protocol 0. Only wsi is defined, pointing to the
986 * new client, and the return value is ignored. */
987 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION = 20,
988 /**< called when the handshake has
989 * been received and parsed from the client, but the response is
990 * not sent yet. Return non-zero to disallow the connection.
991 * user is a pointer to the connection user space allocation,
992 * in is the requested protocol name
993 * In your handler you can use the public APIs
994 * lws_hdr_total_length() / lws_hdr_copy() to access all of the
995 * headers using the header enums lws_token_indexes from
996 * libwebsockets.h to check for and read the supported header
997 * presence and content before deciding to allow the handshake
998 * to proceed or to kill the connection. */
999 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS = 21,
1000 /**< if configured for
1001 * including OpenSSL support, this callback allows your user code
1002 * to perform extra SSL_CTX_load_verify_locations() or similar
1003 * calls to direct OpenSSL where to find certificates the client
1004 * can use to confirm the remote server identity. user is the
1005 * OpenSSL SSL_CTX* */
1006 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS = 22,
1007 /**< if configured for
1008 * including OpenSSL support, this callback allows your user code
1009 * to load extra certifcates into the server which allow it to
1010 * verify the validity of certificates returned by clients. user
1011 * is the server's OpenSSL SSL_CTX* */
1012 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION = 23,
1013 /**< if the libwebsockets vhost was created with the option
1014 * LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT, then this
1015 * callback is generated during OpenSSL verification of the cert
1016 * sent from the client. It is sent to protocol[0] callback as
1017 * no protocol has been negotiated on the connection yet.
1018 * Notice that the libwebsockets context and wsi are both NULL
1019 * during this callback. See
1020 * http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html
1021 * to understand more detail about the OpenSSL callback that
1022 * generates this libwebsockets callback and the meanings of the
1023 * arguments passed. In this callback, user is the x509_ctx,
1024 * in is the ssl pointer and len is preverify_ok
1025 * Notice that this callback maintains libwebsocket return
1026 * conventions, return 0 to mean the cert is OK or 1 to fail it.
1027 * This also means that if you don't handle this callback then
1028 * the default callback action of returning 0 allows the client
1030 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER = 24,
1031 /**< this callback happens
1032 * when a client handshake is being compiled. user is NULL,
1033 * in is a char **, it's pointing to a char * which holds the
1034 * next location in the header buffer where you can add
1035 * headers, and len is the remaining space in the header buffer,
1036 * which is typically some hundreds of bytes. So, to add a canned
1037 * cookie, your handler code might look similar to:
1039 * char **p = (char **)in;
1044 * *p += sprintf(*p, "Cookie: a=b\x0d\x0a");
1048 * Notice if you add anything, you just have to take care about
1049 * the CRLF on the line you added. Obviously this callback is
1050 * optional, if you don't handle it everything is fine.
1052 * Notice the callback is coming to protocols[0] all the time,
1053 * because there is no specific protocol negotiated yet. */
1054 LWS_CALLBACK_CONFIRM_EXTENSION_OKAY = 25,
1055 /**< When the server handshake code
1056 * sees that it does support a requested extension, before
1057 * accepting the extension by additing to the list sent back to
1058 * the client it gives this callback just to check that it's okay
1059 * to use that extension. It calls back to the requested protocol
1060 * and with in being the extension name, len is 0 and user is
1061 * valid. Note though at this time the ESTABLISHED callback hasn't
1062 * happened yet so if you initialize user content there, user
1063 * content during this callback might not be useful for anything. */
1064 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED = 26,
1066 * connection is being prepared to start a handshake to a server,
1067 * each supported extension is checked with protocols[0] callback
1068 * with this reason, giving the user code a chance to suppress the
1069 * claim to support that extension by returning non-zero. If
1070 * unhandled, by default 0 will be returned and the extension
1071 * support included in the header to the server. Notice this
1072 * callback comes to protocols[0]. */
1073 LWS_CALLBACK_PROTOCOL_INIT = 27,
1074 /**< One-time call per protocol, per-vhost using it, so it can
1075 * do initial setup / allocations etc */
1076 LWS_CALLBACK_PROTOCOL_DESTROY = 28,
1077 /**< One-time call per protocol, per-vhost using it, indicating
1078 * this protocol won't get used at all after this callback, the
1079 * vhost is getting destroyed. Take the opportunity to
1080 * deallocate everything that was allocated by the protocol. */
1081 LWS_CALLBACK_WSI_CREATE = 29,
1082 /**< outermost (earliest) wsi create notification to protocols[0] */
1083 LWS_CALLBACK_WSI_DESTROY = 30,
1084 /**< outermost (latest) wsi destroy notification to protocols[0] */
1085 LWS_CALLBACK_GET_THREAD_ID = 31,
1086 /**< lws can accept callback when writable requests from other
1087 * threads, if you implement this callback and return an opaque
1088 * current thread ID integer. */
1090 /* external poll() management support */
1091 LWS_CALLBACK_ADD_POLL_FD = 32,
1092 /**< lws normally deals with its poll() or other event loop
1093 * internally, but in the case you are integrating with another
1094 * server you will need to have lws sockets share a
1095 * polling array with the other server. This and the other
1096 * POLL_FD related callbacks let you put your specialized
1097 * poll array interface code in the callback for protocol 0, the
1098 * first protocol you support, usually the HTTP protocol in the
1100 * This callback happens when a socket needs to be
1101 * added to the polling loop: in points to a struct
1102 * lws_pollargs; the fd member of the struct is the file
1103 * descriptor, and events contains the active events
1105 * If you are using the internal lws polling / event loop
1106 * you can just ignore these callbacks. */
1107 LWS_CALLBACK_DEL_POLL_FD = 33,
1108 /**< This callback happens when a socket descriptor
1109 * needs to be removed from an external polling array. in is
1110 * again the struct lws_pollargs containing the fd member
1111 * to be removed. If you are using the internal polling
1112 * loop, you can just ignore it. */
1113 LWS_CALLBACK_CHANGE_MODE_POLL_FD = 34,
1114 /**< This callback happens when lws wants to modify the events for
1116 * in is the struct lws_pollargs with the fd to change.
1117 * The new event mask is in events member and the old mask is in
1118 * the prev_events member.
1119 * If you are using the internal polling loop, you can just ignore
1121 LWS_CALLBACK_LOCK_POLL = 35,
1122 /**< These allow the external poll changes driven
1123 * by lws to participate in an external thread locking
1124 * scheme around the changes, so the whole thing is threadsafe.
1125 * These are called around three activities in the library,
1126 * - inserting a new wsi in the wsi / fd table (len=1)
1127 * - deleting a wsi from the wsi / fd table (len=1)
1128 * - changing a wsi's POLLIN/OUT state (len=0)
1129 * Locking and unlocking external synchronization objects when
1130 * len == 1 allows external threads to be synchronized against
1131 * wsi lifecycle changes if it acquires the same lock for the
1132 * duration of wsi dereference from the other thread context. */
1133 LWS_CALLBACK_UNLOCK_POLL = 36,
1134 /**< See LWS_CALLBACK_LOCK_POLL, ignore if using lws internal poll */
1136 LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY = 37,
1137 /**< if configured for including OpenSSL support but no private key
1138 * file has been specified (ssl_private_key_filepath is NULL), this is
1139 * called to allow the user to set the private key directly via
1140 * libopenssl and perform further operations if required; this might be
1141 * useful in situations where the private key is not directly accessible
1142 * by the OS, for example if it is stored on a smartcard.
1143 * user is the server's OpenSSL SSL_CTX* */
1144 LWS_CALLBACK_WS_PEER_INITIATED_CLOSE = 38,
1145 /**< The peer has sent an unsolicited Close WS packet. in and
1146 * len are the optional close code (first 2 bytes, network
1147 * order) and the optional additional information which is not
1148 * defined in the standard, and may be a string or non-human- readable data.
1149 * If you return 0 lws will echo the close and then close the
1150 * connection. If you return nonzero lws will just close the
1153 LWS_CALLBACK_WS_EXT_DEFAULTS = 39,
1156 LWS_CALLBACK_CGI = 40,
1158 LWS_CALLBACK_CGI_TERMINATED = 41,
1160 LWS_CALLBACK_CGI_STDIN_DATA = 42,
1162 LWS_CALLBACK_CGI_STDIN_COMPLETED = 43,
1164 LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP = 44,
1166 LWS_CALLBACK_CLOSED_CLIENT_HTTP = 45,
1168 LWS_CALLBACK_RECEIVE_CLIENT_HTTP = 46,
1170 LWS_CALLBACK_COMPLETED_CLIENT_HTTP = 47,
1172 LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ = 48,
1174 LWS_CALLBACK_HTTP_BIND_PROTOCOL = 49,
1176 LWS_CALLBACK_HTTP_DROP_PROTOCOL = 50,
1178 LWS_CALLBACK_CHECK_ACCESS_RIGHTS = 51,
1180 LWS_CALLBACK_PROCESS_HTML = 52,
1182 LWS_CALLBACK_ADD_HEADERS = 53,
1184 LWS_CALLBACK_SESSION_INFO = 54,
1187 LWS_CALLBACK_GS_EVENT = 55,
1189 LWS_CALLBACK_HTTP_PMO = 56,
1190 /**< per-mount options for this connection, called before
1191 * the normal LWS_CALLBACK_HTTP when the mount has per-mount
1194 LWS_CALLBACK_CLIENT_HTTP_WRITEABLE = 57,
1195 /**< when doing an HTTP type client connection, you can call
1196 * lws_client_http_body_pending(wsi, 1) from
1197 * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER to get these callbacks
1198 * sending the HTTP headers.
1200 * From this callback, when you have sent everything, you should let
1201 * lws know by calling lws_client_http_body_pending(wsi, 0)
1203 LWS_CALLBACK_OPENSSL_PERFORM_SERVER_CERT_VERIFICATION = 58,
1204 /**< Similar to LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION
1205 * this callback is called during OpenSSL verification of the cert
1206 * sent from the server to the client. It is sent to protocol[0]
1207 * callback as no protocol has been negotiated on the connection yet.
1208 * Notice that the wsi is set because lws_client_connect_via_info was
1211 * See http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html
1212 * to understand more detail about the OpenSSL callback that
1213 * generates this libwebsockets callback and the meanings of the
1214 * arguments passed. In this callback, user is the x509_ctx,
1215 * in is the ssl pointer and len is preverify_ok.
1217 * THIS IS NOT RECOMMENDED BUT if a cert validation error shall be
1218 * overruled and cert shall be accepted as ok,
1219 * X509_STORE_CTX_set_error((X509_STORE_CTX*)user, X509_V_OK); must be
1220 * called and return value must be 0 to mean the cert is OK;
1221 * returning 1 will fail the cert in any case.
1223 * This also means that if you don't handle this callback then
1224 * the default callback action of returning 0 will not accept the
1225 * certificate in case of a validation error decided by the SSL lib.
1227 * This is expected and secure behaviour when validating certificates.
1229 * Note: LCCSCF_ALLOW_SELFSIGNED and
1230 * LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK still work without this
1231 * callback being implemented.
1233 LWS_CALLBACK_RAW_RX = 59,
1234 /**< RAW mode connection RX */
1235 LWS_CALLBACK_RAW_CLOSE = 60,
1236 /**< RAW mode connection is closing */
1237 LWS_CALLBACK_RAW_WRITEABLE = 61,
1238 /**< RAW mode connection may be written */
1239 LWS_CALLBACK_RAW_ADOPT = 62,
1240 /**< RAW mode connection was adopted (equivalent to 'wsi created') */
1241 LWS_CALLBACK_RAW_ADOPT_FILE = 63,
1242 /**< RAW mode file was adopted (equivalent to 'wsi created') */
1243 LWS_CALLBACK_RAW_RX_FILE = 64,
1244 /**< RAW mode file has something to read */
1245 LWS_CALLBACK_RAW_WRITEABLE_FILE = 65,
1246 /**< RAW mode file is writeable */
1247 LWS_CALLBACK_RAW_CLOSE_FILE = 66,
1248 /**< RAW mode wsi that adopted a file is closing */
1249 LWS_CALLBACK_SSL_INFO = 67,
1250 /**< SSL connections only. An event you registered an
1251 * interest in at the vhost has occurred on a connection
1252 * using the vhost. @in is a pointer to a
1253 * struct lws_ssl_info containing information about the
1256 /****** add new things just above ---^ ******/
1258 LWS_CALLBACK_USER = 1000,
1259 /**< user code can use any including above without fear of clashes */
1265 * typedef lws_callback_function() - User server actions
1266 * \param wsi: Opaque websocket instance pointer
1267 * \param reason: The reason for the call
1268 * \param user: Pointer to per-session user data allocated by library
1269 * \param in: Pointer used for some callback reasons
1270 * \param len: Length set for some callback reasons
1272 * This callback is the way the user controls what is served. All the
1273 * protocol detail is hidden and handled by the library.
1275 * For each connection / session there is user data allocated that is
1276 * pointed to by "user". You set the size of this user data area when
1277 * the library is initialized with lws_create_server.
1280 lws_callback_function(struct lws *wsi, enum lws_callback_reasons reason,
1281 void *user, void *in, size_t len);
1284 /*! \defgroup extensions
1286 * ##Extension releated functions
1288 * Ws defines optional extensions, lws provides the ability to implement these
1289 * in user code if so desired.
1291 * We provide one extensions permessage-deflate.
1296 * NOTE: These public enums are part of the abi. If you want to add one,
1297 * add it at where specified so existing users are unaffected.
1299 enum lws_extension_callback_reasons {
1300 LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT = 0,
1301 LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT = 1,
1302 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT = 2,
1303 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT = 3,
1304 LWS_EXT_CB_CONSTRUCT = 4,
1305 LWS_EXT_CB_CLIENT_CONSTRUCT = 5,
1306 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE = 6,
1307 LWS_EXT_CB_CHECK_OK_TO_PROPOSE_EXTENSION = 7,
1308 LWS_EXT_CB_DESTROY = 8,
1309 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING = 9,
1310 LWS_EXT_CB_ANY_WSI_ESTABLISHED = 10,
1311 LWS_EXT_CB_PACKET_RX_PREPARSE = 11,
1312 LWS_EXT_CB_PACKET_TX_PRESEND = 12,
1313 LWS_EXT_CB_PACKET_TX_DO_SEND = 13,
1314 LWS_EXT_CB_HANDSHAKE_REPLY_TX = 14,
1315 LWS_EXT_CB_FLUSH_PENDING_TX = 15,
1316 LWS_EXT_CB_EXTENDED_PAYLOAD_RX = 16,
1317 LWS_EXT_CB_CAN_PROXY_CLIENT_CONNECTION = 17,
1318 LWS_EXT_CB_1HZ = 18,
1319 LWS_EXT_CB_REQUEST_ON_WRITEABLE = 19,
1320 LWS_EXT_CB_IS_WRITEABLE = 20,
1321 LWS_EXT_CB_PAYLOAD_TX = 21,
1322 LWS_EXT_CB_PAYLOAD_RX = 22,
1323 LWS_EXT_CB_OPTION_DEFAULT = 23,
1324 LWS_EXT_CB_OPTION_SET = 24,
1325 LWS_EXT_CB_OPTION_CONFIRM = 25,
1326 LWS_EXT_CB_NAMED_OPTION_SET = 26,
1328 /****** add new things just above ---^ ******/
1331 /** enum lws_ext_options_types */
1332 enum lws_ext_options_types {
1333 EXTARG_NONE, /**< does not take an argument */
1334 EXTARG_DEC, /**< requires a decimal argument */
1335 EXTARG_OPT_DEC /**< may have an optional decimal argument */
1337 /* Add new things just above here ---^
1338 * This is part of the ABI, don't needlessly break compatibility */
1341 /** struct lws_ext_options - Option arguments to the extension. These are
1342 * used in the negotiation at ws upgrade time.
1343 * The helper function lws_ext_parse_options()
1344 * uses these to generate callbacks */
1345 struct lws_ext_options {
1346 const char *name; /**< Option name, eg, "server_no_context_takeover" */
1347 enum lws_ext_options_types type; /**< What kind of args the option can take */
1349 /* Add new things just above here ---^
1350 * This is part of the ABI, don't needlessly break compatibility */
1353 /** struct lws_ext_option_arg */
1354 struct lws_ext_option_arg {
1355 const char *option_name; /**< may be NULL, option_index used then */
1356 int option_index; /**< argument ordinal to use if option_name missing */
1357 const char *start; /**< value */
1358 int len; /**< length of value */
1362 * typedef lws_extension_callback_function() - Hooks to allow extensions to operate
1363 * \param context: Websockets context
1364 * \param ext: This extension
1365 * \param wsi: Opaque websocket instance pointer
1366 * \param reason: The reason for the call
1367 * \param user: Pointer to ptr to per-session user data allocated by library
1368 * \param in: Pointer used for some callback reasons
1369 * \param len: Length set for some callback reasons
1371 * Each extension that is active on a particular connection receives
1372 * callbacks during the connection lifetime to allow the extension to
1373 * operate on websocket data and manage itself.
1375 * Libwebsockets takes care of allocating and freeing "user" memory for
1376 * each active extension on each connection. That is what is pointed to
1377 * by the user parameter.
1379 * LWS_EXT_CB_CONSTRUCT: called when the server has decided to
1380 * select this extension from the list provided by the client,
1381 * just before the server will send back the handshake accepting
1382 * the connection with this extension active. This gives the
1383 * extension a chance to initialize its connection context found
1386 * LWS_EXT_CB_CLIENT_CONSTRUCT: same as LWS_EXT_CB_CONSTRUCT
1387 * but called when client is instantiating this extension. Some
1388 * extensions will work the same on client and server side and then
1389 * you can just merge handlers for both CONSTRUCTS.
1391 * LWS_EXT_CB_DESTROY: called when the connection the extension was
1392 * being used on is about to be closed and deallocated. It's the
1393 * last chance for the extension to deallocate anything it has
1394 * allocated in the user data (pointed to by user) before the
1395 * user data is deleted. This same callback is used whether you
1396 * are in client or server instantiation context.
1398 * LWS_EXT_CB_PACKET_RX_PREPARSE: when this extension was active on
1399 * a connection, and a packet of data arrived at the connection,
1400 * it is passed to this callback to give the extension a chance to
1401 * change the data, eg, decompress it. user is pointing to the
1402 * extension's private connection context data, in is pointing
1403 * to an lws_tokens struct, it consists of a char * pointer called
1404 * token, and an int called token_len. At entry, these are
1405 * set to point to the received buffer and set to the content
1406 * length. If the extension will grow the content, it should use
1407 * a new buffer allocated in its private user context data and
1408 * set the pointed-to lws_tokens members to point to its buffer.
1410 * LWS_EXT_CB_PACKET_TX_PRESEND: this works the same way as
1411 * LWS_EXT_CB_PACKET_RX_PREPARSE above, except it gives the
1412 * extension a chance to change websocket data just before it will
1413 * be sent out. Using the same lws_token pointer scheme in in,
1414 * the extension can change the buffer and the length to be
1415 * transmitted how it likes. Again if it wants to grow the
1416 * buffer safely, it should copy the data into its own buffer and
1417 * set the lws_tokens token pointer to it.
1419 * LWS_EXT_CB_ARGS_VALIDATE:
1422 lws_extension_callback_function(struct lws_context *context,
1423 const struct lws_extension *ext, struct lws *wsi,
1424 enum lws_extension_callback_reasons reason,
1425 void *user, void *in, size_t len);
1427 /** struct lws_extension - An extension we support */
1428 struct lws_extension {
1429 const char *name; /**< Formal extension name, eg, "permessage-deflate" */
1430 lws_extension_callback_function *callback; /**< Service callback */
1431 const char *client_offer; /**< String containing exts and options client offers */
1433 /* Add new things just above here ---^
1434 * This is part of the ABI, don't needlessly break compatibility */
1438 * lws_set_extension_option(): set extension option if possible
1440 * \param wsi: websocket connection
1441 * \param ext_name: name of ext, like "permessage-deflate"
1442 * \param opt_name: name of option, like "rx_buf_size"
1443 * \param opt_val: value to set option to
1445 LWS_VISIBLE LWS_EXTERN int
1446 lws_set_extension_option(struct lws *wsi, const char *ext_name,
1447 const char *opt_name, const char *opt_val);
1449 #ifndef LWS_NO_EXTENSIONS
1450 /* lws_get_internal_extensions() - DEPRECATED
1452 * \Deprecated There is no longer a set internal extensions table. The table is provided
1453 * by user code along with application-specific settings. See the test
1454 * client and server for how to do.
1456 static LWS_INLINE LWS_WARN_DEPRECATED const struct lws_extension *
1457 lws_get_internal_extensions(void) { return NULL; }
1460 * lws_ext_parse_options() - deal with parsing negotiated extension options
1462 * \param ext: related extension struct
1463 * \param wsi: websocket connection
1464 * \param ext_user: per-connection extension private data
1465 * \param opts: list of supported options
1466 * \param o: option string to parse
1467 * \param len: length
1469 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
1470 lws_ext_parse_options(const struct lws_extension *ext, struct lws *wsi,
1471 void *ext_user, const struct lws_ext_options *opts,
1472 const char *o, int len);
1475 /** lws_extension_callback_pm_deflate() - extension for RFC7692
1477 * \param context: lws context
1478 * \param ext: related lws_extension struct
1479 * \param wsi: websocket connection
1480 * \param reason: incoming callback reason
1481 * \param user: per-connection extension private data
1482 * \param in: pointer parameter
1483 * \param len: length parameter
1485 * Built-in callback implementing RFC7692 permessage-deflate
1488 int lws_extension_callback_pm_deflate(
1489 struct lws_context *context, const struct lws_extension *ext,
1490 struct lws *wsi, enum lws_extension_callback_reasons reason,
1491 void *user, void *in, size_t len);
1494 * The internal exts are part of the public abi
1495 * If we add more extensions, publish the callback here ------v
1499 /*! \defgroup Protocols-and-Plugins Protocols and Plugins
1502 * ##Protocol and protocol plugin -related apis
1504 * Protocols bind ws protocol names to a custom callback specific to that
1505 * protocol implementaion.
1507 * A list of protocols can be passed in at context creation time, but it is
1508 * also legal to leave that NULL and add the protocols and their callback code
1511 * Plugins are much preferable compared to cut and pasting code into an
1512 * application each time, since they can be used standalone.
1515 /** struct lws_protocols - List of protocols and handlers client or server
1518 struct lws_protocols {
1520 /**< Protocol name that must match the one given in the client
1521 * Javascript new WebSocket(url, 'protocol') name. */
1522 lws_callback_function *callback;
1523 /**< The service callback used for this protocol. It allows the
1524 * service action for an entire protocol to be encapsulated in
1525 * the protocol-specific callback */
1526 size_t per_session_data_size;
1527 /**< Each new connection using this protocol gets
1528 * this much memory allocated on connection establishment and
1529 * freed on connection takedown. A pointer to this per-connection
1530 * allocation is passed into the callback in the 'user' parameter */
1531 size_t rx_buffer_size;
1532 /**< lws allocates this much space for rx data and informs callback
1533 * when something came. Due to rx flow control, the callback may not
1534 * be able to consume it all without having to return to the event
1535 * loop. That is supported in lws.
1537 * If .tx_packet_size is 0, this also controls how much may be sent at once
1538 * for backwards compatibility.
1541 /**< ignored by lws, but useful to contain user information bound
1542 * to the selected protocol. For example if this protocol was
1543 * called "myprotocol-v2", you might set id to 2, and the user
1544 * code that acts differently according to the version can do so by
1545 * switch (wsi->protocol->id), user code might use some bits as
1546 * capability flags based on selected protocol version, etc. */
1547 void *user; /**< ignored by lws, but user code can pass a pointer
1548 here it can later access from the protocol callback */
1549 size_t tx_packet_size;
1550 /**< 0 indicates restrict send() size to .rx_buffer_size for backwards-
1552 * If greater than zero, a single send() is restricted to this amount
1553 * and any remainder is buffered by lws and sent afterwards also in
1554 * these size chunks. Since that is expensive, it's preferable
1555 * to restrict one fragment you are trying to send to match this
1559 /* Add new things just above here ---^
1560 * This is part of the ABI, don't needlessly break compatibility */
1566 * lws_vhost_name_to_protocol() - get vhost's protocol object from its name
1568 * \param vh: vhost to search
1569 * \param name: protocol name
1571 * Returns NULL or a pointer to the vhost's protocol of the requested name
1573 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1574 lws_vhost_name_to_protocol(struct lws_vhost *vh, const char *name);
1577 * lws_get_protocol() - Returns a protocol pointer from a websocket
1579 * \param wsi: pointer to struct websocket you want to know the protocol of
1582 * Some apis can act on all live connections of a given protocol,
1583 * this is how you can get a pointer to the active protocol if needed.
1585 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1586 lws_get_protocol(struct lws *wsi);
1588 /** lws_protocol_get() - deprecated: use lws_get_protocol */
1589 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1590 lws_protocol_get(struct lws *wsi) LWS_WARN_DEPRECATED;
1593 * lws_protocol_vh_priv_zalloc() - Allocate and zero down a protocol's per-vhost
1595 * \param vhost: vhost the instance is related to
1596 * \param prot: protocol the instance is related to
1597 * \param size: bytes to allocate
1599 * Protocols often find it useful to allocate a per-vhost struct, this is a
1600 * helper to be called in the per-vhost init LWS_CALLBACK_PROTOCOL_INIT
1602 LWS_VISIBLE LWS_EXTERN void *
1603 lws_protocol_vh_priv_zalloc(struct lws_vhost *vhost, const struct lws_protocols *prot,
1607 * lws_protocol_vh_priv_get() - retreive a protocol's per-vhost storage
1609 * \param vhost: vhost the instance is related to
1610 * \param prot: protocol the instance is related to
1612 * Recover a pointer to the allocated per-vhost storage for the protocol created
1613 * by lws_protocol_vh_priv_zalloc() earlier
1615 LWS_VISIBLE LWS_EXTERN void *
1616 lws_protocol_vh_priv_get(struct lws_vhost *vhost, const struct lws_protocols *prot);
1619 * lws_finalize_startup() - drop initial process privileges
1621 * \param context: lws context
1623 * This is called after the end of the vhost protocol initializations, but
1624 * you may choose to call it earlier
1626 LWS_VISIBLE LWS_EXTERN int
1627 lws_finalize_startup(struct lws_context *context);
1629 LWS_VISIBLE LWS_EXTERN int
1630 lws_protocol_init(struct lws_context *context);
1632 #ifdef LWS_WITH_PLUGINS
1634 /* PLUGINS implies LIBUV */
1636 #define LWS_PLUGIN_API_MAGIC 180
1638 /** struct lws_plugin_capability - how a plugin introduces itself to lws */
1639 struct lws_plugin_capability {
1640 unsigned int api_magic; /**< caller fills this in, plugin fills rest */
1641 const struct lws_protocols *protocols; /**< array of supported protocols provided by plugin */
1642 int count_protocols; /**< how many protocols */
1643 const struct lws_extension *extensions; /**< array of extensions provided by plugin */
1644 int count_extensions; /**< how many extensions */
1647 typedef int (*lws_plugin_init_func)(struct lws_context *,
1648 struct lws_plugin_capability *);
1649 typedef int (*lws_plugin_destroy_func)(struct lws_context *);
1651 /** struct lws_plugin */
1653 struct lws_plugin *list; /**< linked list */
1654 #if (UV_VERSION_MAJOR > 0)
1655 uv_lib_t lib; /**< shared library pointer */
1657 void *l; /**< so we can compile on ancient libuv */
1659 char name[64]; /**< name of the plugin */
1660 struct lws_plugin_capability caps; /**< plugin capabilities */
1668 /*! \defgroup generic-sessions plugin: generic-sessions
1669 * \ingroup Protocols-and-Plugins
1671 * ##Plugin Generic-sessions related
1673 * generic-sessions plugin provides a reusable, generic session and login /
1674 * register / forgot password framework including email verification.
1678 #define LWSGS_EMAIL_CONTENT_SIZE 16384
1679 /**< Maximum size of email we might send */
1681 /* SHA-1 binary and hexified versions */
1682 /** typedef struct lwsgw_hash_bin */
1683 typedef struct { unsigned char bin[20]; /**< binary representation of hash */} lwsgw_hash_bin;
1684 /** typedef struct lwsgw_hash */
1685 typedef struct { char id[41]; /**< ascii hex representation of hash */ } lwsgw_hash;
1687 /** enum lwsgs_auth_bits */
1688 enum lwsgs_auth_bits {
1689 LWSGS_AUTH_LOGGED_IN = 1, /**< user is logged in as somebody */
1690 LWSGS_AUTH_ADMIN = 2, /**< logged in as the admin user */
1691 LWSGS_AUTH_VERIFIED = 4, /**< user has verified his email */
1692 LWSGS_AUTH_FORGOT_FLOW = 8, /**< he just completed "forgot password" flow */
1695 /** struct lws_session_info - information about user session status */
1696 struct lws_session_info {
1697 char username[32]; /**< username logged in as, or empty string */
1698 char email[100]; /**< email address associated with login, or empty string */
1699 char ip[72]; /**< ip address session was started from */
1700 unsigned int mask; /**< access rights mask associated with session
1701 * see enum lwsgs_auth_bits */
1702 char session[42]; /**< session id string, usable as opaque uid when not logged in */
1705 /** enum lws_gs_event */
1707 LWSGSE_CREATED, /**< a new user was created */
1708 LWSGSE_DELETED /**< an existing user was deleted */
1711 /** struct lws_gs_event_args */
1712 struct lws_gs_event_args {
1713 enum lws_gs_event event; /**< which event happened */
1714 const char *username; /**< which username the event happened to */
1715 const char *email; /**< the email address of that user */
1721 /*! \defgroup context-and-vhost
1724 * ##Context and Vhost releated functions
1726 * LWS requires that there is one context, in which you may define multiple
1727 * vhosts. Each vhost is a virtual host, with either its own listen port
1728 * or sharing an existing one. Each vhost has its own SSL context that can
1729 * be set up individually or left disabled.
1731 * If you don't care about multiple "site" support, you can ignore it and
1732 * lws will create a single default vhost at context creation time.
1737 * NOTE: These public enums are part of the abi. If you want to add one,
1738 * add it at where specified so existing users are unaffected.
1741 /** enum lws_context_options - context and vhost options */
1742 enum lws_context_options {
1743 LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT = (1 << 1) |
1745 /**< (VH) Don't allow the connection unless the client has a
1746 * client cert that we recognize; provides
1747 * LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT */
1748 LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME = (1 << 2),
1749 /**< (CTX) Don't try to get the server's hostname */
1750 LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT = (1 << 3) |
1752 /**< (VH) Allow non-SSL (plaintext) connections on the same
1753 * port as SSL is listening... undermines the security of SSL;
1754 * provides LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT */
1755 LWS_SERVER_OPTION_LIBEV = (1 << 4),
1756 /**< (CTX) Use libev event loop */
1757 LWS_SERVER_OPTION_DISABLE_IPV6 = (1 << 5),
1758 /**< (VH) Disable IPV6 support */
1759 LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS = (1 << 6),
1760 /**< (VH) Don't load OS CA certs, you will need to load your
1762 LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED = (1 << 7),
1763 /**< (VH) Accept connections with no valid Cert (eg, selfsigned) */
1764 LWS_SERVER_OPTION_VALIDATE_UTF8 = (1 << 8),
1765 /**< (VH) Check UT-8 correctness */
1766 LWS_SERVER_OPTION_SSL_ECDH = (1 << 9) |
1768 /**< (VH) initialize ECDH ciphers */
1769 LWS_SERVER_OPTION_LIBUV = (1 << 10),
1770 /**< (CTX) Use libuv event loop */
1771 LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS = (1 << 11) |
1773 /**< (VH) Use http redirect to force http to https
1774 * (deprecated: use mount redirection) */
1775 LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT = (1 << 12),
1776 /**< (CTX) Initialize the SSL library at all */
1777 LWS_SERVER_OPTION_EXPLICIT_VHOSTS = (1 << 13),
1778 /**< (CTX) Only create the context when calling context
1779 * create api, implies user code will create its own vhosts */
1780 LWS_SERVER_OPTION_UNIX_SOCK = (1 << 14),
1781 /**< (VH) Use Unix socket */
1782 LWS_SERVER_OPTION_STS = (1 << 15),
1783 /**< (VH) Send Strict Transport Security header, making
1784 * clients subsequently go to https even if user asked for http */
1785 LWS_SERVER_OPTION_IPV6_V6ONLY_MODIFY = (1 << 16),
1786 /**< (VH) Enable LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE to take effect */
1787 LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE = (1 << 17),
1788 /**< (VH) if set, only ipv6 allowed on the vhost */
1789 LWS_SERVER_OPTION_UV_NO_SIGSEGV_SIGFPE_SPIN = (1 << 18),
1790 /**< (CTX) Libuv only: Do not spin on SIGSEGV / SIGFPE. A segfault
1791 * normally makes the lib spin so you can attach a debugger to it
1792 * even if it happened without a debugger in place. You can disable
1793 * that by giving this option.
1795 LWS_SERVER_OPTION_JUST_USE_RAW_ORIGIN = (1 << 19),
1796 /**< For backwards-compatibility reasons, by default
1797 * lws prepends "http://" to the origin you give in the client
1798 * connection info struct. If you give this flag when you create
1799 * the context, only the string you give in the client connect
1800 * info for .origin (if any) will be used directly.
1802 LWS_SERVER_OPTION_FALLBACK_TO_RAW = (1 << 20),
1803 /**< (VH) if invalid http is coming in the first line, */
1804 LWS_SERVER_OPTION_LIBEVENT = (1 << 21),
1805 /**< (CTX) Use libevent event loop */
1806 LWS_SERVER_OPTION_ONLY_RAW = (1 << 22),
1807 /**< (VH) All connections to this vhost / port are RAW as soon as
1808 * the connection is accepted, no HTTP is going to be coming.
1810 LWS_SERVER_OPTION_ALLOW_LISTEN_SHARE = (1 << 23),
1811 /**< (VH) Set to allow multiple listen sockets on one interface +
1812 * address + port. The default is to strictly allow only one
1813 * listen socket at a time. This is automatically selected if you
1814 * have multiple service threads.
1817 /****** add new things just above ---^ ******/
1820 #define lws_check_opt(c, f) (((c) & (f)) == (f))
1822 struct lws_plat_file_ops;
1824 /** struct lws_context_creation_info - parameters to create context and /or vhost with
1826 * This is also used to create vhosts.... if LWS_SERVER_OPTION_EXPLICIT_VHOSTS
1827 * is not given, then for backwards compatibility one vhost is created at
1828 * context-creation time using the info from this struct.
1830 * If LWS_SERVER_OPTION_EXPLICIT_VHOSTS is given, then no vhosts are created
1831 * at the same time as the context, they are expected to be created afterwards.
1833 struct lws_context_creation_info {
1835 /**< VHOST: Port to listen on. Use CONTEXT_PORT_NO_LISTEN to suppress
1836 * listening for a client. Use CONTEXT_PORT_NO_LISTEN_SERVER if you are
1837 * writing a server but you are using \ref sock-adopt instead of the
1838 * built-in listener */
1840 /**< VHOST: NULL to bind the listen socket to all interfaces, or the
1841 * interface name, eg, "eth2"
1842 * If options specifies LWS_SERVER_OPTION_UNIX_SOCK, this member is
1843 * the pathname of a UNIX domain socket. you can use the UNIX domain
1844 * sockets in abstract namespace, by prepending an at symbol to the
1846 const struct lws_protocols *protocols;
1847 /**< VHOST: Array of structures listing supported protocols and a protocol-
1848 * specific callback for each one. The list is ended with an
1849 * entry that has a NULL callback pointer. */
1850 const struct lws_extension *extensions;
1851 /**< VHOST: NULL or array of lws_extension structs listing the
1852 * extensions this context supports. */
1853 const struct lws_token_limits *token_limits;
1854 /**< CONTEXT: NULL or struct lws_token_limits pointer which is initialized
1855 * with a token length limit for each possible WSI_TOKEN_ */
1856 const char *ssl_private_key_password;
1857 /**< VHOST: NULL or the passphrase needed for the private key */
1858 const char *ssl_cert_filepath;
1859 /**< VHOST: If libwebsockets was compiled to use ssl, and you want
1860 * to listen using SSL, set to the filepath to fetch the
1861 * server cert from, otherwise NULL for unencrypted */
1862 const char *ssl_private_key_filepath;
1863 /**< VHOST: filepath to private key if wanting SSL mode;
1864 * if this is set to NULL but sll_cert_filepath is set, the
1865 * OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY callback is called
1866 * to allow setting of the private key directly via openSSL
1868 const char *ssl_ca_filepath;
1869 /**< VHOST: CA certificate filepath or NULL */
1870 const char *ssl_cipher_list;
1871 /**< VHOST: List of valid ciphers to use (eg,
1872 * "RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL"
1873 * or you can leave it as NULL to get "DEFAULT" */
1874 const char *http_proxy_address;
1875 /**< VHOST: If non-NULL, attempts to proxy via the given address.
1876 * If proxy auth is required, use format "username:password\@server:port" */
1877 unsigned int http_proxy_port;
1878 /**< VHOST: If http_proxy_address was non-NULL, uses this port */
1880 /**< CONTEXT: group id to change to after setting listen socket, or -1. */
1882 /**< CONTEXT: user id to change to after setting listen socket, or -1. */
1883 unsigned int options;
1884 /**< VHOST + CONTEXT: 0, or LWS_SERVER_OPTION_... bitfields */
1886 /**< CONTEXT: optional user pointer that can be recovered via the context
1887 * pointer using lws_context_user */
1889 /**< CONTEXT: 0 for no TCP keepalive, otherwise apply this keepalive
1890 * timeout to all libwebsocket sockets, client or server */
1892 /**< CONTEXT: if ka_time was nonzero, after the timeout expires how many
1893 * times to try to get a response from the peer before giving up
1894 * and killing the connection */
1896 /**< CONTEXT: if ka_time was nonzero, how long to wait before each ka_probes
1898 #ifdef LWS_OPENSSL_SUPPORT
1899 SSL_CTX *provided_client_ssl_ctx;
1900 /**< CONTEXT: If non-null, swap out libwebsockets ssl
1901 * implementation for the one provided by provided_ssl_ctx.
1902 * Libwebsockets no longer is responsible for freeing the context
1903 * if this option is selected. */
1904 #else /* maintain structure layout either way */
1905 void *provided_client_ssl_ctx; /**< dummy if ssl disabled */
1908 short max_http_header_data;
1909 /**< CONTEXT: The max amount of header payload that can be handled
1910 * in an http request (unrecognized header payload is dropped) */
1911 short max_http_header_pool;
1912 /**< CONTEXT: The max number of connections with http headers that
1913 * can be processed simultaneously (the corresponding memory is
1914 * allocated for the lifetime of the context). If the pool is
1915 * busy new incoming connections must wait for accept until one
1918 unsigned int count_threads;
1919 /**< CONTEXT: how many contexts to create in an array, 0 = 1 */
1920 unsigned int fd_limit_per_thread;
1921 /**< CONTEXT: nonzero means restrict each service thread to this
1922 * many fds, 0 means the default which is divide the process fd
1923 * limit by the number of threads. */
1924 unsigned int timeout_secs;
1925 /**< VHOST: various processes involving network roundtrips in the
1926 * library are protected from hanging forever by timeouts. If
1927 * nonzero, this member lets you set the timeout used in seconds.
1928 * Otherwise a default timeout is used. */
1929 const char *ecdh_curve;
1930 /**< VHOST: if NULL, defaults to initializing server with "prime256v1" */
1931 const char *vhost_name;
1932 /**< VHOST: name of vhost, must match external DNS name used to
1933 * access the site, like "warmcat.com" as it's used to match
1934 * Host: header and / or SNI name for SSL. */
1935 const char * const *plugin_dirs;
1936 /**< CONTEXT: NULL, or NULL-terminated array of directories to
1937 * scan for lws protocol plugins at context creation time */
1938 const struct lws_protocol_vhost_options *pvo;
1939 /**< VHOST: pointer to optional linked list of per-vhost
1940 * options made accessible to protocols */
1941 int keepalive_timeout;
1942 /**< VHOST: (default = 0 = 60s) seconds to allow remote
1943 * client to hold on to an idle HTTP/1.1 connection */
1944 const char *log_filepath;
1945 /**< VHOST: filepath to append logs to... this is opened before
1946 * any dropping of initial privileges */
1947 const struct lws_http_mount *mounts;
1948 /**< VHOST: optional linked list of mounts for this vhost */
1949 const char *server_string;
1950 /**< CONTEXT: string used in HTTP headers to identify server
1951 * software, if NULL, "libwebsockets". */
1952 unsigned int pt_serv_buf_size;
1953 /**< CONTEXT: 0 = default of 4096. This buffer is used by
1954 * various service related features including file serving, it
1955 * defines the max chunk of file that can be sent at once.
1956 * At the risk of lws having to buffer failed large sends, it
1957 * can be increased to, eg, 128KiB to improve throughput. */
1958 unsigned int max_http_header_data2;
1959 /**< CONTEXT: if max_http_header_data is 0 and this
1960 * is nonzero, this will be used in place of the default. It's
1961 * like this for compatibility with the original short version,
1962 * this is unsigned int length. */
1963 long ssl_options_set;
1964 /**< VHOST: Any bits set here will be set as SSL options */
1965 long ssl_options_clear;
1966 /**< VHOST: Any bits set here will be cleared as SSL options */
1967 unsigned short ws_ping_pong_interval;
1968 /**< CONTEXT: 0 for none, else interval in seconds between sending
1969 * PINGs on idle websocket connections. When the PING is sent,
1970 * the PONG must come within the normal timeout_secs timeout period
1971 * or the connection will be dropped.
1972 * Any RX or TX traffic on the connection restarts the interval timer,
1973 * so a connection which always sends or receives something at intervals
1974 * less than the interval given here will never send PINGs / expect
1975 * PONGs. Conversely as soon as the ws connection is established, an
1976 * idle connection will do the PING / PONG roundtrip as soon as
1977 * ws_ping_pong_interval seconds has passed without traffic
1979 const struct lws_protocol_vhost_options *headers;
1980 /**< VHOST: pointer to optional linked list of per-vhost
1981 * canned headers that are added to server responses */
1983 const struct lws_protocol_vhost_options *reject_service_keywords;
1984 /**< CONTEXT: Optional list of keywords and rejection codes + text.
1986 * The keywords are checked for existing in the user agent string.
1988 * Eg, "badrobot" "404 Not Found"
1990 void *external_baggage_free_on_destroy;
1991 /**< CONTEXT: NULL, or pointer to something externally malloc'd, that
1992 * should be freed when the context is destroyed. This allows you to
1993 * automatically sync the freeing action to the context destruction
1994 * action, so there is no need for an external free() if the context
1995 * succeeded to create.
1998 #ifdef LWS_OPENSSL_SUPPORT
1999 /**< CONTEXT: NULL or struct lws_token_limits pointer which is initialized
2000 * with a token length limit for each possible WSI_TOKEN_ */
2001 const char *client_ssl_private_key_password;
2002 /**< VHOST: NULL or the passphrase needed for the private key */
2003 const char *client_ssl_cert_filepath;
2004 /**< VHOST: If libwebsockets was compiled to use ssl, and you want
2005 * to listen using SSL, set to the filepath to fetch the
2006 * server cert from, otherwise NULL for unencrypted */
2007 const char *client_ssl_private_key_filepath;
2008 /**< VHOST: filepath to private key if wanting SSL mode;
2009 * if this is set to NULL but sll_cert_filepath is set, the
2010 * OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY callback is called
2011 * to allow setting of the private key directly via openSSL
2013 const char *client_ssl_ca_filepath;
2014 /**< VHOST: CA certificate filepath or NULL */
2015 const char *client_ssl_cipher_list;
2016 /**< VHOST: List of valid ciphers to use (eg,
2017 * "RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL"
2018 * or you can leave it as NULL to get "DEFAULT" */
2021 const struct lws_plat_file_ops *fops;
2022 /**< CONTEXT: NULL, or pointer to an array of fops structs, terminated
2023 * by a sentinel with NULL .open.
2025 * If NULL, lws provides just the platform file operations struct for
2026 * backwards compatibility.
2028 int simultaneous_ssl_restriction;
2029 /**< CONTEXT: 0 (no limit) or limit of simultaneous SSL sessions possible.*/
2030 const char *socks_proxy_address;
2031 /**< VHOST: If non-NULL, attempts to proxy via the given address.
2032 * If proxy auth is required, use format "username:password\@server:port" */
2033 unsigned int socks_proxy_port;
2034 /**< VHOST: If socks_proxy_address was non-NULL, uses this port */
2035 #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
2036 cap_value_t caps[4];
2037 /**< CONTEXT: array holding Linux capabilities you want to
2038 * continue to be available to the server after it transitions
2039 * to a noprivileged user. Usually none are needed but for, eg,
2040 * .bind_iface, CAP_NET_RAW is required. This gives you a way
2041 * to still have the capability but drop root.
2044 /**< CONTEXT: count of Linux capabilities in .caps[]. 0 means
2045 * no capabilities will be inherited from root (the default) */
2048 /**< VHOST: nonzero to strictly bind sockets to the interface name in
2049 * .iface (eg, "eth2"), using SO_BIND_TO_DEVICE.
2051 * Requires SO_BINDTODEVICE support from your OS and CAP_NET_RAW
2054 * Notice that common things like access network interface IP from
2055 * your local machine use your lo / loopback interface and will be
2056 * disallowed by this.
2059 /* Add new things just above here ---^
2060 * This is part of the ABI, don't needlessly break compatibility
2062 * The below is to ensure later library versions with new
2063 * members added above will see 0 (default) even if the app
2064 * was not built against the newer headers.
2066 int ssl_info_event_mask;
2067 /**< VHOST: mask of ssl events to be reported on LWS_CALLBACK_SSL_INFO
2068 * callback for connections on this vhost. The mask values are of
2069 * the form SSL_CB_ALERT, defined in openssl/ssl.h. The default of
2070 * 0 means no info events will be reported.
2073 void *_unused[8]; /**< dummy */
2077 * lws_create_context() - Create the websocket handler
2078 * \param info: pointer to struct with parameters
2080 * This function creates the listening socket (if serving) and takes care
2081 * of all initialization in one step.
2083 * If option LWS_SERVER_OPTION_EXPLICIT_VHOSTS is given, no vhost is
2084 * created; you're expected to create your own vhosts afterwards using
2085 * lws_create_vhost(). Otherwise a vhost named "default" is also created
2086 * using the information in the vhost-related members, for compatibility.
2088 * After initialization, it returns a struct lws_context * that
2089 * represents this server. After calling, user code needs to take care
2090 * of calling lws_service() with the context pointer to get the
2091 * server's sockets serviced. This must be done in the same process
2092 * context as the initialization call.
2094 * The protocol callback functions are called for a handful of events
2095 * including http requests coming in, websocket connections becoming
2096 * established, and data arriving; it's also called periodically to allow
2097 * async transmission.
2099 * HTTP requests are sent always to the FIRST protocol in protocol, since
2100 * at that time websocket protocol has not been negotiated. Other
2101 * protocols after the first one never see any HTTP callback activity.
2103 * The server created is a simple http server by default; part of the
2104 * websocket standard is upgrading this http connection to a websocket one.
2106 * This allows the same server to provide files like scripts and favicon /
2107 * images or whatever over http and dynamic data over websockets all in
2108 * one place; they're all handled in the user callback.
2110 LWS_VISIBLE LWS_EXTERN struct lws_context *
2111 lws_create_context(struct lws_context_creation_info *info);
2114 * lws_context_destroy() - Destroy the websocket context
2115 * \param context: Websocket context
2117 * This function closes any active connections and then frees the
2118 * context. After calling this, any further use of the context is
2121 LWS_VISIBLE LWS_EXTERN void
2122 lws_context_destroy(struct lws_context *context);
2124 LWS_VISIBLE LWS_EXTERN void
2125 lws_context_destroy2(struct lws_context *context);
2127 typedef int (*lws_reload_func)(void);
2130 * lws_context_deprecate() - Deprecate the websocket context
2131 * \param context: Websocket context
2133 * This function is used on an existing context before superceding it
2134 * with a new context.
2136 * It closes any listen sockets in the context, so new connections are
2139 * And it marks the context to be deleted when the number of active
2140 * connections into it falls to zero.
2142 * Otherwise if you attach the deprecated context to the replacement
2143 * context when it has been created using lws_context_attach_deprecated()
2144 * both any deprecated and the new context will service their connections.
2146 * This is aimed at allowing seamless configuration reloads.
2148 * The callback cb will be called after the listen sockets are actually
2149 * closed and may be reopened. In the callback the new context should be
2150 * configured and created. (With libuv, socket close happens async after
2151 * more loop events).
2153 LWS_VISIBLE LWS_EXTERN void
2154 lws_context_deprecate(struct lws_context *context, lws_reload_func cb);
2156 LWS_VISIBLE LWS_EXTERN int
2157 lws_context_is_deprecated(struct lws_context *context);
2160 * lws_set_proxy() - Setups proxy to lws_context.
2161 * \param vhost: pointer to struct lws_vhost you want set proxy for
2162 * \param proxy: pointer to c string containing proxy in format address:port
2164 * Returns 0 if proxy string was parsed and proxy was setup.
2165 * Returns -1 if proxy is NULL or has incorrect format.
2167 * This is only required if your OS does not provide the http_proxy
2168 * environment variable (eg, OSX)
2170 * IMPORTANT! You should call this function right after creation of the
2171 * lws_context and before call to connect. If you call this
2172 * function after connect behavior is undefined.
2173 * This function will override proxy settings made on lws_context
2174 * creation with genenv() call.
2176 LWS_VISIBLE LWS_EXTERN int
2177 lws_set_proxy(struct lws_vhost *vhost, const char *proxy);
2180 * lws_set_socks() - Setup socks to lws_context.
2181 * \param vhost: pointer to struct lws_vhost you want set socks for
2182 * \param socks: pointer to c string containing socks in format address:port
2184 * Returns 0 if socks string was parsed and socks was setup.
2185 * Returns -1 if socks is NULL or has incorrect format.
2187 * This is only required if your OS does not provide the socks_proxy
2188 * environment variable (eg, OSX)
2190 * IMPORTANT! You should call this function right after creation of the
2191 * lws_context and before call to connect. If you call this
2192 * function after connect behavior is undefined.
2193 * This function will override proxy settings made on lws_context
2194 * creation with genenv() call.
2196 LWS_VISIBLE LWS_EXTERN int
2197 lws_set_socks(struct lws_vhost *vhost, const char *socks);
2202 * lws_create_vhost() - Create a vhost (virtual server context)
2203 * \param context: pointer to result of lws_create_context()
2204 * \param info: pointer to struct with parameters
2206 * This function creates a virtual server (vhost) using the vhost-related
2207 * members of the info struct. You can create many vhosts inside one context
2208 * if you created the context with the option LWS_SERVER_OPTION_EXPLICIT_VHOSTS
2210 LWS_VISIBLE LWS_EXTERN struct lws_vhost *
2211 lws_create_vhost(struct lws_context *context,
2212 struct lws_context_creation_info *info);
2215 * lws_destroy_vhost() - Destroy a vhost (virtual server context)
2216 * \param vhost: pointer to result of lws_create_vhost()
2218 * This function destroys a vhost. Normally, if you just want to exit,
2219 * then lws_destroy_context() will take care of everything. If you want
2220 * to destroy an individual vhost and all connections and allocations, you
2221 * can do it with this.
2223 LWS_VISIBLE LWS_EXTERN void
2224 lws_vhost_destroy(struct lws_vhost *vh);
2227 * lwsws_get_config_globals() - Parse a JSON server config file
2228 * \param info: pointer to struct with parameters
2229 * \param d: filepath of the config file
2230 * \param config_strings: storage for the config strings extracted from JSON,
2231 * the pointer is incremented as strings are stored
2232 * \param len: pointer to the remaining length left in config_strings
2233 * the value is decremented as strings are stored
2235 * This function prepares a n lws_context_creation_info struct with global
2236 * settings from a file d.
2238 * Requires CMake option LWS_WITH_LEJP_CONF to have been enabled
2240 LWS_VISIBLE LWS_EXTERN int
2241 lwsws_get_config_globals(struct lws_context_creation_info *info, const char *d,
2242 char **config_strings, int *len);
2245 * lwsws_get_config_vhosts() - Create vhosts from a JSON server config file
2246 * \param context: pointer to result of lws_create_context()
2247 * \param info: pointer to struct with parameters
2248 * \param d: filepath of the config file
2249 * \param config_strings: storage for the config strings extracted from JSON,
2250 * the pointer is incremented as strings are stored
2251 * \param len: pointer to the remaining length left in config_strings
2252 * the value is decremented as strings are stored
2254 * This function creates vhosts into a context according to the settings in
2255 *JSON files found in directory d.
2257 * Requires CMake option LWS_WITH_LEJP_CONF to have been enabled
2259 LWS_VISIBLE LWS_EXTERN int
2260 lwsws_get_config_vhosts(struct lws_context *context,
2261 struct lws_context_creation_info *info, const char *d,
2262 char **config_strings, int *len);
2264 /** lws_vhost_get() - \deprecated deprecated: use lws_get_vhost() */
2265 LWS_VISIBLE LWS_EXTERN struct lws_vhost *
2266 lws_vhost_get(struct lws *wsi) LWS_WARN_DEPRECATED;
2269 * lws_get_vhost() - return the vhost a wsi belongs to
2271 * \param wsi: which connection
2273 LWS_VISIBLE LWS_EXTERN struct lws_vhost *
2274 lws_get_vhost(struct lws *wsi);
2277 * lws_json_dump_vhost() - describe vhost state and stats in JSON
2279 * \param vh: the vhost
2280 * \param buf: buffer to fill with JSON
2281 * \param len: max length of buf
2283 LWS_VISIBLE LWS_EXTERN int
2284 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len);
2287 * lws_json_dump_context() - describe context state and stats in JSON
2289 * \param context: the context
2290 * \param buf: buffer to fill with JSON
2291 * \param len: max length of buf
2293 LWS_VISIBLE LWS_EXTERN int
2294 lws_json_dump_context(const struct lws_context *context, char *buf, int len,
2298 * lws_context_user() - get the user data associated with the context
2299 * \param context: Websocket context
2301 * This returns the optional user allocation that can be attached to
2302 * the context the sockets live in at context_create time. It's a way
2303 * to let all sockets serviced in the same context share data without
2304 * using globals statics in the user code.
2306 LWS_VISIBLE LWS_EXTERN void *
2307 lws_context_user(struct lws_context *context);
2309 /*! \defgroup vhost-mounts Vhost mounts and options
2310 * \ingroup context-and-vhost-creation
2312 * ##Vhost mounts and options
2315 /** struct lws_protocol_vhost_options - linked list of per-vhost protocol
2316 * name=value options
2318 * This provides a general way to attach a linked-list of name=value pairs,
2319 * which can also have an optional child link-list using the options member.
2321 struct lws_protocol_vhost_options {
2322 const struct lws_protocol_vhost_options *next; /**< linked list */
2323 const struct lws_protocol_vhost_options *options; /**< child linked-list of more options for this node */
2324 const char *name; /**< name of name=value pair */
2325 const char *value; /**< value of name=value pair */
2328 /** enum lws_mount_protocols
2329 * This specifies the mount protocol for a mountpoint, whether it is to be
2330 * served from a filesystem, or it is a cgi etc.
2332 enum lws_mount_protocols {
2333 LWSMPRO_HTTP = 0, /**< http reverse proxy */
2334 LWSMPRO_HTTPS = 1, /**< https reverse proxy */
2335 LWSMPRO_FILE = 2, /**< serve from filesystem directory */
2336 LWSMPRO_CGI = 3, /**< pass to CGI to handle */
2337 LWSMPRO_REDIR_HTTP = 4, /**< redirect to http:// url */
2338 LWSMPRO_REDIR_HTTPS = 5, /**< redirect to https:// url */
2339 LWSMPRO_CALLBACK = 6, /**< hand by named protocol's callback */
2342 /** struct lws_http_mount
2344 * arguments for mounting something in a vhost's url namespace
2346 struct lws_http_mount {
2347 const struct lws_http_mount *mount_next;
2348 /**< pointer to next struct lws_http_mount */
2349 const char *mountpoint;
2350 /**< mountpoint in http pathspace, eg, "/" */
2352 /**< path to be mounted, eg, "/var/www/warmcat.com" */
2354 /**< default target, eg, "index.html" */
2355 const char *protocol;
2356 /**<"protocol-name" to handle mount */
2358 const struct lws_protocol_vhost_options *cgienv;
2359 /**< optional linked-list of cgi options. These are created
2360 * as environment variables for the cgi process
2362 const struct lws_protocol_vhost_options *extra_mimetypes;
2363 /**< optional linked-list of mimetype mappings */
2364 const struct lws_protocol_vhost_options *interpret;
2365 /**< optional linked-list of files to be interpreted */
2368 /**< seconds cgi is allowed to live, if cgi://mount type */
2370 /**< max-age for reuse of client cache of files, seconds */
2371 unsigned int auth_mask;
2372 /**< bits set here must be set for authorized client session */
2374 unsigned int cache_reusable:1; /**< set if client cache may reuse this */
2375 unsigned int cache_revalidate:1; /**< set if client cache should revalidate on use */
2376 unsigned int cache_intermediaries:1; /**< set if intermediaries are allowed to cache */
2378 unsigned char origin_protocol; /**< one of enum lws_mount_protocols */
2379 unsigned char mountpoint_len; /**< length of mountpoint string */
2381 const char *basic_auth_login_file;
2382 /**<NULL, or filepath to use to check basic auth logins against */
2384 /* Add new things just above here ---^
2385 * This is part of the ABI, don't needlessly break compatibility
2387 * The below is to ensure later library versions with new
2388 * members added above will see 0 (default) even if the app
2389 * was not built against the newer headers.
2392 void *_unused[2]; /**< dummy */
2397 /*! \defgroup client
2400 * ##Client releated functions
2404 /** enum lws_client_connect_ssl_connection_flags - flags that may be used
2405 * with struct lws_client_connect_info ssl_connection member to control if
2406 * and how SSL checks apply to the client connection being created
2409 enum lws_client_connect_ssl_connection_flags {
2410 LCCSCF_USE_SSL = (1 << 0),
2411 LCCSCF_ALLOW_SELFSIGNED = (1 << 1),
2412 LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK = (1 << 2),
2413 LCCSCF_ALLOW_EXPIRED = (1 << 3)
2416 /** struct lws_client_connect_info - parameters to connect with when using
2417 * lws_client_connect_via_info() */
2419 struct lws_client_connect_info {
2420 struct lws_context *context;
2421 /**< lws context to create connection in */
2422 const char *address;
2423 /**< remote address to connect to */
2425 /**< remote port to connect to */
2427 /**< nonzero for ssl */
2431 /**< content of host header */
2433 /**< content of origin header */
2434 const char *protocol;
2435 /**< list of ws protocols we could accept */
2436 int ietf_version_or_minus_one;
2437 /**< deprecated: currently leave at 0 or -1 */
2439 /**< if non-NULL, use this as wsi user_data instead of malloc it */
2440 const void *client_exts;
2441 /**< UNUSED... provide in info.extensions at context creation time */
2443 /**< if non-NULL, do this http method instead of ws[s] upgrade.
2444 * use "GET" to be a simple http client connection */
2445 struct lws *parent_wsi;
2446 /**< if another wsi is responsible for this connection, give it here.
2447 * this is used to make sure if the parent closes so do any
2448 * child connections first. */
2449 const char *uri_replace_from;
2450 /**< if non-NULL, when this string is found in URIs in
2451 * text/html content-encoding, it's replaced with uri_replace_to */
2452 const char *uri_replace_to;
2453 /**< see uri_replace_from */
2454 struct lws_vhost *vhost;
2455 /**< vhost to bind to (used to determine related SSL_CTX) */
2457 /**< if not NULL, store the new wsi here early in the connection
2458 * process. Although we return the new wsi, the call to create the
2459 * client connection does progress the connection somewhat and may
2460 * meet an error that will result in the connection being scrubbed and
2461 * NULL returned. While the wsi exists though, he may process a
2462 * callback like CLIENT_CONNECTION_ERROR with his wsi: this gives the
2463 * user callback a way to identify which wsi it is that faced the error
2464 * even before the new wsi is returned and even if ultimately no wsi
2468 /**< NULL to allow routing on any interface, or interface name or IP
2469 * to bind the socket to */
2471 /* Add new things just above here ---^
2472 * This is part of the ABI, don't needlessly break compatibility
2474 * The below is to ensure later library versions with new
2475 * members added above will see 0 (default) even if the app
2476 * was not built against the newer headers.
2479 void *_unused[4]; /**< dummy */
2483 * lws_client_connect_via_info() - Connect to another websocket server
2484 * \param ccinfo: pointer to lws_client_connect_info struct
2486 * This function creates a connection to a remote server using the
2487 * information provided in ccinfo.
2489 LWS_VISIBLE LWS_EXTERN struct lws *
2490 lws_client_connect_via_info(struct lws_client_connect_info * ccinfo);
2493 * lws_client_connect() - Connect to another websocket server
2494 * \deprecated DEPRECATED use lws_client_connect_via_info
2495 * \param clients: Websocket context
2496 * \param address: Remote server address, eg, "myserver.com"
2497 * \param port: Port to connect to on the remote server, eg, 80
2498 * \param ssl_connection: 0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
2500 * \param path: Websocket path on server
2501 * \param host: Hostname on server
2502 * \param origin: Socket origin name
2503 * \param protocol: Comma-separated list of protocols being asked for from
2504 * the server, or just one. The server will pick the one it
2505 * likes best. If you don't want to specify a protocol, which is
2506 * legal, use NULL here.
2507 * \param ietf_version_or_minus_one: -1 to ask to connect using the default, latest
2508 * protocol supported, or the specific protocol ordinal
2510 * This function creates a connection to a remote server
2512 /* deprecated, use lws_client_connect_via_info() */
2513 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
2514 lws_client_connect(struct lws_context *clients, const char *address,
2515 int port, int ssl_connection, const char *path,
2516 const char *host, const char *origin, const char *protocol,
2517 int ietf_version_or_minus_one) LWS_WARN_DEPRECATED;
2518 /* deprecated, use lws_client_connect_via_info() */
2520 * lws_client_connect_extended() - Connect to another websocket server
2521 * \deprecated DEPRECATED use lws_client_connect_via_info
2522 * \param clients: Websocket context
2523 * \param address: Remote server address, eg, "myserver.com"
2524 * \param port: Port to connect to on the remote server, eg, 80
2525 * \param ssl_connection: 0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
2527 * \param path: Websocket path on server
2528 * \param host: Hostname on server
2529 * \param origin: Socket origin name
2530 * \param protocol: Comma-separated list of protocols being asked for from
2531 * the server, or just one. The server will pick the one it
2533 * \param ietf_version_or_minus_one: -1 to ask to connect using the default, latest
2534 * protocol supported, or the specific protocol ordinal
2535 * \param userdata: Pre-allocated user data
2537 * This function creates a connection to a remote server
2539 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
2540 lws_client_connect_extended(struct lws_context *clients, const char *address,
2541 int port, int ssl_connection, const char *path,
2542 const char *host, const char *origin,
2543 const char *protocol, int ietf_version_or_minus_one,
2544 void *userdata) LWS_WARN_DEPRECATED;
2547 * lws_init_vhost_client_ssl() - also enable client SSL on an existing vhost
2549 * \param info: client ssl related info
2550 * \param vhost: which vhost to initialize client ssl operations on
2552 * You only need to call this if you plan on using SSL client connections on
2553 * the vhost. For non-SSL client connections, it's not necessary to call this.
2555 * The following members of info are used during the call
2557 * - options must have LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT set,
2558 * otherwise the call does nothing
2559 * - provided_client_ssl_ctx must be NULL to get a generated client
2560 * ssl context, otherwise you can pass a prepared one in by setting it
2561 * - ssl_cipher_list may be NULL or set to the client valid cipher list
2562 * - ssl_ca_filepath may be NULL or client cert filepath
2563 * - ssl_cert_filepath may be NULL or client cert filepath
2564 * - ssl_private_key_filepath may be NULL or client cert private key
2566 * You must create your vhost explicitly if you want to use this, so you have
2567 * a pointer to the vhost. Create the context first with the option flag
2568 * LWS_SERVER_OPTION_EXPLICIT_VHOSTS and then call lws_create_vhost() with
2569 * the same info struct.
2571 LWS_VISIBLE LWS_EXTERN int
2572 lws_init_vhost_client_ssl(const struct lws_context_creation_info *info,
2573 struct lws_vhost *vhost);
2575 * lws_http_client_read() - consume waiting received http client data
2577 * \param wsi: client connection
2578 * \param buf: pointer to buffer pointer - fill with pointer to your buffer
2579 * \param len: pointer to chunk length - fill with max length of buffer
2581 * This is called when the user code is notified client http data has arrived.
2582 * The user code may choose to delay calling it to consume the data, for example
2583 * waiting until an onward connection is writeable.
2585 * For non-chunked connections, up to len bytes of buf are filled with the
2586 * received content. len is set to the actual amount filled before return.
2588 * For chunked connections, the linear buffer content contains the chunking
2589 * headers and it cannot be passed in one lump. Instead, this function will
2590 * call back LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ with in pointing to the
2591 * chunk start and len set to the chunk length. There will be as many calls
2592 * as there are chunks or partial chunks in the buffer.
2594 LWS_VISIBLE LWS_EXTERN int
2595 lws_http_client_read(struct lws *wsi, char **buf, int *len);
2598 * lws_http_client_http_response() - get last HTTP response code
2600 * \param wsi: client connection
2602 * Returns the last server response code, eg, 200 for client http connections.
2604 LWS_VISIBLE LWS_EXTERN unsigned int
2605 lws_http_client_http_response(struct lws *wsi);
2607 LWS_VISIBLE LWS_EXTERN void
2608 lws_client_http_body_pending(struct lws *wsi, int something_left_to_send);
2611 * lws_client_http_body_pending() - control if client connection neeeds to send body
2613 * \param wsi: client connection
2614 * \param something_left_to_send: nonzero if need to send more body, 0 (default)
2615 * if nothing more to send
2617 * If you will send payload data with your HTTP client connection, eg, for POST,
2618 * when you set the related http headers in
2619 * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER callback you should also call
2620 * this API with something_left_to_send nonzero, and call
2621 * lws_callback_on_writable(wsi);
2623 * After sending the headers, lws will call your callback with
2624 * LWS_CALLBACK_CLIENT_HTTP_WRITEABLE reason when writable. You can send the
2625 * next part of the http body payload, calling lws_callback_on_writable(wsi);
2626 * if there is more to come, or lws_client_http_body_pending(wsi, 0); to
2627 * let lws know the last part is sent and the connection can move on.
2632 /** \defgroup service Built-in service loop entry
2634 * ##Built-in service loop entry
2636 * If you're not using libev / libuv, these apis are needed to enter the poll()
2637 * wait in lws and service any connections with pending events.
2642 * lws_service() - Service any pending websocket activity
2643 * \param context: Websocket context
2644 * \param timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
2645 * service otherwise block and service immediately, returning
2646 * after the timeout if nothing needed service.
2648 * This function deals with any pending websocket traffic, for three
2649 * kinds of event. It handles these events on both server and client
2650 * types of connection the same.
2652 * 1) Accept new connections to our context's server
2654 * 2) Call the receive callback for incoming frame data received by
2655 * server or client connections.
2657 * You need to call this service function periodically to all the above
2658 * functions to happen; if your application is single-threaded you can
2659 * just call it in your main event loop.
2661 * Alternatively you can fork a new process that asynchronously handles
2662 * calling this service in a loop. In that case you are happy if this
2663 * call blocks your thread until it needs to take care of something and
2664 * would call it with a large nonzero timeout. Your loop then takes no
2665 * CPU while there is nothing happening.
2667 * If you are calling it in a single-threaded app, you don't want it to
2668 * wait around blocking other things in your loop from happening, so you
2669 * would call it with a timeout_ms of 0, so it returns immediately if
2670 * nothing is pending, or as soon as it services whatever was pending.
2672 LWS_VISIBLE LWS_EXTERN int
2673 lws_service(struct lws_context *context, int timeout_ms);
2676 * lws_service() - Service any pending websocket activity
2678 * \param context: Websocket context
2679 * \param timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
2680 * service otherwise block and service immediately, returning
2681 * after the timeout if nothing needed service.
2683 * Same as lws_service(), but for a specific thread service index. Only needed
2684 * if you are spawning multiple service threads.
2686 LWS_VISIBLE LWS_EXTERN int
2687 lws_service_tsi(struct lws_context *context, int timeout_ms, int tsi);
2690 * lws_cancel_service_pt() - Cancel servicing of pending socket activity
2692 * \param wsi: Cancel service on the thread this wsi is serviced by
2694 * This function lets a call to lws_service() waiting for a timeout
2695 * immediately return.
2697 * It works by creating a phony event and then swallowing it silently.
2699 * The reason it may be needed is when waiting in poll(), changes to
2700 * the event masks are ignored by the OS until poll() is reentered. This
2701 * lets you halt the poll() wait and make the reentry happen immediately
2702 * instead of having the wait out the rest of the poll timeout.
2704 LWS_VISIBLE LWS_EXTERN void
2705 lws_cancel_service_pt(struct lws *wsi);
2708 * lws_cancel_service() - Cancel wait for new pending socket activity
2709 * \param context: Websocket context
2711 * This function let a call to lws_service() waiting for a timeout
2712 * immediately return.
2714 * What it basically does is provide a fake event that will be swallowed,
2715 * so the wait in poll() is ended. That's useful because poll() doesn't
2716 * attend to changes in POLLIN/OUT/ERR until it re-enters the wait.
2718 LWS_VISIBLE LWS_EXTERN void
2719 lws_cancel_service(struct lws_context *context);
2722 * lws_service_fd() - Service polled socket with something waiting
2723 * \param context: Websocket context
2724 * \param pollfd: The pollfd entry describing the socket fd and which events
2725 * happened, or NULL to tell lws to do only timeout servicing.
2727 * This function takes a pollfd that has POLLIN or POLLOUT activity and
2728 * services it according to the state of the associated
2731 * The one call deals with all "service" that might happen on a socket
2732 * including listen accepts, http files as well as websocket protocol.
2734 * If a pollfd says it has something, you can just pass it to
2735 * lws_service_fd() whether it is a socket handled by lws or not.
2736 * If it sees it is a lws socket, the traffic will be handled and
2737 * pollfd->revents will be zeroed now.
2739 * If the socket is foreign to lws, it leaves revents alone. So you can
2740 * see if you should service yourself by checking the pollfd revents
2741 * after letting lws try to service it.
2743 * You should also call this with pollfd = NULL to just allow the
2744 * once-per-second global timeout checks; if less than a second since the last
2745 * check it returns immediately then.
2747 LWS_VISIBLE LWS_EXTERN int
2748 lws_service_fd(struct lws_context *context, struct lws_pollfd *pollfd);
2751 * lws_service_fd_tsi() - Service polled socket in specific service thread
2752 * \param context: Websocket context
2753 * \param pollfd: The pollfd entry describing the socket fd and which events
2755 * \param tsi: thread service index
2757 * Same as lws_service_fd() but used with multiple service threads
2759 LWS_VISIBLE LWS_EXTERN int
2760 lws_service_fd_tsi(struct lws_context *context, struct lws_pollfd *pollfd,
2764 * lws_service_adjust_timeout() - Check for any connection needing forced service
2765 * \param context: Websocket context
2766 * \param timeout_ms: The original poll timeout value. You can just set this
2767 * to 1 if you don't really have a poll timeout.
2768 * \param tsi: thread service index
2770 * Under some conditions connections may need service even though there is no
2771 * pending network action on them, this is "forced service". For default
2772 * poll() and libuv / libev, the library takes care of calling this and
2773 * dealing with it for you. But for external poll() integration, you need
2774 * access to the apis.
2776 * If anybody needs "forced service", returned timeout is zero. In that case,
2777 * you can call lws_service_tsi() with a timeout of -1 to only service
2778 * guys who need forced service.
2780 LWS_VISIBLE LWS_EXTERN int
2781 lws_service_adjust_timeout(struct lws_context *context, int timeout_ms, int tsi);
2783 /* Backwards compatibility */
2784 #define lws_plat_service_tsi lws_service_tsi
2788 /*! \defgroup http HTTP
2790 Modules related to handling HTTP
2794 /*! \defgroup httpft HTTP File transfer
2797 APIs for sending local files in response to HTTP requests
2802 * lws_get_mimetype() - Determine mimetype to use from filename
2804 * \param file: filename
2805 * \param m: NULL, or mount context
2807 * This uses a canned list of known filetypes first, if no match and m is
2808 * non-NULL, then tries a list of per-mount file suffix to mimtype mappings.
2810 * Returns either NULL or a pointer to the mimetype matching the file.
2812 LWS_VISIBLE LWS_EXTERN const char *
2813 lws_get_mimetype(const char *file, const struct lws_http_mount *m);
2816 * lws_serve_http_file() - Send a file back to the client using http
2817 * \param wsi: Websocket instance (available from user callback)
2818 * \param file: The file to issue over http
2819 * \param content_type: The http content type, eg, text/html
2820 * \param other_headers: NULL or pointer to header string
2821 * \param other_headers_len: length of the other headers if non-NULL
2823 * This function is intended to be called from the callback in response
2824 * to http requests from the client. It allows the callback to issue
2825 * local files down the http link in a single step.
2827 * Returning <0 indicates error and the wsi should be closed. Returning
2828 * >0 indicates the file was completely sent and
2829 * lws_http_transaction_completed() called on the wsi (and close if != 0)
2830 * ==0 indicates the file transfer is started and needs more service later,
2831 * the wsi should be left alone.
2833 LWS_VISIBLE LWS_EXTERN int
2834 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
2835 const char *other_headers, int other_headers_len);
2837 LWS_VISIBLE LWS_EXTERN int
2838 lws_serve_http_file_fragment(struct lws *wsi);
2841 /*! \defgroup html-chunked-substitution HTML Chunked Substitution
2844 * ##HTML chunked Substitution
2846 * APIs for receiving chunks of text, replacing a set of variable names via
2847 * a callback, and then prepending and appending HTML chunked encoding
2853 HTTP_STATUS_OK = 200,
2854 HTTP_STATUS_NO_CONTENT = 204,
2855 HTTP_STATUS_PARTIAL_CONTENT = 206,
2857 HTTP_STATUS_MOVED_PERMANENTLY = 301,
2858 HTTP_STATUS_FOUND = 302,
2859 HTTP_STATUS_SEE_OTHER = 303,
2860 HTTP_STATUS_NOT_MODIFIED = 304,
2862 HTTP_STATUS_BAD_REQUEST = 400,
2863 HTTP_STATUS_UNAUTHORIZED,
2864 HTTP_STATUS_PAYMENT_REQUIRED,
2865 HTTP_STATUS_FORBIDDEN,
2866 HTTP_STATUS_NOT_FOUND,
2867 HTTP_STATUS_METHOD_NOT_ALLOWED,
2868 HTTP_STATUS_NOT_ACCEPTABLE,
2869 HTTP_STATUS_PROXY_AUTH_REQUIRED,
2870 HTTP_STATUS_REQUEST_TIMEOUT,
2871 HTTP_STATUS_CONFLICT,
2873 HTTP_STATUS_LENGTH_REQUIRED,
2874 HTTP_STATUS_PRECONDITION_FAILED,
2875 HTTP_STATUS_REQ_ENTITY_TOO_LARGE,
2876 HTTP_STATUS_REQ_URI_TOO_LONG,
2877 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE,
2878 HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE,
2879 HTTP_STATUS_EXPECTATION_FAILED,
2881 HTTP_STATUS_INTERNAL_SERVER_ERROR = 500,
2882 HTTP_STATUS_NOT_IMPLEMENTED,
2883 HTTP_STATUS_BAD_GATEWAY,
2884 HTTP_STATUS_SERVICE_UNAVAILABLE,
2885 HTTP_STATUS_GATEWAY_TIMEOUT,
2886 HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED,
2889 struct lws_process_html_args {
2890 char *p; /**< pointer to the buffer containing the data */
2891 int len; /**< length of the original data at p */
2892 int max_len; /**< maximum length we can grow the data to */
2893 int final; /**< set if this is the last chunk of the file */
2896 typedef const char *(*lws_process_html_state_cb)(void *data, int index);
2898 struct lws_process_html_state {
2899 char *start; /**< pointer to start of match */
2900 char swallow[16]; /**< matched character buffer */
2901 int pos; /**< position in match */
2902 void *data; /**< opaque pointer */
2903 const char * const *vars; /**< list of variable names */
2904 int count_vars; /**< count of variable names */
2906 lws_process_html_state_cb replace; /**< called on match to perform substitution */
2909 /*! lws_chunked_html_process() - generic chunked substitution
2910 * \param args: buffer to process using chunked encoding
2911 * \param s: current processing state
2913 LWS_VISIBLE LWS_EXTERN int
2914 lws_chunked_html_process(struct lws_process_html_args *args,
2915 struct lws_process_html_state *s);
2918 /** \defgroup HTTP-headers-read HTTP headers: read
2921 * ##HTTP header releated functions
2923 * In lws the client http headers are temporarily stored in a pool, only for the
2924 * duration of the http part of the handshake. It's because in most cases,
2925 * the header content is ignored for the whole rest of the connection lifetime
2926 * and would then just be taking up space needlessly.
2928 * During LWS_CALLBACK_HTTP when the URI path is delivered is the last time
2929 * the http headers are still allocated, you can use these apis then to
2930 * look at and copy out interesting header content (cookies, etc)
2932 * Notice that the header total length reported does not include a terminating
2933 * '\0', however you must allocate for it when using the _copy apis. So the
2934 * length reported for a header containing "123" is 3, but you must provide
2935 * a buffer of length 4 so that "123\0" may be copied into it, or the copy
2936 * will fail with a nonzero return code.
2938 * In the special case of URL arguments, like ?x=1&y=2, the arguments are
2939 * stored in a token named for the method, eg, WSI_TOKEN_GET_URI if it
2940 * was a GET or WSI_TOKEN_POST_URI if POST. You can check the total
2941 * length to confirm the method.
2943 * For URL arguments, each argument is stored urldecoded in a "fragment", so
2944 * you can use the fragment-aware api lws_hdr_copy_fragment() to access each
2945 * argument in turn: the fragments contain urldecoded strings like x=1 or y=2.
2947 * As a convenience, lws has an api that will find the fragment with a
2948 * given name= part, lws_get_urlarg_by_name().
2952 /** struct lws_tokens
2953 * you need these to look at headers that have been parsed if using the
2954 * LWS_CALLBACK_FILTER_CONNECTION callback. If a header from the enum
2955 * list below is absent, .token = NULL and token_len = 0. Otherwise .token
2956 * points to .token_len chars containing that header content.
2959 char *token; /**< pointer to start of the token */
2960 int token_len; /**< length of the token's value */
2963 /* enum lws_token_indexes
2964 * these have to be kept in sync with lextable.h / minilex.c
2966 * NOTE: These public enums are part of the abi. If you want to add one,
2967 * add it at where specified so existing users are unaffected.
2969 enum lws_token_indexes {
2970 WSI_TOKEN_GET_URI = 0,
2971 WSI_TOKEN_POST_URI = 1,
2972 WSI_TOKEN_OPTIONS_URI = 2,
2974 WSI_TOKEN_CONNECTION = 4,
2975 WSI_TOKEN_UPGRADE = 5,
2976 WSI_TOKEN_ORIGIN = 6,
2977 WSI_TOKEN_DRAFT = 7,
2978 WSI_TOKEN_CHALLENGE = 8,
2979 WSI_TOKEN_EXTENSIONS = 9,
2980 WSI_TOKEN_KEY1 = 10,
2981 WSI_TOKEN_KEY2 = 11,
2982 WSI_TOKEN_PROTOCOL = 12,
2983 WSI_TOKEN_ACCEPT = 13,
2984 WSI_TOKEN_NONCE = 14,
2985 WSI_TOKEN_HTTP = 15,
2986 WSI_TOKEN_HTTP2_SETTINGS = 16,
2987 WSI_TOKEN_HTTP_ACCEPT = 17,
2988 WSI_TOKEN_HTTP_AC_REQUEST_HEADERS = 18,
2989 WSI_TOKEN_HTTP_IF_MODIFIED_SINCE = 19,
2990 WSI_TOKEN_HTTP_IF_NONE_MATCH = 20,
2991 WSI_TOKEN_HTTP_ACCEPT_ENCODING = 21,
2992 WSI_TOKEN_HTTP_ACCEPT_LANGUAGE = 22,
2993 WSI_TOKEN_HTTP_PRAGMA = 23,
2994 WSI_TOKEN_HTTP_CACHE_CONTROL = 24,
2995 WSI_TOKEN_HTTP_AUTHORIZATION = 25,
2996 WSI_TOKEN_HTTP_COOKIE = 26,
2997 WSI_TOKEN_HTTP_CONTENT_LENGTH = 27,
2998 WSI_TOKEN_HTTP_CONTENT_TYPE = 28,
2999 WSI_TOKEN_HTTP_DATE = 29,
3000 WSI_TOKEN_HTTP_RANGE = 30,
3001 WSI_TOKEN_HTTP_REFERER = 31,
3003 WSI_TOKEN_VERSION = 33,
3004 WSI_TOKEN_SWORIGIN = 34,
3006 WSI_TOKEN_HTTP_COLON_AUTHORITY = 35,
3007 WSI_TOKEN_HTTP_COLON_METHOD = 36,
3008 WSI_TOKEN_HTTP_COLON_PATH = 37,
3009 WSI_TOKEN_HTTP_COLON_SCHEME = 38,
3010 WSI_TOKEN_HTTP_COLON_STATUS = 39,
3012 WSI_TOKEN_HTTP_ACCEPT_CHARSET = 40,
3013 WSI_TOKEN_HTTP_ACCEPT_RANGES = 41,
3014 WSI_TOKEN_HTTP_ACCESS_CONTROL_ALLOW_ORIGIN = 42,
3015 WSI_TOKEN_HTTP_AGE = 43,
3016 WSI_TOKEN_HTTP_ALLOW = 44,
3017 WSI_TOKEN_HTTP_CONTENT_DISPOSITION = 45,
3018 WSI_TOKEN_HTTP_CONTENT_ENCODING = 46,
3019 WSI_TOKEN_HTTP_CONTENT_LANGUAGE = 47,
3020 WSI_TOKEN_HTTP_CONTENT_LOCATION = 48,
3021 WSI_TOKEN_HTTP_CONTENT_RANGE = 49,
3022 WSI_TOKEN_HTTP_ETAG = 50,
3023 WSI_TOKEN_HTTP_EXPECT = 51,
3024 WSI_TOKEN_HTTP_EXPIRES = 52,
3025 WSI_TOKEN_HTTP_FROM = 53,
3026 WSI_TOKEN_HTTP_IF_MATCH = 54,
3027 WSI_TOKEN_HTTP_IF_RANGE = 55,
3028 WSI_TOKEN_HTTP_IF_UNMODIFIED_SINCE = 56,
3029 WSI_TOKEN_HTTP_LAST_MODIFIED = 57,
3030 WSI_TOKEN_HTTP_LINK = 58,
3031 WSI_TOKEN_HTTP_LOCATION = 59,
3032 WSI_TOKEN_HTTP_MAX_FORWARDS = 60,
3033 WSI_TOKEN_HTTP_PROXY_AUTHENTICATE = 61,
3034 WSI_TOKEN_HTTP_PROXY_AUTHORIZATION = 62,
3035 WSI_TOKEN_HTTP_REFRESH = 63,
3036 WSI_TOKEN_HTTP_RETRY_AFTER = 64,
3037 WSI_TOKEN_HTTP_SERVER = 65,
3038 WSI_TOKEN_HTTP_SET_COOKIE = 66,
3039 WSI_TOKEN_HTTP_STRICT_TRANSPORT_SECURITY = 67,
3040 WSI_TOKEN_HTTP_TRANSFER_ENCODING = 68,
3041 WSI_TOKEN_HTTP_USER_AGENT = 69,
3042 WSI_TOKEN_HTTP_VARY = 70,
3043 WSI_TOKEN_HTTP_VIA = 71,
3044 WSI_TOKEN_HTTP_WWW_AUTHENTICATE = 72,
3046 WSI_TOKEN_PATCH_URI = 73,
3047 WSI_TOKEN_PUT_URI = 74,
3048 WSI_TOKEN_DELETE_URI = 75,
3050 WSI_TOKEN_HTTP_URI_ARGS = 76,
3051 WSI_TOKEN_PROXY = 77,
3052 WSI_TOKEN_HTTP_X_REAL_IP = 78,
3053 WSI_TOKEN_HTTP1_0 = 79,
3054 WSI_TOKEN_X_FORWARDED_FOR = 80,
3055 WSI_TOKEN_CONNECT = 81,
3056 /****** add new things just above ---^ ******/
3058 /* use token storage to stash these internally, not for
3061 _WSI_TOKEN_CLIENT_SENT_PROTOCOLS,
3062 _WSI_TOKEN_CLIENT_PEER_ADDRESS,
3063 _WSI_TOKEN_CLIENT_URI,
3064 _WSI_TOKEN_CLIENT_HOST,
3065 _WSI_TOKEN_CLIENT_ORIGIN,
3066 _WSI_TOKEN_CLIENT_METHOD,
3067 _WSI_TOKEN_CLIENT_IFACE,
3069 /* always last real token index*/
3072 /* parser state additions, no storage associated */
3073 WSI_TOKEN_NAME_PART,
3075 WSI_TOKEN_SKIPPING_SAW_CR,
3076 WSI_PARSING_COMPLETE,
3077 WSI_INIT_TOKEN_MUXURL,
3080 struct lws_token_limits {
3081 unsigned short token_limit[WSI_TOKEN_COUNT]; /**< max chars for this token */
3085 * lws_token_to_string() - returns a textual representation of a hdr token index
3087 * \param: token index
3089 LWS_VISIBLE LWS_EXTERN const unsigned char *
3090 lws_token_to_string(enum lws_token_indexes token);
3094 * lws_hdr_total_length: report length of all fragments of a header totalled up
3095 * The returned length does not include the space for a
3098 * \param wsi: websocket connection
3099 * \param h: which header index we are interested in
3101 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3102 lws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h);
3105 * lws_hdr_fragment_length: report length of a single fragment of a header
3106 * The returned length does not include the space for a
3109 * \param wsi: websocket connection
3110 * \param h: which header index we are interested in
3111 * \param frag_idx: which fragment of h we want to get the length of
3113 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3114 lws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx);
3117 * lws_hdr_copy() - copy a single fragment of the given header to a buffer
3118 * The buffer length len must include space for an additional
3119 * terminating '\0', or it will fail returning -1.
3121 * \param wsi: websocket connection
3122 * \param dest: destination buffer
3123 * \param len: length of destination buffer
3124 * \param h: which header index we are interested in
3126 * copies the whole, aggregated header, even if it was delivered in
3127 * several actual headers piece by piece
3129 LWS_VISIBLE LWS_EXTERN int
3130 lws_hdr_copy(struct lws *wsi, char *dest, int len, enum lws_token_indexes h);
3133 * lws_hdr_copy_fragment() - copy a single fragment of the given header to a buffer
3134 * The buffer length len must include space for an additional
3135 * terminating '\0', or it will fail returning -1.
3136 * If the requested fragment index is not present, it fails
3139 * \param wsi: websocket connection
3140 * \param dest: destination buffer
3141 * \param len: length of destination buffer
3142 * \param h: which header index we are interested in
3143 * \param frag_idx: which fragment of h we want to copy
3145 * Normally this is only useful
3146 * to parse URI arguments like ?x=1&y=2, token index WSI_TOKEN_HTTP_URI_ARGS
3147 * fragment 0 will contain "x=1" and fragment 1 "y=2"
3149 LWS_VISIBLE LWS_EXTERN int
3150 lws_hdr_copy_fragment(struct lws *wsi, char *dest, int len,
3151 enum lws_token_indexes h, int frag_idx);
3154 * lws_get_urlarg_by_name() - return pointer to arg value if present
3155 * \param wsi: the connection to check
3156 * \param name: the arg name, like "token="
3157 * \param buf: the buffer to receive the urlarg (including the name= part)
3158 * \param len: the length of the buffer to receive the urlarg
3160 * Returns NULL if not found or a pointer inside buf to just after the
3163 LWS_VISIBLE LWS_EXTERN const char *
3164 lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len);
3167 /*! \defgroup HTTP-headers-create HTTP headers: create
3169 * ## HTTP headers: Create
3171 * These apis allow you to create HTTP response headers in a way compatible with
3172 * both HTTP/1.x and HTTP/2.
3174 * They each append to a buffer taking care about the buffer end, which is
3175 * passed in as a pointer. When data is written to the buffer, the current
3176 * position p is updated accordingly.
3178 * All of these apis are LWS_WARN_UNUSED_RESULT as they can run out of space
3179 * and fail with nonzero return.
3183 #define LWSAHH_CODE_MASK ((1 << 16) - 1)
3184 #define LWSAHH_FLAG_NO_SERVER_NAME (1 << 30)
3187 * lws_add_http_header_status() - add the HTTP response status code
3189 * \param wsi: the connection to check
3190 * \param code: an HTTP code like 200, 404 etc (see enum http_status)
3191 * \param p: pointer to current position in buffer pointer
3192 * \param end: pointer to end of buffer
3194 * Adds the initial response code, so should be called first.
3196 * Code may additionally take OR'd flags:
3198 * LWSAHH_FLAG_NO_SERVER_NAME: don't apply server name header this time
3200 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3201 lws_add_http_header_status(struct lws *wsi,
3202 unsigned int code, unsigned char **p,
3203 unsigned char *end);
3205 * lws_add_http_header_by_name() - append named header and value
3207 * \param wsi: the connection to check
3208 * \param name: the hdr name, like "my-header"
3209 * \param value: the value after the = for this header
3210 * \param length: the length of the value
3211 * \param p: pointer to current position in buffer pointer
3212 * \param end: pointer to end of buffer
3214 * Appends name: value to the headers
3216 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3217 lws_add_http_header_by_name(struct lws *wsi, const unsigned char *name,
3218 const unsigned char *value, int length,
3219 unsigned char **p, unsigned char *end);
3221 * lws_add_http_header_by_token() - append given header and value
3223 * \param wsi: the connection to check
3224 * \param token: the token index for the hdr
3225 * \param value: the value after the = for this header
3226 * \param length: the length of the value
3227 * \param p: pointer to current position in buffer pointer
3228 * \param end: pointer to end of buffer
3230 * Appends name=value to the headers, but is able to take advantage of better
3231 * HTTP/2 coding mechanisms where possible.
3233 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3234 lws_add_http_header_by_token(struct lws *wsi, enum lws_token_indexes token,
3235 const unsigned char *value, int length,
3236 unsigned char **p, unsigned char *end);
3238 * lws_add_http_header_content_length() - append content-length helper
3240 * \param wsi: the connection to check
3241 * \param content_length: the content length to use
3242 * \param p: pointer to current position in buffer pointer
3243 * \param end: pointer to end of buffer
3245 * Appends content-length: content_length to the headers
3247 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3248 lws_add_http_header_content_length(struct lws *wsi,
3249 lws_filepos_t content_length,
3250 unsigned char **p, unsigned char *end);
3252 * lws_finalize_http_header() - terminate header block
3254 * \param wsi: the connection to check
3255 * \param p: pointer to current position in buffer pointer
3256 * \param end: pointer to end of buffer
3258 * Indicates no more headers will be added
3260 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3261 lws_finalize_http_header(struct lws *wsi, unsigned char **p,
3262 unsigned char *end);
3265 /** \defgroup form-parsing Form Parsing
3267 * ##POSTed form parsing functions
3269 * These lws_spa (stateful post arguments) apis let you parse and urldecode
3270 * POSTed form arguments, both using simple urlencoded and multipart transfer
3273 * It's capable of handling file uploads as well a named input parsing,
3274 * and the apis are the same for both form upload styles.
3276 * You feed it a list of parameter names and it creates pointers to the
3277 * urldecoded arguments: file upload parameters pass the file data in chunks to
3278 * a user-supplied callback as they come.
3280 * Since it's stateful, it handles the incoming data needing more than one
3281 * POST_BODY callback and has no limit on uploaded file size.
3285 /** enum lws_spa_fileupload_states */
3286 enum lws_spa_fileupload_states {
3288 /**< a chunk of file content has arrived */
3289 LWS_UFS_FINAL_CONTENT,
3290 /**< the last chunk (possibly zero length) of file content has arrived */
3292 /**< a new file is starting to arrive */
3296 * lws_spa_fileupload_cb() - callback to receive file upload data
3298 * \param data: opt_data pointer set in lws_spa_create
3299 * \param name: name of the form field being uploaded
3300 * \param filename: original filename from client
3301 * \param buf: start of data to receive
3302 * \param len: length of data to receive
3303 * \param state: information about how this call relates to file
3305 * Notice name and filename shouldn't be trusted, as they are passed from
3306 * HTTP provided by the client.
3308 typedef int (*lws_spa_fileupload_cb)(void *data, const char *name,
3309 const char *filename, char *buf, int len,
3310 enum lws_spa_fileupload_states state);
3312 /** struct lws_spa - opaque urldecode parser capable of handling multipart
3313 * and file uploads */
3317 * lws_spa_create() - create urldecode parser
3319 * \param wsi: lws connection (used to find Content Type)
3320 * \param param_names: array of form parameter names, like "username"
3321 * \param count_params: count of param_names
3322 * \param max_storage: total amount of form parameter values we can store
3323 * \param opt_cb: NULL, or callback to receive file upload data.
3324 * \param opt_data: NULL, or user pointer provided to opt_cb.
3326 * Creates a urldecode parser and initializes it.
3328 * opt_cb can be NULL if you just want normal name=value parsing, however
3329 * if one or more entries in your form are bulk data (file transfer), you
3330 * can provide this callback and filter on the name callback parameter to
3331 * treat that urldecoded data separately. The callback should return -1
3332 * in case of fatal error, and 0 if OK.
3334 LWS_VISIBLE LWS_EXTERN struct lws_spa *
3335 lws_spa_create(struct lws *wsi, const char * const *param_names,
3336 int count_params, int max_storage, lws_spa_fileupload_cb opt_cb,
3340 * lws_spa_process() - parses a chunk of input data
3342 * \param spa: the parser object previously created
3343 * \param in: incoming, urlencoded data
3344 * \param len: count of bytes valid at \param in
3346 LWS_VISIBLE LWS_EXTERN int
3347 lws_spa_process(struct lws_spa *spa, const char *in, int len);
3350 * lws_spa_finalize() - indicate incoming data completed
3352 * \param spa: the parser object previously created
3354 LWS_VISIBLE LWS_EXTERN int
3355 lws_spa_finalize(struct lws_spa *spa);
3358 * lws_spa_get_length() - return length of parameter value
3360 * \param spa: the parser object previously created
3361 * \param n: parameter ordinal to return length of value for
3363 LWS_VISIBLE LWS_EXTERN int
3364 lws_spa_get_length(struct lws_spa *spa, int n);
3367 * lws_spa_get_string() - return pointer to parameter value
3368 * \param spa: the parser object previously created
3369 * \param n: parameter ordinal to return pointer to value for
3371 LWS_VISIBLE LWS_EXTERN const char *
3372 lws_spa_get_string(struct lws_spa *spa, int n);
3375 * lws_spa_destroy() - destroy parser object
3377 * \param spa: the parser object previously created
3379 LWS_VISIBLE LWS_EXTERN int
3380 lws_spa_destroy(struct lws_spa *spa);
3383 /*! \defgroup urlendec Urlencode and Urldecode
3386 * ##HTML chunked Substitution
3388 * APIs for receiving chunks of text, replacing a set of variable names via
3389 * a callback, and then prepending and appending HTML chunked encoding
3395 * lws_urlencode() - like strncpy but with urlencoding
3397 * \param escaped: output buffer
3398 * \param string: input buffer ('/0' terminated)
3399 * \param len: output buffer max length
3401 * Because urlencoding expands the output string, it's not
3402 * possible to do it in-place, ie, with escaped == string
3404 LWS_VISIBLE LWS_EXTERN const char *
3405 lws_urlencode(char *escaped, const char *string, int len);
3410 * This simple urldecode only operates until the first '\0' and requires the
3411 * data to exist all at once
3414 * lws_urldecode() - like strncpy but with urldecoding
3416 * \param string: output buffer
3417 * \param escaped: input buffer ('\0' terminated)
3418 * \param len: output buffer max length
3420 * This is only useful for '\0' terminated strings
3422 * Since urldecoding only shrinks the output string, it is possible to
3423 * do it in-place, ie, string == escaped
3425 LWS_VISIBLE LWS_EXTERN int
3426 lws_urldecode(char *string, const char *escaped, int len);
3429 * lws_return_http_status() - Return simple http status
3430 * \param wsi: Websocket instance (available from user callback)
3431 * \param code: Status index, eg, 404
3432 * \param html_body: User-readable HTML description < 1KB, or NULL
3434 * Helper to report HTTP errors back to the client cleanly and
3437 LWS_VISIBLE LWS_EXTERN int
3438 lws_return_http_status(struct lws *wsi, unsigned int code,
3439 const char *html_body);
3442 * lws_http_redirect() - write http redirect into buffer
3444 * \param wsi: websocket connection
3445 * \param code: HTTP response code (eg, 301)
3446 * \param loc: where to redirect to
3447 * \param len: length of loc
3448 * \param p: pointer current position in buffer (updated as we write)
3449 * \param end: pointer to end of buffer
3451 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3452 lws_http_redirect(struct lws *wsi, int code, const unsigned char *loc, int len,
3453 unsigned char **p, unsigned char *end);
3456 * lws_http_transaction_completed() - wait for new http transaction or close
3457 * \param wsi: websocket connection
3459 * Returns 1 if the HTTP connection must close now
3460 * Returns 0 and resets connection to wait for new HTTP header /
3461 * transaction if possible
3463 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3464 lws_http_transaction_completed(struct lws *wsi);
3467 /*! \defgroup pur Sanitize / purify SQL and JSON helpers
3469 * ##Sanitize / purify SQL and JSON helpers
3471 * APIs for escaping untrusted JSON and SQL safely before use
3476 * lws_sql_purify() - like strncpy but with escaping for sql quotes
3478 * \param escaped: output buffer
3479 * \param string: input buffer ('/0' terminated)
3480 * \param len: output buffer max length
3482 * Because escaping expands the output string, it's not
3483 * possible to do it in-place, ie, with escaped == string
3485 LWS_VISIBLE LWS_EXTERN const char *
3486 lws_sql_purify(char *escaped, const char *string, int len);
3489 * lws_json_purify() - like strncpy but with escaping for json chars
3491 * \param escaped: output buffer
3492 * \param string: input buffer ('/0' terminated)
3493 * \param len: output buffer max length
3495 * Because escaping expands the output string, it's not
3496 * possible to do it in-place, ie, with escaped == string
3498 LWS_VISIBLE LWS_EXTERN const char *
3499 lws_json_purify(char *escaped, const char *string, int len);
3502 /*! \defgroup ev libev helpers
3506 * APIs specific to libev event loop itegration
3510 #ifdef LWS_USE_LIBEV
3511 typedef void (lws_ev_signal_cb_t)(EV_P_ struct ev_signal *w, int revents);
3513 LWS_VISIBLE LWS_EXTERN int
3514 lws_ev_sigint_cfg(struct lws_context *context, int use_ev_sigint,
3515 lws_ev_signal_cb_t *cb);
3517 LWS_VISIBLE LWS_EXTERN int
3518 lws_ev_initloop(struct lws_context *context, struct ev_loop *loop, int tsi);
3520 LWS_VISIBLE LWS_EXTERN void
3521 lws_ev_sigint_cb(struct ev_loop *loop, struct ev_signal *watcher, int revents);
3522 #endif /* LWS_USE_LIBEV */
3526 /*! \defgroup uv libuv helpers
3530 * APIs specific to libuv event loop itegration
3533 #ifdef LWS_USE_LIBUV
3534 LWS_VISIBLE LWS_EXTERN int
3535 lws_uv_sigint_cfg(struct lws_context *context, int use_uv_sigint,
3538 LWS_VISIBLE LWS_EXTERN void
3539 lws_libuv_run(const struct lws_context *context, int tsi);
3541 LWS_VISIBLE LWS_EXTERN void
3542 lws_libuv_stop(struct lws_context *context);
3544 LWS_VISIBLE LWS_EXTERN void
3545 lws_libuv_stop_without_kill(const struct lws_context *context, int tsi);
3547 LWS_VISIBLE LWS_EXTERN int
3548 lws_uv_initloop(struct lws_context *context, uv_loop_t *loop, int tsi);
3550 LWS_VISIBLE LWS_EXTERN uv_loop_t *
3551 lws_uv_getloop(struct lws_context *context, int tsi);
3553 LWS_VISIBLE LWS_EXTERN void
3554 lws_uv_sigint_cb(uv_signal_t *watcher, int signum);
3556 LWS_VISIBLE LWS_EXTERN void
3557 lws_close_all_handles_in_loop(uv_loop_t *loop);
3558 #endif /* LWS_USE_LIBUV */
3561 /*! \defgroup event libevent helpers
3563 * ##libevent helpers
3565 * APIs specific to libevent event loop itegration
3569 #ifdef LWS_USE_LIBEVENT
3570 typedef void (lws_event_signal_cb_t) (evutil_socket_t sock_fd, short revents,
3573 LWS_VISIBLE LWS_EXTERN int
3574 lws_event_sigint_cfg(struct lws_context *context, int use_event_sigint,
3575 lws_event_signal_cb_t cb);
3577 LWS_VISIBLE LWS_EXTERN int
3578 lws_event_initloop(struct lws_context *context, struct event_base *loop,
3581 LWS_VISIBLE LWS_EXTERN void
3582 lws_event_sigint_cb(evutil_socket_t sock_fd, short revents,
3584 #endif /* LWS_USE_LIBEVENT */
3588 /*! \defgroup timeout Connection timeouts
3590 APIs related to setting connection timeouts
3595 * NOTE: These public enums are part of the abi. If you want to add one,
3596 * add it at where specified so existing users are unaffected.
3598 enum pending_timeout {
3599 NO_PENDING_TIMEOUT = 0,
3600 PENDING_TIMEOUT_AWAITING_PROXY_RESPONSE = 1,
3601 PENDING_TIMEOUT_AWAITING_CONNECT_RESPONSE = 2,
3602 PENDING_TIMEOUT_ESTABLISH_WITH_SERVER = 3,
3603 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE = 4,
3604 PENDING_TIMEOUT_AWAITING_PING = 5,
3605 PENDING_TIMEOUT_CLOSE_ACK = 6,
3606 PENDING_TIMEOUT_AWAITING_EXTENSION_CONNECT_RESPONSE = 7,
3607 PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE = 8,
3608 PENDING_TIMEOUT_SSL_ACCEPT = 9,
3609 PENDING_TIMEOUT_HTTP_CONTENT = 10,
3610 PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND = 11,
3611 PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE = 12,
3612 PENDING_TIMEOUT_SHUTDOWN_FLUSH = 13,
3613 PENDING_TIMEOUT_CGI = 14,
3614 PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE = 15,
3615 PENDING_TIMEOUT_WS_PONG_CHECK_SEND_PING = 16,
3616 PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG = 17,
3617 PENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD = 18,
3618 PENDING_TIMEOUT_AWAITING_SOCKS_GREETING_REPLY = 19,
3619 PENDING_TIMEOUT_AWAITING_SOCKS_CONNECT_REPLY = 20,
3620 PENDING_TIMEOUT_AWAITING_SOCKS_AUTH_REPLY = 21,
3621 PENDING_TIMEOUT_KILLED_BY_SSL_INFO = 22,
3622 PENDING_TIMEOUT_KILLED_BY_PARENT = 23,
3623 PENDING_TIMEOUT_CLOSE_SEND = 24,
3625 /****** add new things just above ---^ ******/
3629 * lws_set_timeout() - marks the wsi as subject to a timeout
3631 * You will not need this unless you are doing something special
3633 * \param wsi: Websocket connection instance
3634 * \param reason: timeout reason
3635 * \param secs: how many seconds
3637 LWS_VISIBLE LWS_EXTERN void
3638 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs);
3641 /*! \defgroup sending-data Sending data
3643 APIs related to writing data on a connection
3646 #if !defined(LWS_SIZEOFPTR)
3647 #define LWS_SIZEOFPTR (sizeof (void *))
3649 #if !defined(u_int64_t)
3650 #define u_int64_t unsigned long long
3653 #if defined(__x86_64__)
3654 #define _LWS_PAD_SIZE 16 /* Intel recommended for best performance */
3656 #define _LWS_PAD_SIZE LWS_SIZEOFPTR /* Size of a pointer on the target arch */
3658 #define _LWS_PAD(n) (((n) % _LWS_PAD_SIZE) ? \
3659 ((n) + (_LWS_PAD_SIZE - ((n) % _LWS_PAD_SIZE))) : (n))
3660 #define LWS_PRE _LWS_PAD(4 + 10)
3661 /* used prior to 1.7 and retained for backward compatibility */
3662 #define LWS_SEND_BUFFER_PRE_PADDING LWS_PRE
3663 #define LWS_SEND_BUFFER_POST_PADDING 0
3666 * NOTE: These public enums are part of the abi. If you want to add one,
3667 * add it at where specified so existing users are unaffected.
3669 enum lws_write_protocol {
3671 /**< Send a ws TEXT message,the pointer must have LWS_PRE valid
3672 * memory behind it. The receiver expects only valid utf-8 in the
3674 LWS_WRITE_BINARY = 1,
3675 /**< Send a ws BINARY message, the pointer must have LWS_PRE valid
3676 * memory behind it. Any sequence of bytes is valid */
3677 LWS_WRITE_CONTINUATION = 2,
3678 /**< Continue a previous ws message, the pointer must have LWS_PRE valid
3679 * memory behind it */
3681 /**< Send HTTP content */
3683 /* LWS_WRITE_CLOSE is handled by lws_close_reason() */
3687 /* Same as write_http but we know this write ends the transaction */
3688 LWS_WRITE_HTTP_FINAL = 7,
3692 LWS_WRITE_HTTP_HEADERS = 8,
3693 /**< Send http headers (http2 encodes this payload and LWS_WRITE_HTTP
3694 * payload differently, http 1.x links also handle this correctly. so
3695 * to be compatible with both in the future,header response part should
3696 * be sent using this regardless of http version expected)
3699 /****** add new things just above ---^ ******/
3703 LWS_WRITE_NO_FIN = 0x40,
3704 /**< This part of the message is not the end of the message */
3706 LWS_WRITE_CLIENT_IGNORE_XOR_MASK = 0x80
3707 /**< client packet payload goes out on wire unmunged
3708 * only useful for security tests since normal servers cannot
3709 * decode the content if used */
3714 * lws_write() - Apply protocol then write data to client
3715 * \param wsi: Websocket instance (available from user callback)
3716 * \param buf: The data to send. For data being sent on a websocket
3717 * connection (ie, not default http), this buffer MUST have
3718 * LWS_PRE bytes valid BEFORE the pointer.
3719 * This is so the protocol header data can be added in-situ.
3720 * \param len: Count of the data bytes in the payload starting from buf
3721 * \param protocol: Use LWS_WRITE_HTTP to reply to an http connection, and one
3722 * of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
3723 * data on a websockets connection. Remember to allow the extra
3724 * bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
3727 * This function provides the way to issue data back to the client
3728 * for both http and websocket protocols.
3732 * When sending with websocket protocol
3736 * LWS_WRITE_CONTINUATION,
3740 * the send buffer has to have LWS_PRE bytes valid BEFORE
3741 * the buffer pointer you pass to lws_write().
3743 * This allows us to add protocol info before and after the data, and send as
3744 * one packet on the network without payload copying, for maximum efficiency.
3746 * So for example you need this kind of code to use lws_write with a
3749 * char buf[LWS_PRE + 128];
3751 * // fill your part of the buffer... for example here it's all zeros
3752 * memset(&buf[LWS_PRE], 0, 128);
3754 * lws_write(wsi, &buf[LWS_PRE], 128, LWS_WRITE_TEXT);
3756 * When sending HTTP, with
3759 * LWS_WRITE_HTTP_HEADERS
3760 * LWS_WRITE_HTTP_FINAL
3762 * there is no protocol data prepended, and don't need to take care about the
3763 * LWS_PRE bytes valid before the buffer pointer.
3765 * LWS_PRE is at least the frame nonce + 2 header + 8 length
3766 * LWS_SEND_BUFFER_POST_PADDING is deprecated, it's now 0 and can be left off.
3767 * The example apps no longer use it.
3769 * Pad LWS_PRE to the CPU word size, so that word references
3770 * to the address immediately after the padding won't cause an unaligned access
3771 * error. Sometimes for performance reasons the recommended padding is even
3772 * larger than sizeof(void *).
3774 * In the case of sending using websocket protocol, be sure to allocate
3775 * valid storage before and after buf as explained above. This scheme
3776 * allows maximum efficiency of sending data and protocol in a single
3777 * packet while not burdening the user code with any protocol knowledge.
3779 * Return may be -1 for a fatal error needing connection close, or the
3780 * number of bytes sent.
3785 * The OS may not accept everything you asked to write on the connection.
3787 * Posix defines POLLOUT indication from poll() to show that the connection
3788 * will accept more write data, but it doesn't specifiy how much. It may just
3789 * accept one byte of whatever you wanted to send.
3791 * LWS will buffer the remainder automatically, and send it out autonomously.
3793 * During that time, WRITABLE callbacks will be suppressed.
3795 * This is to handle corner cases where unexpectedly the OS refuses what we
3796 * usually expect it to accept. You should try to send in chunks that are
3797 * almost always accepted in order to avoid the inefficiency of the buffering.
3799 LWS_VISIBLE LWS_EXTERN int
3800 lws_write(struct lws *wsi, unsigned char *buf, size_t len,
3801 enum lws_write_protocol protocol);
3803 /* helper for case where buffer may be const */
3804 #define lws_write_http(wsi, buf, len) \
3805 lws_write(wsi, (unsigned char *)(buf), len, LWS_WRITE_HTTP)
3808 /** \defgroup callback-when-writeable Callback when writeable
3810 * ##Callback When Writeable
3812 * lws can only write data on a connection when it is able to accept more
3813 * data without blocking.
3815 * So a basic requirement is we should only use the lws_write() apis when the
3816 * connection we want to write on says that he can accept more data.
3818 * When lws cannot complete your send at the time, it will buffer the data
3819 * and send it in the background, suppressing any further WRITEABLE callbacks
3820 * on that connection until it completes. So it is important to write new
3821 * things in a new writeable callback.
3823 * These apis reflect the various ways we can indicate we would like to be
3824 * called back when one or more connections is writeable.
3829 * lws_callback_on_writable() - Request a callback when this socket
3830 * becomes able to be written to without
3833 * \param wsi: Websocket connection instance to get callback for
3835 * - Which: only this wsi
3836 * - When: when the individual connection becomes writeable
3837 * - What: LWS_CALLBACK_*_WRITEABLE
3839 LWS_VISIBLE LWS_EXTERN int
3840 lws_callback_on_writable(struct lws *wsi);
3843 * lws_callback_on_writable_all_protocol() - Request a callback for all
3844 * connections on same vhost using the given protocol when it
3845 * becomes possible to write to each socket without
3848 * \param context: lws_context
3849 * \param protocol: Protocol whose connections will get callbacks
3851 * - Which: connections using this protocol on ANY VHOST
3852 * - When: when the individual connection becomes writeable
3853 * - What: LWS_CALLBACK_*_WRITEABLE
3855 LWS_VISIBLE LWS_EXTERN int
3856 lws_callback_on_writable_all_protocol(const struct lws_context *context,
3857 const struct lws_protocols *protocol);
3860 * lws_callback_on_writable_all_protocol_vhost() - Request a callback for
3861 * all connections using the given protocol when it
3862 * becomes possible to write to each socket without
3865 * \param vhost: Only consider connections on this lws_vhost
3866 * \param protocol: Protocol whose connections will get callbacks
3868 * - Which: connections using this protocol on GIVEN VHOST ONLY
3869 * - When: when the individual connection becomes writeable
3870 * - What: LWS_CALLBACK_*_WRITEABLE
3872 LWS_VISIBLE LWS_EXTERN int
3873 lws_callback_on_writable_all_protocol_vhost(const struct lws_vhost *vhost,
3874 const struct lws_protocols *protocol);
3877 * lws_callback_all_protocol() - Callback all connections using
3878 * the given protocol with the given reason
3880 * \param context: lws_context
3881 * \param protocol: Protocol whose connections will get callbacks
3882 * \param reason: Callback reason index
3884 * - Which: connections using this protocol on ALL VHOSTS
3885 * - When: before returning
3888 * This isn't normally what you want... normally any update of connection-
3889 * specific information can wait until a network-related callback like rx,
3890 * writable, or close.
3892 LWS_VISIBLE LWS_EXTERN int
3893 lws_callback_all_protocol(struct lws_context *context,
3894 const struct lws_protocols *protocol, int reason);
3897 * lws_callback_all_protocol_vhost() - Callback all connections using
3898 * the given protocol with the given reason
3900 * \param vh: Vhost whose connections will get callbacks
3901 * \param protocol: Which protocol to match
3902 * \param reason: Callback reason index
3904 * - Which: connections using this protocol on GIVEN VHOST ONLY
3908 LWS_VISIBLE LWS_EXTERN int
3909 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
3910 const struct lws_protocols *protocol, int reason);
3913 * lws_callback_vhost_protocols() - Callback all protocols enabled on a vhost
3914 * with the given reason
3916 * \param wsi: wsi whose vhost will get callbacks
3917 * \param reason: Callback reason index
3918 * \param in: in argument to callback
3919 * \param len: len argument to callback
3921 * - Which: connections using this protocol on same VHOST as wsi ONLY
3925 LWS_VISIBLE LWS_EXTERN int
3926 lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len);
3928 LWS_VISIBLE LWS_EXTERN int
3929 lws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason,
3930 void *user, void *in, size_t len);
3933 * lws_get_socket_fd() - returns the socket file descriptor
3935 * You will not need this unless you are doing something special
3937 * \param wsi: Websocket connection instance
3939 LWS_VISIBLE LWS_EXTERN int
3940 lws_get_socket_fd(struct lws *wsi);
3943 * lws_get_peer_write_allowance() - get the amount of data writeable to peer
3946 * \param wsi: Websocket connection instance
3948 * if the protocol does not have any guidance, returns -1. Currently only
3949 * http2 connections get send window information from this API. But your code
3950 * should use it so it can work properly with any protocol.
3952 * If nonzero return is the amount of payload data the peer or intermediary has
3953 * reported it has buffer space for. That has NO relationship with the amount
3954 * of buffer space your OS can accept on this connection for a write action.
3956 * This number represents the maximum you could send to the peer or intermediary
3957 * on this connection right now without the protocol complaining.
3959 * lws manages accounting for send window updates and payload writes
3960 * automatically, so this number reflects the situation at the peer or
3961 * intermediary dynamically.
3963 LWS_VISIBLE LWS_EXTERN size_t
3964 lws_get_peer_write_allowance(struct lws *wsi);
3968 * lws_rx_flow_control() - Enable and disable socket servicing for
3971 * If the output side of a server process becomes choked, this allows flow
3972 * control for the input side.
3974 * \param wsi: Websocket connection instance to get callback for
3975 * \param enable: 0 = disable read servicing for this connection, 1 = enable
3977 LWS_VISIBLE LWS_EXTERN int
3978 lws_rx_flow_control(struct lws *wsi, int enable);
3981 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
3983 * When the user server code realizes it can accept more input, it can
3984 * call this to have the RX flow restriction removed from all connections using
3985 * the given protocol.
3986 * \param context: lws_context
3987 * \param protocol: all connections using this protocol will be allowed to receive
3989 LWS_VISIBLE LWS_EXTERN void
3990 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
3991 const struct lws_protocols *protocol);
3994 * lws_remaining_packet_payload() - Bytes to come before "overall"
3995 * rx packet is complete
3996 * \param wsi: Websocket instance (available from user callback)
3998 * This function is intended to be called from the callback if the
3999 * user code is interested in "complete packets" from the client.
4000 * libwebsockets just passes through payload as it comes and issues a buffer
4001 * additionally when it hits a built-in limit. The LWS_CALLBACK_RECEIVE
4002 * callback handler can use this API to find out if the buffer it has just
4003 * been given is the last piece of a "complete packet" from the client --
4004 * when that is the case lws_remaining_packet_payload() will return
4007 * Many protocols won't care becuse their packets are always small.
4009 LWS_VISIBLE LWS_EXTERN size_t
4010 lws_remaining_packet_payload(struct lws *wsi);
4013 /** \defgroup sock-adopt Socket adoption helpers
4014 * ##Socket adoption helpers
4016 * When integrating with an external app with its own event loop, these can
4017 * be used to accept connections from someone else's listening socket.
4019 * When using lws own event loop, these are not needed.
4024 * lws_adopt_socket() - adopt foreign socket as if listen socket accepted it
4025 * for the default vhost of context.
4026 * \param context: lws context
4027 * \param accept_fd: fd of already-accepted socket to adopt
4029 * Either returns new wsi bound to accept_fd, or closes accept_fd and
4030 * returns NULL, having cleaned up any new wsi pieces.
4032 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
4033 * to ws or just serve http.
4035 LWS_VISIBLE LWS_EXTERN struct lws *
4036 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd);
4038 * lws_adopt_socket_vhost() - adopt foreign socket as if listen socket accepted it
4040 * \param vhost: lws vhost
4041 * \param accept_fd: fd of already-accepted socket to adopt
4043 * Either returns new wsi bound to accept_fd, or closes accept_fd and
4044 * returns NULL, having cleaned up any new wsi pieces.
4046 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
4047 * to ws or just serve http.
4049 LWS_VISIBLE LWS_EXTERN struct lws *
4050 lws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd);
4053 LWS_ADOPT_RAW_FILE_DESC = 0, /* convenience constant */
4054 LWS_ADOPT_HTTP = 1, /* flag: absent implies RAW */
4055 LWS_ADOPT_SOCKET = 2, /* flag: absent implies file descr */
4056 LWS_ADOPT_ALLOW_SSL = 4 /* flag: if set requires LWS_ADOPT_SOCKET */
4057 } lws_adoption_type;
4060 lws_sockfd_type sockfd;
4061 lws_filefd_type filefd;
4062 } lws_sock_file_fd_type;
4065 * lws_adopt_descriptor_vhost() - adopt foreign socket or file descriptor
4066 * if socket descriptor, should already have been accepted from listen socket
4068 * \param vhost: lws vhost
4069 * \param type: OR-ed combinations of lws_adoption_type flags
4070 * \param fd: union with either .sockfd or .filefd set
4071 * \param vh_prot_name: NULL or vh protocol name to bind raw connection to
4072 * \param parent: NULL or struct lws to attach new_wsi to as a child
4074 * Either returns new wsi bound to accept_fd, or closes accept_fd and
4075 * returns NULL, having cleaned up any new wsi pieces.
4077 * If LWS_ADOPT_SOCKET is set, LWS adopts the socket in http serving mode, it's
4078 * ready to accept an upgrade to ws or just serve http.
4080 * parent may be NULL, if given it should be an existing wsi that will become the
4081 * parent of the new wsi created by this call.
4083 LWS_VISIBLE LWS_EXTERN struct lws *
4084 lws_adopt_descriptor_vhost(struct lws_vhost *vh, lws_adoption_type type,
4085 lws_sock_file_fd_type fd, const char *vh_prot_name,
4086 struct lws *parent);
4089 * lws_adopt_socket_readbuf() - adopt foreign socket and first rx as if listen socket accepted it
4090 * for the default vhost of context.
4091 * \param context: lws context
4092 * \param accept_fd: fd of already-accepted socket to adopt
4093 * \param readbuf: NULL or pointer to data that must be drained before reading from
4095 * \param len: The length of the data held at \param readbuf
4097 * Either returns new wsi bound to accept_fd, or closes accept_fd and
4098 * returns NULL, having cleaned up any new wsi pieces.
4100 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
4101 * to ws or just serve http.
4103 * If your external code did not already read from the socket, you can use
4104 * lws_adopt_socket() instead.
4106 * This api is guaranteed to use the data at \param readbuf first, before reading from
4109 * readbuf is limited to the size of the ah rx buf, currently 2048 bytes.
4111 LWS_VISIBLE LWS_EXTERN struct lws *
4112 lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
4113 const char *readbuf, size_t len);
4115 * lws_adopt_socket_vhost_readbuf() - adopt foreign socket and first rx as if listen socket
4116 * accepted it for vhost.
4117 * \param vhost: lws vhost
4118 * \param accept_fd: fd of already-accepted socket to adopt
4119 * \param readbuf: NULL or pointer to data that must be drained before reading from
4121 * \param len: The length of the data held at \param readbuf
4123 * Either returns new wsi bound to accept_fd, or closes accept_fd and
4124 * returns NULL, having cleaned up any new wsi pieces.
4126 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
4127 * to ws or just serve http.
4129 * If your external code did not already read from the socket, you can use
4130 * lws_adopt_socket() instead.
4132 * This api is guaranteed to use the data at \param readbuf first, before reading from
4135 * readbuf is limited to the size of the ah rx buf, currently 2048 bytes.
4137 LWS_VISIBLE LWS_EXTERN struct lws *
4138 lws_adopt_socket_vhost_readbuf(struct lws_vhost *vhost, lws_sockfd_type accept_fd,
4139 const char *readbuf, size_t len);
4142 /** \defgroup net Network related helper APIs
4143 * ##Network related helper APIs
4145 * These wrap miscellaneous useful network-related functions
4150 * lws_canonical_hostname() - returns this host's hostname
4152 * This is typically used by client code to fill in the host parameter
4153 * when making a client connection. You can only call it after the context
4156 * \param context: Websocket context
4158 LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
4159 lws_canonical_hostname(struct lws_context *context);
4162 * lws_get_peer_addresses() - Get client address information
4163 * \param wsi: Local struct lws associated with
4164 * \param fd: Connection socket descriptor
4165 * \param name: Buffer to take client address name
4166 * \param name_len: Length of client address name buffer
4167 * \param rip: Buffer to take client address IP dotted quad
4168 * \param rip_len: Length of client address IP buffer
4170 * This function fills in name and rip with the name and IP of
4171 * the client connected with socket descriptor fd. Names may be
4172 * truncated if there is not enough room. If either cannot be
4173 * determined, they will be returned as valid zero-length strings.
4175 LWS_VISIBLE LWS_EXTERN void
4176 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
4177 int name_len, char *rip, int rip_len);
4180 * lws_get_peer_simple() - Get client address information without RDNS
4182 * \param wsi: Local struct lws associated with
4183 * \param name: Buffer to take client address name
4184 * \param namelen: Length of client address name buffer
4186 * This provides a 123.123.123.123 type IP address in name from the
4187 * peer that has connected to wsi
4189 LWS_VISIBLE LWS_EXTERN const char *
4190 lws_get_peer_simple(struct lws *wsi, char *name, int namelen);
4191 #if !defined(LWS_WITH_ESP8266) && !defined(LWS_WITH_ESP32)
4193 * lws_interface_to_sa() - Convert interface name or IP to sockaddr struct
4195 * \param ipv6: Allow IPV6 addresses
4196 * \param ifname: Interface name or IP
4197 * \param addr: struct sockaddr_in * to be written
4198 * \param addrlen: Length of addr
4200 * This converts a textual network interface name to a sockaddr usable by
4201 * other network functions
4203 LWS_VISIBLE LWS_EXTERN int
4204 lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr,
4209 /** \defgroup misc Miscellaneous APIs
4210 * ##Miscellaneous APIs
4212 * Various APIs outside of other categories
4217 * lws_start_foreach_ll(): linkedlist iterator helper start
4219 * \param type: type of iteration, eg, struct xyz *
4220 * \param it: iterator var name to create
4221 * \param start: start of list
4223 * This helper creates an iterator and starts a while (it) {
4224 * loop. The iterator runs through the linked list starting at start and
4225 * ends when it gets a NULL.
4226 * The while loop should be terminated using lws_start_foreach_ll().
4228 #define lws_start_foreach_ll(type, it, start)\
4234 * lws_end_foreach_ll(): linkedlist iterator helper end
4236 * \param it: same iterator var name given when starting
4237 * \param nxt: member name in the iterator pointing to next list element
4239 * This helper is the partner for lws_start_foreach_ll() that ends the
4243 #define lws_end_foreach_ll(it, nxt) \
4249 * lws_start_foreach_llp(): linkedlist pointer iterator helper start
4251 * \param type: type of iteration, eg, struct xyz **
4252 * \param it: iterator var name to create
4253 * \param start: start of list
4255 * This helper creates an iterator and starts a while (it) {
4256 * loop. The iterator runs through the linked list starting at the
4257 * address of start and ends when it gets a NULL.
4258 * The while loop should be terminated using lws_start_foreach_llp().
4260 * This helper variant iterates using a pointer to the previous linked-list
4261 * element. That allows you to easily delete list members by rewriting the
4262 * previous pointer to the element's next pointer.
4264 #define lws_start_foreach_llp(type, it, start)\
4266 type it = &(start); \
4270 * lws_end_foreach_llp(): linkedlist pointer iterator helper end
4272 * \param it: same iterator var name given when starting
4273 * \param nxt: member name in the iterator pointing to next list element
4275 * This helper is the partner for lws_start_foreach_llp() that ends the
4279 #define lws_end_foreach_llp(it, nxt) \
4280 it = &(*(it))->nxt; \
4285 * lws_snprintf(): snprintf that truncates the returned length too
4287 * \param str: destination buffer
4288 * \param size: bytes left in destination buffer
4289 * \param format: format string
4290 * \param ...: args for format
4292 * This lets you correctly truncate buffers by concatenating lengths, if you
4293 * reach the limit the reported length doesn't exceed the limit.
4295 LWS_VISIBLE LWS_EXTERN int
4296 lws_snprintf(char *str, size_t size, const char *format, ...) LWS_FORMAT(3);
4299 * lws_get_random(): fill a buffer with platform random data
4301 * \param context: the lws context
4302 * \param buf: buffer to fill
4303 * \param len: how much to fill
4305 * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
4306 * it's interested to see if the frame it's dealing with was sent in binary
4309 LWS_VISIBLE LWS_EXTERN int
4310 lws_get_random(struct lws_context *context, void *buf, int len);
4312 * lws_daemonize(): make current process run in the background
4314 * \param _lock_path: the filepath to write the lock file
4316 * Spawn lws as a background process, taking care of various things
4318 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4319 lws_daemonize(const char *_lock_path);
4321 * lws_get_library_version(): return string describing the version of lws
4323 * On unix, also includes the git describe
4325 LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
4326 lws_get_library_version(void);
4329 * lws_wsi_user() - get the user data associated with the connection
4330 * \param wsi: lws connection
4332 * Not normally needed since it's passed into the callback
4334 LWS_VISIBLE LWS_EXTERN void *
4335 lws_wsi_user(struct lws *wsi);
4338 * lws_wsi_set_user() - set the user data associated with the client connection
4339 * \param wsi: lws connection
4340 * \param user: user data
4342 * By default lws allocates this and it's not legal to externally set it
4343 * yourself. However client connections may have it set externally when the
4344 * connection is created... if so, this api can be used to modify it at
4345 * runtime additionally.
4347 LWS_VISIBLE LWS_EXTERN void
4348 lws_set_wsi_user(struct lws *wsi, void *user);
4351 * lws_parse_uri: cut up prot:/ads:port/path into pieces
4352 * Notice it does so by dropping '\0' into input string
4353 * and the leading / on the path is consequently lost
4355 * \param p: incoming uri string.. will get written to
4356 * \param prot: result pointer for protocol part (https://)
4357 * \param ads: result pointer for address part
4358 * \param port: result pointer for port part
4359 * \param path: result pointer for path part
4361 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4362 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
4366 * lws_now_secs(): return seconds since 1970-1-1
4368 LWS_VISIBLE LWS_EXTERN unsigned long
4372 * lws_get_context - Allow geting lws_context from a Websocket connection
4375 * With this function, users can access context in the callback function.
4376 * Otherwise users may have to declare context as a global variable.
4378 * \param wsi: Websocket connection instance
4380 LWS_VISIBLE LWS_EXTERN struct lws_context * LWS_WARN_UNUSED_RESULT
4381 lws_get_context(const struct lws *wsi);
4384 * lws_get_count_threads(): how many service threads the context uses
4386 * \param context: the lws context
4388 * By default this is always 1, if you asked for more than lws can handle it
4389 * will clip the number of threads. So you can use this to find out how many
4390 * threads are actually in use.
4392 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4393 lws_get_count_threads(struct lws_context *context);
4396 * lws_get_parent() - get parent wsi or NULL
4397 * \param wsi: lws connection
4399 * Specialized wsi like cgi stdin/out/err are associated to a parent wsi,
4400 * this allows you to get their parent.
4402 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
4403 lws_get_parent(const struct lws *wsi);
4406 * lws_get_child() - get child wsi or NULL
4407 * \param wsi: lws connection
4409 * Allows you to find a related wsi from the parent wsi.
4411 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
4412 lws_get_child(const struct lws *wsi);
4416 * \deprecated DEPRECATED Note: this is not normally needed as a user api.
4417 * It's provided in case it is
4418 * useful when integrating with other app poll loop service code.
4420 LWS_VISIBLE LWS_EXTERN int
4421 lws_read(struct lws *wsi, unsigned char *buf, lws_filepos_t len);
4424 * lws_set_allocator() - custom allocator support
4428 * Allows you to replace the allocator (and deallocator) used by lws
4430 LWS_VISIBLE LWS_EXTERN void
4431 lws_set_allocator(void *(*realloc)(void *ptr, size_t size));
4434 /** \defgroup wsstatus Websocket status APIs
4435 * ##Websocket connection status APIs
4437 * These provide information about ws connection or message status
4441 * lws_send_pipe_choked() - tests if socket is writable or not
4442 * \param wsi: lws connection
4444 * Allows you to check if you can write more on the socket
4446 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4447 lws_send_pipe_choked(struct lws *wsi);
4450 * lws_is_final_fragment() - tests if last part of ws message
4451 * \param wsi: lws connection
4453 LWS_VISIBLE LWS_EXTERN int
4454 lws_is_final_fragment(struct lws *wsi);
4457 * lws_get_reserved_bits() - access reserved bits of ws frame
4458 * \param wsi: lws connection
4460 LWS_VISIBLE LWS_EXTERN unsigned char
4461 lws_get_reserved_bits(struct lws *wsi);
4464 * lws_partial_buffered() - find out if lws buffered the last write
4465 * \param wsi: websocket connection to check
4467 * Returns 1 if you cannot use lws_write because the last
4468 * write on this connection is still buffered, and can't be cleared without
4469 * returning to the service loop and waiting for the connection to be
4472 * If you will try to do >1 lws_write call inside a single
4473 * WRITEABLE callback, you must check this after every write and bail if
4474 * set, ask for a new writeable callback and continue writing from there.
4476 * This is never set at the start of a writeable callback, but any write
4479 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4480 lws_partial_buffered(struct lws *wsi);
4483 * lws_frame_is_binary(): true if the current frame was sent in binary mode
4485 * \param wsi: the connection we are inquiring about
4487 * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
4488 * it's interested to see if the frame it's dealing with was sent in binary
4491 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4492 lws_frame_is_binary(struct lws *wsi);
4495 * lws_is_ssl() - Find out if connection is using SSL
4496 * \param wsi: websocket connection to check
4498 * Returns 0 if the connection is not using SSL, 1 if using SSL and
4499 * using verified cert, and 2 if using SSL but the cert was not
4500 * checked (appears for client wsi told to skip check on connection)
4502 LWS_VISIBLE LWS_EXTERN int
4503 lws_is_ssl(struct lws *wsi);
4505 * lws_is_cgi() - find out if this wsi is running a cgi process
4506 * \param wsi: lws connection
4508 LWS_VISIBLE LWS_EXTERN int
4509 lws_is_cgi(struct lws *wsi);
4511 #ifdef LWS_OPENSSL_SUPPORT
4513 * lws_get_ssl() - Return wsi's SSL context structure
4514 * \param wsi: websocket connection
4516 * Returns pointer to the SSL library's context structure
4518 LWS_VISIBLE LWS_EXTERN SSL*
4519 lws_get_ssl(struct lws *wsi);
4524 /** \defgroup sha SHA and B64 helpers
4525 * ##SHA and B64 helpers
4527 * These provide SHA-1 and B64 helper apis
4530 #ifdef LWS_SHA1_USE_OPENSSL_NAME
4531 #define lws_SHA1 SHA1
4534 * lws_SHA1(): make a SHA-1 digest of a buffer
4536 * \param d: incoming buffer
4537 * \param n: length of incoming buffer
4538 * \param md: buffer for message digest (must be >= 20 bytes)
4540 * Reduces any size buffer into a 20-byte SHA-1 hash.
4542 LWS_VISIBLE LWS_EXTERN unsigned char *
4543 lws_SHA1(const unsigned char *d, size_t n, unsigned char *md);
4546 * lws_b64_encode_string(): encode a string into base 64
4548 * \param in: incoming buffer
4549 * \param in_len: length of incoming buffer
4550 * \param out: result buffer
4551 * \param out_size: length of result buffer
4553 * Encodes a string using b64
4555 LWS_VISIBLE LWS_EXTERN int
4556 lws_b64_encode_string(const char *in, int in_len, char *out, int out_size);
4558 * lws_b64_decode_string(): decode a string from base 64
4560 * \param in: incoming buffer
4561 * \param out: result buffer
4562 * \param out_size: length of result buffer
4564 * Decodes a string using b64
4566 LWS_VISIBLE LWS_EXTERN int
4567 lws_b64_decode_string(const char *in, char *out, int out_size);
4571 /*! \defgroup cgi cgi handling
4575 * These functions allow low-level control over stdin/out/err of the cgi.
4577 * However for most cases, binding the cgi to http in and out, the default
4578 * lws implementation already does the right thing.
4581 enum lws_enum_stdinouterr {
4587 enum lws_cgi_hdr_state {
4599 struct lws_cgi_args {
4600 struct lws **stdwsi; /**< get fd with lws_get_socket_fd() */
4601 enum lws_enum_stdinouterr ch; /**< channel index */
4602 unsigned char *data; /**< for messages with payload */
4603 enum lws_cgi_hdr_state hdr_state; /**< track where we are in cgi headers */
4604 int len; /**< length */
4609 * lws_cgi: spawn network-connected cgi process
4611 * \param wsi: connection to own the process
4612 * \param exec_array: array of "exec-name" "arg1" ... "argn" NULL
4613 * \param script_uri_path_len: how many chars on the left of the uri are the path to the cgi
4614 * \param timeout_secs: seconds script should be allowed to run
4615 * \param mp_cgienv: pvo list with per-vhost cgi options to put in env
4617 LWS_VISIBLE LWS_EXTERN int
4618 lws_cgi(struct lws *wsi, const char * const *exec_array,
4619 int script_uri_path_len, int timeout_secs,
4620 const struct lws_protocol_vhost_options *mp_cgienv);
4623 * lws_cgi_write_split_stdout_headers: write cgi output accounting for header part
4625 * \param wsi: connection to own the process
4627 LWS_VISIBLE LWS_EXTERN int
4628 lws_cgi_write_split_stdout_headers(struct lws *wsi);
4631 * lws_cgi_kill: terminate cgi process associated with wsi
4633 * \param wsi: connection to own the process
4635 LWS_VISIBLE LWS_EXTERN int
4636 lws_cgi_kill(struct lws *wsi);
4641 /*! \defgroup fops file operation wrapping
4643 * ##File operation wrapping
4645 * Use these helper functions if you want to access a file from the perspective
4646 * of a specific wsi, which is usually the case. If you just want contextless
4647 * file access, use the fops callbacks directly with NULL wsi instead of these
4650 * If so, then it calls the platform handler or user overrides where present
4651 * (as defined in info->fops)
4653 * The advantage from all this is user code can be portable for file operations
4654 * without having to deal with differences between platforms.
4658 /** struct lws_plat_file_ops - Platform-specific file operations
4660 * These provide platform-agnostic ways to deal with filesystem access in the
4661 * library and in the user code.
4664 #if defined(LWS_WITH_ESP32)
4665 /* sdk preprocessor defs? compiler issue? gets confused with member names */
4666 #define LWS_FOP_OPEN _open
4667 #define LWS_FOP_CLOSE _close
4668 #define LWS_FOP_SEEK_CUR _seek_cur
4669 #define LWS_FOP_READ _read
4670 #define LWS_FOP_WRITE _write
4672 #define LWS_FOP_OPEN open
4673 #define LWS_FOP_CLOSE close
4674 #define LWS_FOP_SEEK_CUR seek_cur
4675 #define LWS_FOP_READ read
4676 #define LWS_FOP_WRITE write
4679 #define LWS_FOP_FLAGS_MASK ((1 << 23) - 1)
4680 #define LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP (1 << 24)
4681 #define LWS_FOP_FLAG_COMPR_IS_GZIP (1 << 25)
4682 #define LWS_FOP_FLAG_MOD_TIME_VALID (1 << 26)
4683 #define LWS_FOP_FLAG_VIRTUAL (1 << 27)
4685 struct lws_plat_file_ops;
4689 /**< real file descriptor related to the file... */
4690 const struct lws_plat_file_ops *fops;
4691 /**< fops that apply to this fop_fd */
4692 void *filesystem_priv;
4693 /**< ignored by lws; owned by the fops handlers */
4695 /**< generic "position in file" */
4697 /**< generic "length of file" */
4698 lws_fop_flags_t flags;
4699 /**< copy of the returned flags */
4701 /**< optional "modification time of file", only valid if .open()
4702 * set the LWS_FOP_FLAG_MOD_TIME_VALID flag */
4704 typedef struct lws_fop_fd *lws_fop_fd_t;
4706 struct lws_fops_index {
4707 const char *sig; /* NULL or vfs signature, eg, ".zip/" */
4708 uint8_t len; /* length of above string */
4711 struct lws_plat_file_ops {
4712 lws_fop_fd_t (*LWS_FOP_OPEN)(const struct lws_plat_file_ops *fops,
4713 const char *filename, const char *vpath,
4714 lws_fop_flags_t *flags);
4715 /**< Open file (always binary access if plat supports it)
4716 * vpath may be NULL, or if the fops understands it, the point at which
4717 * the filename's virtual part starts.
4718 * *flags & LWS_FOP_FLAGS_MASK should be set to O_RDONLY or O_RDWR.
4719 * If the file may be gzip-compressed,
4720 * LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP is set. If it actually is
4721 * gzip-compressed, then the open handler should OR
4722 * LWS_FOP_FLAG_COMPR_IS_GZIP on to *flags before returning.
4724 int (*LWS_FOP_CLOSE)(lws_fop_fd_t *fop_fd);
4725 /**< close file AND set the pointer to NULL */
4726 lws_fileofs_t (*LWS_FOP_SEEK_CUR)(lws_fop_fd_t fop_fd,
4727 lws_fileofs_t offset_from_cur_pos);
4728 /**< seek from current position */
4729 int (*LWS_FOP_READ)(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4730 uint8_t *buf, lws_filepos_t len);
4731 /**< Read from file, on exit *amount is set to amount actually read */
4732 int (*LWS_FOP_WRITE)(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4733 uint8_t *buf, lws_filepos_t len);
4734 /**< Write to file, on exit *amount is set to amount actually written */
4736 struct lws_fops_index fi[3];
4737 /**< vfs path signatures implying use of this fops */
4739 const struct lws_plat_file_ops *next;
4740 /**< NULL or next fops in list */
4742 /* Add new things just above here ---^
4743 * This is part of the ABI, don't needlessly break compatibility */
4747 * lws_get_fops() - get current file ops
4749 * \param context: context
4751 LWS_VISIBLE LWS_EXTERN struct lws_plat_file_ops * LWS_WARN_UNUSED_RESULT
4752 lws_get_fops(struct lws_context *context);
4753 LWS_VISIBLE LWS_EXTERN void
4754 lws_set_fops(struct lws_context *context, const struct lws_plat_file_ops *fops);
4756 * lws_vfs_tell() - get current file position
4758 * \param fop_fd: fop_fd we are asking about
4760 LWS_VISIBLE LWS_EXTERN lws_filepos_t LWS_WARN_UNUSED_RESULT
4761 lws_vfs_tell(lws_fop_fd_t fop_fd);
4763 * lws_vfs_get_length() - get current file total length in bytes
4765 * \param fop_fd: fop_fd we are asking about
4767 LWS_VISIBLE LWS_EXTERN lws_filepos_t LWS_WARN_UNUSED_RESULT
4768 lws_vfs_get_length(lws_fop_fd_t fop_fd);
4770 * lws_vfs_get_mod_time() - get time file last modified
4772 * \param fop_fd: fop_fd we are asking about
4774 LWS_VISIBLE LWS_EXTERN uint32_t LWS_WARN_UNUSED_RESULT
4775 lws_vfs_get_mod_time(lws_fop_fd_t fop_fd);
4777 * lws_vfs_file_seek_set() - seek relative to start of file
4779 * \param fop_fd: fop_fd we are seeking in
4780 * \param offset: offset from start of file
4782 LWS_VISIBLE LWS_EXTERN lws_fileofs_t
4783 lws_vfs_file_seek_set(lws_fop_fd_t fop_fd, lws_fileofs_t offset);
4785 * lws_vfs_file_seek_end() - seek relative to end of file
4787 * \param fop_fd: fop_fd we are seeking in
4788 * \param offset: offset from start of file
4790 LWS_VISIBLE LWS_EXTERN lws_fileofs_t
4791 lws_vfs_file_seek_end(lws_fop_fd_t fop_fd, lws_fileofs_t offset);
4793 extern struct lws_plat_file_ops fops_zip;
4796 * lws_plat_file_open() - open vfs filepath
4798 * \param fops: file ops struct that applies to this descriptor
4799 * \param vfs_path: filename to open
4800 * \param flags: pointer to open flags
4802 * The vfs_path is scanned for known fops signatures, and the open directed
4803 * to any matching fops open.
4805 * User code should use this api to perform vfs opens.
4807 * returns semi-opaque handle
4809 LWS_VISIBLE LWS_EXTERN lws_fop_fd_t LWS_WARN_UNUSED_RESULT
4810 lws_vfs_file_open(const struct lws_plat_file_ops *fops, const char *vfs_path,
4811 lws_fop_flags_t *flags);
4814 * lws_plat_file_close() - close file
4816 * \param fop_fd: file handle to close
4818 static LWS_INLINE int
4819 lws_vfs_file_close(lws_fop_fd_t *fop_fd)
4821 return (*fop_fd)->fops->LWS_FOP_CLOSE(fop_fd);
4825 * lws_plat_file_seek_cur() - close file
4828 * \param fop_fd: file handle
4829 * \param offset: position to seek to
4831 static LWS_INLINE lws_fileofs_t
4832 lws_vfs_file_seek_cur(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
4834 return fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, offset);
4837 * lws_plat_file_read() - read from file
4839 * \param fop_fd: file handle
4840 * \param amount: how much to read (rewritten by call)
4841 * \param buf: buffer to write to
4842 * \param len: max length
4844 static LWS_INLINE int LWS_WARN_UNUSED_RESULT
4845 lws_vfs_file_read(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4846 uint8_t *buf, lws_filepos_t len)
4848 return fop_fd->fops->LWS_FOP_READ(fop_fd, amount, buf, len);
4851 * lws_plat_file_write() - write from file
4853 * \param fop_fd: file handle
4854 * \param amount: how much to write (rewritten by call)
4855 * \param buf: buffer to read from
4856 * \param len: max length
4858 static LWS_INLINE int LWS_WARN_UNUSED_RESULT
4859 lws_vfs_file_write(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4860 uint8_t *buf, lws_filepos_t len)
4862 return fop_fd->fops->LWS_FOP_WRITE(fop_fd, amount, buf, len);
4865 /* these are the platform file operations implementations... they can
4866 * be called directly and used in fops arrays
4869 LWS_VISIBLE LWS_EXTERN lws_fop_fd_t
4870 _lws_plat_file_open(const struct lws_plat_file_ops *fops, const char *filename,
4871 const char *vpath, lws_fop_flags_t *flags);
4872 LWS_VISIBLE LWS_EXTERN int
4873 _lws_plat_file_close(lws_fop_fd_t *fop_fd);
4874 LWS_VISIBLE LWS_EXTERN lws_fileofs_t
4875 _lws_plat_file_seek_cur(lws_fop_fd_t fop_fd, lws_fileofs_t offset);
4876 LWS_VISIBLE LWS_EXTERN int
4877 _lws_plat_file_read(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4878 uint8_t *buf, lws_filepos_t len);
4879 LWS_VISIBLE LWS_EXTERN int
4880 _lws_plat_file_write(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4881 uint8_t *buf, lws_filepos_t len);
4883 LWS_VISIBLE LWS_EXTERN int
4884 lws_alloc_vfs_file(struct lws_context *context, const char *filename, uint8_t **buf,
4885 lws_filepos_t *amount);
4890 * ##SMTP related functions
4892 * These apis let you communicate with a local SMTP server to send email from
4893 * lws. It handles all the SMTP sequencing and protocol actions.
4895 * Your system should have postfix, sendmail or another MTA listening on port
4896 * 25 and able to send email using the "mail" commandline app. Usually distro
4897 * MTAs are configured for this by default.
4899 * It runs via its own libuv events if initialized (which requires giving it
4900 * a libuv loop to attach to).
4902 * It operates using three callbacks, on_next() queries if there is a new email
4903 * to send, on_get_body() asks for the body of the email, and on_sent() is
4904 * called after the email is successfully sent.
4908 * - create an lws_email struct
4910 * - initialize data, loop, the email_* strings, max_content_size and
4913 * - call lws_email_init()
4915 * When you have at least one email to send, call lws_email_check() to
4916 * schedule starting to send it.
4919 #ifdef LWS_WITH_SMTP
4921 /** enum lwsgs_smtp_states - where we are in SMTP protocol sequence */
4922 enum lwsgs_smtp_states {
4923 LGSSMTP_IDLE, /**< awaiting new email */
4924 LGSSMTP_CONNECTING, /**< opening tcp connection to MTA */
4925 LGSSMTP_CONNECTED, /**< tcp connection to MTA is connected */
4926 LGSSMTP_SENT_HELO, /**< sent the HELO */
4927 LGSSMTP_SENT_FROM, /**< sent FROM */
4928 LGSSMTP_SENT_TO, /**< sent TO */
4929 LGSSMTP_SENT_DATA, /**< sent DATA request */
4930 LGSSMTP_SENT_BODY, /**< sent the email body */
4931 LGSSMTP_SENT_QUIT, /**< sent the session quit */
4934 /** struct lws_email - abstract context for performing SMTP operations */
4937 /**< opaque pointer set by user code and available to the callbacks */
4939 /**< the libuv loop we will work on */
4941 char email_smtp_ip[32]; /**< Fill before init, eg, "127.0.0.1" */
4942 char email_helo[32]; /**< Fill before init, eg, "myserver.com" */
4943 char email_from[100]; /**< Fill before init or on_next */
4944 char email_to[100]; /**< Fill before init or on_next */
4946 unsigned int max_content_size;
4947 /**< largest possible email body size */
4949 /* Fill all the callbacks before init */
4951 int (*on_next)(struct lws_email *email);
4952 /**< (Fill in before calling lws_email_init)
4953 * called when idle, 0 = another email to send, nonzero is idle.
4954 * If you return 0, all of the email_* char arrays must be set
4955 * to something useful. */
4956 int (*on_sent)(struct lws_email *email);
4957 /**< (Fill in before calling lws_email_init)
4958 * called when transfer of the email to the SMTP server was
4959 * successful, your callback would remove the current email
4961 int (*on_get_body)(struct lws_email *email, char *buf, int len);
4962 /**< (Fill in before calling lws_email_init)
4963 * called when the body part of the queued email is about to be
4964 * sent to the SMTP server. */
4967 /* private things */
4968 uv_timer_t timeout_email; /**< private */
4969 enum lwsgs_smtp_states estate; /**< private */
4970 uv_connect_t email_connect_req; /**< private */
4971 uv_tcp_t email_client; /**< private */
4972 time_t email_connect_started; /**< private */
4973 char email_buf[256]; /**< private */
4974 char *content; /**< private */
4978 * lws_email_init() - Initialize a struct lws_email
4980 * \param email: struct lws_email to init
4981 * \param loop: libuv loop to use
4982 * \param max_content: max email content size
4984 * Prepares a struct lws_email for use ending SMTP
4986 LWS_VISIBLE LWS_EXTERN int
4987 lws_email_init(struct lws_email *email, uv_loop_t *loop, int max_content);
4990 * lws_email_check() - Request check for new email
4992 * \param email: struct lws_email context to check
4994 * Schedules a check for new emails in 1s... call this when you have queued an
4997 LWS_VISIBLE LWS_EXTERN void
4998 lws_email_check(struct lws_email *email);
5000 * lws_email_destroy() - stop using the struct lws_email
5002 * \param email: the struct lws_email context
5004 * Stop sending email using email and free allocations
5006 LWS_VISIBLE LWS_EXTERN void
5007 lws_email_destroy(struct lws_email *email);
5013 * Stats are all uint64_t numbers that start at 0.
5014 * Index names here have the convention
5018 * _MS_ millisecond count
5022 LWSSTATS_C_CONNECTIONS, /**< count incoming connections */
5023 LWSSTATS_C_API_CLOSE, /**< count calls to close api */
5024 LWSSTATS_C_API_READ, /**< count calls to read from socket api */
5025 LWSSTATS_C_API_LWS_WRITE, /**< count calls to lws_write API */
5026 LWSSTATS_C_API_WRITE, /**< count calls to write API */
5027 LWSSTATS_C_WRITE_PARTIALS, /**< count of partial writes */
5028 LWSSTATS_C_WRITEABLE_CB_REQ, /**< count of writable callback requests */
5029 LWSSTATS_C_WRITEABLE_CB_EFF_REQ, /**< count of effective writable callback requests */
5030 LWSSTATS_C_WRITEABLE_CB, /**< count of writable callbacks */
5031 LWSSTATS_C_SSL_CONNECTIONS_FAILED, /**< count of failed SSL connections */
5032 LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED, /**< count of accepted SSL connections */
5033 LWSSTATS_C_SSL_CONNS_HAD_RX, /**< count of accepted SSL conns that have had some RX */
5034 LWSSTATS_C_TIMEOUTS, /**< count of timed-out connections */
5035 LWSSTATS_C_SERVICE_ENTRY, /**< count of entries to lws service loop */
5036 LWSSTATS_B_READ, /**< aggregate bytes read */
5037 LWSSTATS_B_WRITE, /**< aggregate bytes written */
5038 LWSSTATS_B_PARTIALS_ACCEPTED_PARTS, /**< aggreate of size of accepted write data from new partials */
5039 LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY, /**< aggregate delay in accepting connection */
5040 LWSSTATS_MS_WRITABLE_DELAY, /**< aggregate delay between asking for writable and getting cb */
5041 LWSSTATS_MS_WORST_WRITABLE_DELAY, /**< single worst delay between asking for writable and getting cb */
5042 LWSSTATS_MS_SSL_RX_DELAY, /**< aggregate delay between ssl accept complete and first RX */
5044 /* Add new things just above here ---^
5045 * This is part of the ABI, don't needlessly break compatibility */
5049 #if defined(LWS_WITH_STATS)
5051 LWS_VISIBLE LWS_EXTERN uint64_t
5052 lws_stats_get(struct lws_context *context, int index);
5053 LWS_VISIBLE LWS_EXTERN void
5054 lws_stats_log_dump(struct lws_context *context);
5056 static LWS_INLINE uint64_t
5057 lws_stats_get(struct lws_context *context, int index) { return 0; }
5058 static LWS_INLINE void
5059 lws_stats_log_dump(struct lws_context *context) { }