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_WITH_ESP8266)
43 #include "lws_config.h"
45 #if defined(WIN32) || defined(_WIN32)
46 #ifndef WIN32_LEAN_AND_MEAN
47 #define WIN32_LEAN_AND_MEAN
57 #define _O_RDONLY 0x0000
58 #define O_RDONLY _O_RDONLY
61 // Visual studio older than 2015 and WIN_CE has only _stricmp
62 #if (defined(_MSC_VER) && _MSC_VER < 1900) || defined(_WIN32_WCE)
63 #define strcasecmp _stricmp
64 #elif !defined(__MINGW32__)
65 #define strcasecmp stricmp
67 #define getdtablesize() 30000
69 #define LWS_INLINE __inline
71 #define LWS_WARN_UNUSED_RESULT
72 #define LWS_WARN_DEPRECATED
73 #define LWS_FORMAT(string_index)
77 #define LWS_EXTERN extern __declspec(dllexport)
79 #define LWS_EXTERN extern __declspec(dllimport)
85 #define LWS_INVALID_FILE INVALID_HANDLE_VALUE
86 #define LWS_O_RDONLY _O_RDONLY
87 #define LWS_O_WRONLY _O_WRONLY
88 #define LWS_O_CREAT _O_CREAT
89 #define LWS_O_TRUNC _O_TRUNC
91 #if !defined(__MINGW32__) && (!defined(_MSC_VER) || _MSC_VER < 1900) /* Visual Studio 2015 already defines this in <stdio.h> */
92 #define lws_snprintf _snprintf
96 #define __func__ __FUNCTION__
99 #if !defined(__MINGW32__) &&(!defined(_MSC_VER) || _MSC_VER < 1900) && !defined(snprintf)
100 #define snprintf(buf,len, format,...) _snprintf_s(buf, len,len, format, __VA_ARGS__)
103 #else /* NOT WIN32 */
105 #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
106 #include <sys/capability.h>
109 #if defined(__NetBSD__) || defined(__FreeBSD__)
110 #include <netinet/in.h>
113 #define LWS_INLINE inline
114 #define LWS_O_RDONLY O_RDONLY
115 #define LWS_O_WRONLY O_WRONLY
116 #define LWS_O_CREAT O_CREAT
117 #define LWS_O_TRUNC O_TRUNC
119 #if !defined(LWS_WITH_ESP8266) && !defined(OPTEE_TA) && !defined(LWS_WITH_ESP32)
122 #define LWS_INVALID_FILE -1
124 #define getdtablesize() (30)
125 #if defined(LWS_WITH_ESP32)
126 #define LWS_INVALID_FILE NULL
128 #define LWS_INVALID_FILE NULL
132 #if defined(__GNUC__)
134 /* warn_unused_result attribute only supported by GCC 3.4 or later */
135 #if __GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
136 #define LWS_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
138 #define LWS_WARN_UNUSED_RESULT
141 #define LWS_VISIBLE __attribute__((visibility("default")))
142 #define LWS_WARN_DEPRECATED __attribute__ ((deprecated))
143 #define LWS_FORMAT(string_index) __attribute__ ((format(printf, string_index, string_index+1)))
146 #define LWS_WARN_UNUSED_RESULT
147 #define LWS_WARN_DEPRECATED
148 #define LWS_FORMAT(string_index)
151 #if defined(__ANDROID__)
153 #define getdtablesize() sysconf(_SC_OPEN_MAX)
160 #endif /* LWS_USE_LIBEV */
163 #ifdef LWS_HAVE_UV_VERSION_H
164 #include <uv-version.h>
166 #endif /* LWS_USE_LIBUV */
167 #ifdef LWS_USE_LIBEVENT
168 #include <event2/event.h>
169 #endif /* LWS_USE_LIBEVENT */
172 #define LWS_EXTERN extern
178 #if !defined(OPTEE_TA)
179 #include <sys/time.h>
184 #ifdef LWS_OPENSSL_SUPPORT
187 #ifdef USE_OLD_CYASSL
188 #include <cyassl/openssl/ssl.h>
189 #include <cyassl/error-ssl.h>
191 #include <wolfssl/openssl/ssl.h>
192 #include <wolfssl/error-ssl.h>
193 #endif /* not USE_OLD_CYASSL */
195 #include <openssl/ssl.h>
196 #if !defined(LWS_WITH_ESP32)
197 #include <openssl/err.h>
199 #endif /* not USE_WOLFSSL */
203 #define CONTEXT_PORT_NO_LISTEN -1
204 #define CONTEXT_PORT_NO_LISTEN_SERVER -2
206 /** \defgroup log Logging
210 * Lws provides flexible and filterable logging facilities, which can be
211 * used inside lws and in user code.
213 * Log categories may be individually filtered bitwise, and directed to built-in
214 * sinks for syslog-compatible logging, or a user-defined function.
218 enum lws_log_levels {
228 LLL_LATENCY = 1 << 9,
231 LLL_COUNT = 11 /* set to count of valid flags */
234 LWS_VISIBLE LWS_EXTERN void _lws_log(int filter, const char *format, ...) LWS_FORMAT(2);
235 LWS_VISIBLE LWS_EXTERN void _lws_logv(int filter, const char *format, va_list vl);
237 * lwsl_timestamp: generate logging timestamp string
239 * \param level: logging level
240 * \param p: char * buffer to take timestamp
241 * \param len: length of p
243 * returns length written in p
245 LWS_VISIBLE LWS_EXTERN int
246 lwsl_timestamp(int level, char *p, int len);
248 /* these guys are unconditionally included */
250 #define lwsl_err(...) _lws_log(LLL_ERR, __VA_ARGS__)
251 #define lwsl_user(...) _lws_log(LLL_USER, __VA_ARGS__)
253 #if !defined(LWS_WITH_NO_LOGS)
254 /* notice and warn are usually included by being compiled in */
255 #define lwsl_warn(...) _lws_log(LLL_WARN, __VA_ARGS__)
256 #define lwsl_notice(...) _lws_log(LLL_NOTICE, __VA_ARGS__)
259 * weaker logging can be deselected by telling CMake to build in RELEASE mode
260 * that gets rid of the overhead of checking while keeping _warn and _err
264 #if defined(LWS_WITH_ESP8266)
269 #if defined(LWS_WITH_NO_LOGS)
270 /* notice, warn and log are always compiled in */
271 #define lwsl_warn(...) _lws_log(LLL_WARN, __VA_ARGS__)
272 #define lwsl_notice(...) _lws_log(LLL_NOTICE, __VA_ARGS__)
274 #define lwsl_info(...) _lws_log(LLL_INFO, __VA_ARGS__)
275 #define lwsl_debug(...) _lws_log(LLL_DEBUG, __VA_ARGS__)
276 #define lwsl_parser(...) _lws_log(LLL_PARSER, __VA_ARGS__)
277 #define lwsl_header(...) _lws_log(LLL_HEADER, __VA_ARGS__)
278 #define lwsl_ext(...) _lws_log(LLL_EXT, __VA_ARGS__)
279 #define lwsl_client(...) _lws_log(LLL_CLIENT, __VA_ARGS__)
280 #define lwsl_latency(...) _lws_log(LLL_LATENCY, __VA_ARGS__)
282 * lwsl_hexdump() - helper to hexdump a buffer (DEBUG builds only)
284 * \param buf: buffer start to dump
285 * \param len: length of buffer to dump
287 LWS_VISIBLE LWS_EXTERN void lwsl_hexdump(void *buf, size_t len);
290 #if defined(LWS_WITH_NO_LOGS)
291 #define lwsl_warn(...) do {} while(0)
292 #define lwsl_notice(...) do {} while(0)
294 #define lwsl_info(...) do {} while(0)
295 #define lwsl_debug(...) do {} while(0)
296 #define lwsl_parser(...) do {} while(0)
297 #define lwsl_header(...) do {} while(0)
298 #define lwsl_ext(...) do {} while(0)
299 #define lwsl_client(...) do {} while(0)
300 #define lwsl_latency(...) do {} while(0)
301 #define lwsl_hexdump(a, b)
305 static LWS_INLINE int lws_is_be(void) {
306 const int probe = ~0xff;
308 return *(const char *)&probe;
312 * lws_set_log_level() - Set the logging bitfield
313 * \param level: OR together the LLL_ debug contexts you want output from
314 * \param log_emit_function: NULL to leave it as it is, or a user-supplied
315 * function to perform log string emission instead of
316 * the default stderr one.
318 * log level defaults to "err", "warn" and "notice" contexts enabled and
319 * emission on stderr.
321 LWS_VISIBLE LWS_EXTERN void
322 lws_set_log_level(int level,
323 void (*log_emit_function)(int level, const char *line));
326 * lwsl_emit_syslog() - helper log emit function writes to system log
328 * \param level: one of LLL_ log level indexes
329 * \param line: log string
331 * You use this by passing the function pointer to lws_set_log_level(), to set
332 * it as the log emit function, it is not called directly.
334 LWS_VISIBLE LWS_EXTERN void
335 lwsl_emit_syslog(int level, const char *line);
338 * lwsl_visible() - returns true if the log level should be printed
340 * \param level: one of LLL_ log level indexes
342 * This is useful if you have to do work to generate the log content, you
343 * can skip the work if the log level used to print it is not actually
344 * enabled at runtime.
346 LWS_VISIBLE LWS_EXTERN int
347 lwsl_visible(int level);
354 #ifndef lws_container_of
355 #define lws_container_of(P,T,M) ((T *)((char *)(P) - offsetof(T, M)))
361 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
364 /* api change list for user code to test against */
366 #define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_ARG
368 /* the struct lws_protocols has the id field present */
369 #define LWS_FEATURE_PROTOCOLS_HAS_ID_FIELD
371 /* you can call lws_get_peer_write_allowance */
372 #define LWS_FEATURE_PROTOCOLS_HAS_PEER_WRITE_ALLOWANCE
374 /* extra parameter introduced in 917f43ab821 */
375 #define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_LEN
377 /* File operations stuff exists */
378 #define LWS_FEATURE_FOPS
382 typedef SOCKET lws_sockfd_type;
383 typedef HANDLE lws_filefd_type;
384 #define lws_sockfd_valid(sfd) (!!sfd)
386 lws_sockfd_type fd; /**< file descriptor */
387 SHORT events; /**< which events to respond to */
388 SHORT revents; /**< which events happened */
390 #define LWS_POLLHUP (FD_CLOSE)
391 #define LWS_POLLIN (FD_READ | FD_ACCEPT)
392 #define LWS_POLLOUT (FD_WRITE)
396 #if defined(LWS_WITH_ESP8266)
398 #include <user_interface.h>
401 typedef struct espconn * lws_sockfd_type;
402 typedef void * lws_filefd_type;
403 #define lws_sockfd_valid(sfd) (!!sfd)
405 lws_sockfd_type fd; /**< fd related to */
406 short events; /**< which POLL... events to respond to */
407 short revents; /**< which POLL... events occurred */
409 #define POLLIN 0x0001
410 #define POLLPRI 0x0002
411 #define POLLOUT 0x0004
412 #define POLLERR 0x0008
413 #define POLLHUP 0x0010
414 #define POLLNVAL 0x0020
418 lws_sockfd_type esp8266_create_tcp_listen_socket(struct lws_vhost *vh);
419 void esp8266_tcp_stream_accept(lws_sockfd_type fd, struct lws *wsi);
425 int ets_snprintf(char *str, size_t size, const char *format, ...) LWS_FORMAT(3);
426 #define snprintf ets_snprintf
428 typedef os_timer_t uv_timer_t;
429 typedef void uv_cb_t(uv_timer_t *);
431 void os_timer_disarm(void *);
432 void os_timer_setfn(os_timer_t *, os_timer_func_t *, void *);
434 void ets_timer_arm_new(os_timer_t *, int, int, int);
436 //void os_timer_arm(os_timer_t *, int, int);
438 #define UV_VERSION_MAJOR 1
440 #define lws_uv_getloop(a, b) (NULL)
442 static inline void uv_timer_init(void *l, uv_timer_t *t)
445 memset(t, 0, sizeof(*t));
449 static inline void uv_timer_start(uv_timer_t *t, uv_cb_t *cb, int first, int rep)
451 os_timer_setfn(t, (os_timer_func_t *)cb, t);
453 os_timer_arm(t, first, !!rep);
456 static inline void uv_timer_stop(uv_timer_t *t)
462 #if defined(LWS_WITH_ESP32)
464 typedef int lws_sockfd_type;
465 typedef int lws_filefd_type;
466 #define lws_sockfd_valid(sfd) (sfd >= 0)
468 lws_sockfd_type fd; /**< fd related to */
469 short events; /**< which POLL... events to respond to */
470 short revents; /**< which POLL... events occurred */
472 #define POLLIN 0x0001
473 #define POLLPRI 0x0002
474 #define POLLOUT 0x0004
475 #define POLLERR 0x0008
476 #define POLLHUP 0x0010
477 #define POLLNVAL 0x0020
479 #include <freertos/FreeRTOS.h>
480 #include <freertos/event_groups.h>
482 #include "esp_wifi.h"
483 #include "esp_system.h"
484 #include "esp_event.h"
485 #include "esp_event_loop.h"
487 #include "driver/gpio.h"
488 #include "esp_spi_flash.h"
489 #include "freertos/timers.h"
491 #if !defined(CONFIG_FREERTOS_HZ)
492 #define CONFIG_FREERTOS_HZ 100
495 typedef TimerHandle_t uv_timer_t;
496 typedef void uv_cb_t(uv_timer_t *);
497 typedef void * uv_handle_t;
499 struct timer_mapping {
504 #define UV_VERSION_MAJOR 1
506 #define lws_uv_getloop(a, b) (NULL)
508 static inline void uv_timer_init(void *l, uv_timer_t *t)
514 extern void esp32_uvtimer_cb(TimerHandle_t t);
516 static inline void uv_timer_start(uv_timer_t *t, uv_cb_t *cb, int first, int rep)
518 struct timer_mapping *tm = (struct timer_mapping *)malloc(sizeof(*tm));
526 *t = xTimerCreate("x", pdMS_TO_TICKS(first), !!rep, tm,
527 (TimerCallbackFunction_t)esp32_uvtimer_cb);
531 static inline void uv_timer_stop(uv_timer_t *t)
536 static inline void uv_close(uv_handle_t *h, void *v)
538 free(pvTimerGetTimerID((uv_timer_t)h));
539 xTimerDelete(*(uv_timer_t *)h, 0);
542 /* ESP32 helper declarations */
545 #include <esp_partition.h>
547 #define LWS_PLUGIN_STATIC
548 #define LWS_MAGIC_REBOOT_TYPE_ADS 0x50001ffc
549 #define LWS_MAGIC_REBOOT_TYPE_REQ_FACTORY 0xb00bcafe
550 #define LWS_MAGIC_REBOOT_TYPE_FORCED_FACTORY 0xfaceb00b
551 #define LWS_MAGIC_REBOOT_TYPE_FORCED_FACTORY_BUTTON 0xf0cedfac
554 /* user code provides these */
557 lws_esp32_identify_physical_device(void);
559 /* lws-plat-esp32 provides these */
561 typedef void (*lws_cb_scan_done)(uint16_t count, wifi_ap_record_t *recs, void *arg);
564 LWSESP32_GENLED__INIT,
565 LWSESP32_GENLED__LOST_NETWORK,
566 LWSESP32_GENLED__NO_NETWORK,
567 LWSESP32_GENLED__CONN_AP,
568 LWSESP32_GENLED__GOT_IP,
572 struct lws_group_member {
573 struct lws_group_member *next;
580 struct ip4_addr addr;
581 struct ip6_addr addrv6;
585 #define LWS_SYSTEM_GROUP_MEMBER_ADD 1
586 #define LWS_SYSTEM_GROUP_MEMBER_CHANGE 2
587 #define LWS_SYSTEM_GROUP_MEMBER_REMOVE 3
589 #define LWS_GROUP_FLAG_SELF 1
601 char password[4][32];
602 char active_ssid[32];
611 enum genled_state genled;
614 lws_cb_scan_done scan_consumer;
615 void *scan_consumer_arg;
616 struct lws_group_member *first;
617 int extant_group_members;
620 struct lws_esp32_image {
627 extern struct lws_esp32 lws_esp32;
630 lws_esp32_event_passthru(void *ctx, system_event_t *event);
632 lws_esp32_wlan_config(void);
634 lws_esp32_wlan_start_ap(void);
636 lws_esp32_wlan_start_station(void);
637 struct lws_context_creation_info;
639 lws_esp32_set_creation_defaults(struct lws_context_creation_info *info);
640 extern struct lws_context *
641 lws_esp32_init(struct lws_context_creation_info *);
643 lws_esp32_wlan_nvs_get(int retry);
645 lws_nvs_set_str(nvs_handle handle, const char* key, const char* value);
647 lws_esp32_restart_guided(uint32_t type);
648 extern const esp_partition_t *
649 lws_esp_ota_get_boot_partition(void);
651 lws_esp32_get_image_info(const esp_partition_t *part, struct lws_esp32_image *i, char *json, int json_len);
653 lws_esp32_leds_network_indication(void);
655 extern uint32_t lws_esp32_get_reboot_type(void);
656 extern uint16_t lws_esp32_sine_interp(int n);
658 /* required in external code by esp32 plat (may just return if no leds) */
659 extern void lws_esp32_leds_timer_cb(TimerHandle_t th);
661 typedef int lws_sockfd_type;
662 typedef int lws_filefd_type;
663 #define lws_sockfd_valid(sfd) (sfd >= 0)
667 #define lws_pollfd pollfd
668 #define LWS_POLLHUP (POLLHUP|POLLERR)
669 #define LWS_POLLIN (POLLIN)
670 #define LWS_POLLOUT (POLLOUT)
674 #if (defined(WIN32) || defined(_WIN32)) && !defined(__MINGW32__)
676 #if !defined(ssize_t)
677 typedef SSIZE_T ssize_t;
681 #if defined(LWS_HAVE_STDINT_H)
684 #if defined(WIN32) || defined(_WIN32)
686 typedef unsigned __int32 uint32_t;
687 typedef unsigned __int16 uint16_t;
688 typedef unsigned __int8 uint8_t;
690 typedef unsigned int uint32_t;
691 typedef unsigned short uint16_t;
692 typedef unsigned char uint8_t;
696 typedef size_t lws_filepos_t;
697 typedef ssize_t lws_fileofs_t;
698 typedef uint32_t lws_fop_flags_t;
700 /** struct lws_pollargs - argument structure for all external poll related calls
701 * passed in via 'in' */
702 struct lws_pollargs {
703 lws_sockfd_type fd; /**< applicable socket descriptor */
704 int events; /**< the new event mask */
705 int prev_events; /**< the previous event mask */
709 struct lws_token_limits;
711 /*! \defgroup wsclose Websocket Close
713 * ##Websocket close frame control
715 * When we close a ws connection, we can send a reason code and a short
716 * UTF-8 description back with the close packet.
721 * NOTE: These public enums are part of the abi. If you want to add one,
722 * add it at where specified so existing users are unaffected.
724 /** enum lws_close_status - RFC6455 close status codes */
725 enum lws_close_status {
726 LWS_CLOSE_STATUS_NOSTATUS = 0,
727 LWS_CLOSE_STATUS_NORMAL = 1000,
728 /**< 1000 indicates a normal closure, meaning that the purpose for
729 which the connection was established has been fulfilled. */
730 LWS_CLOSE_STATUS_GOINGAWAY = 1001,
731 /**< 1001 indicates that an endpoint is "going away", such as a server
732 going down or a browser having navigated away from a page. */
733 LWS_CLOSE_STATUS_PROTOCOL_ERR = 1002,
734 /**< 1002 indicates that an endpoint is terminating the connection due
735 to a protocol error. */
736 LWS_CLOSE_STATUS_UNACCEPTABLE_OPCODE = 1003,
737 /**< 1003 indicates that an endpoint is terminating the connection
738 because it has received a type of data it cannot accept (e.g., an
739 endpoint that understands only text data MAY send this if it
740 receives a binary message). */
741 LWS_CLOSE_STATUS_RESERVED = 1004,
742 /**< Reserved. The specific meaning might be defined in the future. */
743 LWS_CLOSE_STATUS_NO_STATUS = 1005,
744 /**< 1005 is a reserved value and MUST NOT be set as a status code in a
745 Close control frame by an endpoint. It is designated for use in
746 applications expecting a status code to indicate that no status
747 code was actually present. */
748 LWS_CLOSE_STATUS_ABNORMAL_CLOSE = 1006,
749 /**< 1006 is a reserved value and MUST NOT be set as a status code in a
750 Close control frame by an endpoint. It is designated for use in
751 applications expecting a status code to indicate that the
752 connection was closed abnormally, e.g., without sending or
753 receiving a Close control frame. */
754 LWS_CLOSE_STATUS_INVALID_PAYLOAD = 1007,
755 /**< 1007 indicates that an endpoint is terminating the connection
756 because it has received data within a message that was not
757 consistent with the type of the message (e.g., non-UTF-8 [RFC3629]
758 data within a text message). */
759 LWS_CLOSE_STATUS_POLICY_VIOLATION = 1008,
760 /**< 1008 indicates that an endpoint is terminating the connection
761 because it has received a message that violates its policy. This
762 is a generic status code that can be returned when there is no
763 other more suitable status code (e.g., 1003 or 1009) or if there
764 is a need to hide specific details about the policy. */
765 LWS_CLOSE_STATUS_MESSAGE_TOO_LARGE = 1009,
766 /**< 1009 indicates that an endpoint is terminating the connection
767 because it has received a message that is too big for it to
769 LWS_CLOSE_STATUS_EXTENSION_REQUIRED = 1010,
770 /**< 1010 indicates that an endpoint (client) is terminating the
771 connection because it has expected the server to negotiate one or
772 more extension, but the server didn't return them in the response
773 message of the WebSocket handshake. The list of extensions that
774 are needed SHOULD appear in the /reason/ part of the Close frame.
775 Note that this status code is not used by the server, because it
776 can fail the WebSocket handshake instead */
777 LWS_CLOSE_STATUS_UNEXPECTED_CONDITION = 1011,
778 /**< 1011 indicates that a server is terminating the connection because
779 it encountered an unexpected condition that prevented it from
780 fulfilling the request. */
781 LWS_CLOSE_STATUS_TLS_FAILURE = 1015,
782 /**< 1015 is a reserved value and MUST NOT be set as a status code in a
783 Close control frame by an endpoint. It is designated for use in
784 applications expecting a status code to indicate that the
785 connection was closed due to a failure to perform a TLS handshake
786 (e.g., the server certificate can't be verified). */
788 /****** add new things just above ---^ ******/
790 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY = 9999,
794 * lws_close_reason - Set reason and aux data to send with Close packet
795 * If you are going to return nonzero from the callback
796 * requesting the connection to close, you can optionally
797 * call this to set the reason the peer will be told if
800 * \param wsi: The websocket connection to set the close reason on
801 * \param status: A valid close status from websocket standard
802 * \param buf: NULL or buffer containing up to 124 bytes of auxiliary data
803 * \param len: Length of data in \param buf to send
805 LWS_VISIBLE LWS_EXTERN void
806 lws_close_reason(struct lws *wsi, enum lws_close_status status,
807 unsigned char *buf, size_t len);
813 /* needed even with extensions disabled for create context */
814 struct lws_extension;
816 /*! \defgroup usercb User Callback
818 * ##User protocol callback
820 * The protocol callback is the primary way lws interacts with
821 * user code. For one of a list of a few dozen reasons the callback gets
822 * called at some event to be handled.
824 * All of the events can be ignored, returning 0 is taken as "OK" and returning
825 * nonzero in most cases indicates that the connection should be closed.
831 * NOTE: These public enums are part of the abi. If you want to add one,
832 * add it at where specified so existing users are unaffected.
834 /** enum lws_callback_reasons - reason you're getting a protocol callback */
835 enum lws_callback_reasons {
836 LWS_CALLBACK_ESTABLISHED = 0,
837 /**< (VH) after the server completes a handshake with an incoming
838 * client. If you built the library with ssl support, in is a
839 * pointer to the ssl struct associated with the connection or NULL.*/
840 LWS_CALLBACK_CLIENT_CONNECTION_ERROR = 1,
841 /**< the request client connection has been unable to complete a
842 * handshake with the remote server. If in is non-NULL, you can
843 * find an error string of length len where it points to
845 * Diagnostic strings that may be returned include
847 * "getaddrinfo (ipv6) failed"
848 * "unknown address family"
849 * "getaddrinfo (ipv4) failed"
850 * "set socket opts failed"
851 * "insert wsi failed"
852 * "lws_ssl_client_connect1 failed"
853 * "lws_ssl_client_connect2 failed"
857 * "HS: Redirect code but no Location"
858 * "HS: URI did not parse"
859 * "HS: Redirect failed"
860 * "HS: Server did not return 200"
862 * "HS: disallowed by client filter"
863 * "HS: disallowed at ESTABLISHED"
864 * "HS: ACCEPT missing"
865 * "HS: ws upgrade response not 101"
866 * "HS: UPGRADE missing"
867 * "HS: Upgrade to something other than websocket"
868 * "HS: CONNECTION missing"
869 * "HS: UPGRADE malformed"
870 * "HS: PROTOCOL malformed"
871 * "HS: Cannot match protocol"
872 * "HS: EXT: list too big"
873 * "HS: EXT: failed setting defaults"
874 * "HS: EXT: failed parsing defaults"
875 * "HS: EXT: failed parsing options"
876 * "HS: EXT: Rejects server options"
877 * "HS: EXT: unknown ext"
878 * "HS: Accept hash wrong"
879 * "HS: Rejected by filter cb"
881 * "HS: SO_SNDBUF failed"
882 * "HS: Rejected at CLIENT_ESTABLISHED"
884 LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH = 2,
885 /**< this is the last chance for the client user code to examine the
886 * http headers and decide to reject the connection. If the
887 * content in the headers is interesting to the
888 * client (url, etc) it needs to copy it out at
889 * this point since it will be destroyed before
890 * the CLIENT_ESTABLISHED call */
891 LWS_CALLBACK_CLIENT_ESTABLISHED = 3,
892 /**< after your client connection completed
893 * a handshake with the remote server */
894 LWS_CALLBACK_CLOSED = 4,
895 /**< when the websocket session ends */
896 LWS_CALLBACK_CLOSED_HTTP = 5,
897 /**< when a HTTP (non-websocket) session ends */
898 LWS_CALLBACK_RECEIVE = 6,
899 /**< data has appeared for this server endpoint from a
900 * remote client, it can be found at *in and is
902 LWS_CALLBACK_RECEIVE_PONG = 7,
903 /**< servers receive PONG packets with this callback reason */
904 LWS_CALLBACK_CLIENT_RECEIVE = 8,
905 /**< data has appeared from the server for the client connection, it
906 * can be found at *in and is len bytes long */
907 LWS_CALLBACK_CLIENT_RECEIVE_PONG = 9,
908 /**< clients receive PONG packets with this callback reason */
909 LWS_CALLBACK_CLIENT_WRITEABLE = 10,
910 /**< If you call lws_callback_on_writable() on a connection, you will
911 * get one of these callbacks coming when the connection socket
912 * is able to accept another write packet without blocking.
913 * If it already was able to take another packet without blocking,
914 * you'll get this callback at the next call to the service loop
915 * function. Notice that CLIENTs get LWS_CALLBACK_CLIENT_WRITEABLE
916 * and servers get LWS_CALLBACK_SERVER_WRITEABLE. */
917 LWS_CALLBACK_SERVER_WRITEABLE = 11,
918 /**< See LWS_CALLBACK_CLIENT_WRITEABLE */
919 LWS_CALLBACK_HTTP = 12,
920 /**< an http request has come from a client that is not
921 * asking to upgrade the connection to a websocket
922 * one. This is a chance to serve http content,
923 * for example, to send a script to the client
924 * which will then open the websockets connection.
925 * in points to the URI path requested and
926 * lws_serve_http_file() makes it very
927 * simple to send back a file to the client.
928 * Normally after sending the file you are done
929 * with the http connection, since the rest of the
930 * activity will come by websockets from the script
931 * that was delivered by http, so you will want to
932 * return 1; to close and free up the connection. */
933 LWS_CALLBACK_HTTP_BODY = 13,
934 /**< the next len bytes data from the http
935 * request body HTTP connection is now available in in. */
936 LWS_CALLBACK_HTTP_BODY_COMPLETION = 14,
937 /**< the expected amount of http request body has been delivered */
938 LWS_CALLBACK_HTTP_FILE_COMPLETION = 15,
939 /**< a file requested to be sent down http link has completed. */
940 LWS_CALLBACK_HTTP_WRITEABLE = 16,
941 /**< you can write more down the http protocol link now. */
942 LWS_CALLBACK_FILTER_NETWORK_CONNECTION = 17,
943 /**< called when a client connects to
944 * the server at network level; the connection is accepted but then
945 * passed to this callback to decide whether to hang up immediately
946 * or not, based on the client IP. in contains the connection
947 * socket's descriptor. Since the client connection information is
948 * not available yet, wsi still pointing to the main server socket.
949 * Return non-zero to terminate the connection before sending or
950 * receiving anything. Because this happens immediately after the
951 * network connection from the client, there's no websocket protocol
952 * selected yet so this callback is issued only to protocol 0. */
953 LWS_CALLBACK_FILTER_HTTP_CONNECTION = 18,
954 /**< called when the request has
955 * been received and parsed from the client, but the response is
956 * not sent yet. Return non-zero to disallow the connection.
957 * user is a pointer to the connection user space allocation,
958 * in is the URI, eg, "/"
959 * In your handler you can use the public APIs
960 * lws_hdr_total_length() / lws_hdr_copy() to access all of the
961 * headers using the header enums lws_token_indexes from
962 * libwebsockets.h to check for and read the supported header
963 * presence and content before deciding to allow the http
964 * connection to proceed or to kill the connection. */
965 LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED = 19,
966 /**< A new client just had
967 * been connected, accepted, and instantiated into the pool. This
968 * callback allows setting any relevant property to it. Because this
969 * happens immediately after the instantiation of a new client,
970 * there's no websocket protocol selected yet so this callback is
971 * issued only to protocol 0. Only wsi is defined, pointing to the
972 * new client, and the return value is ignored. */
973 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION = 20,
974 /**< called when the handshake has
975 * been received and parsed from the client, but the response is
976 * not sent yet. Return non-zero to disallow the connection.
977 * user is a pointer to the connection user space allocation,
978 * in is the requested protocol name
979 * In your handler you can use the public APIs
980 * lws_hdr_total_length() / lws_hdr_copy() to access all of the
981 * headers using the header enums lws_token_indexes from
982 * libwebsockets.h to check for and read the supported header
983 * presence and content before deciding to allow the handshake
984 * to proceed or to kill the connection. */
985 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS = 21,
986 /**< if configured for
987 * including OpenSSL support, this callback allows your user code
988 * to perform extra SSL_CTX_load_verify_locations() or similar
989 * calls to direct OpenSSL where to find certificates the client
990 * can use to confirm the remote server identity. user is the
991 * OpenSSL SSL_CTX* */
992 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS = 22,
993 /**< if configured for
994 * including OpenSSL support, this callback allows your user code
995 * to load extra certifcates into the server which allow it to
996 * verify the validity of certificates returned by clients. user
997 * is the server's OpenSSL SSL_CTX* */
998 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION = 23,
999 /**< if the libwebsockets vhost was created with the option
1000 * LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT, then this
1001 * callback is generated during OpenSSL verification of the cert
1002 * sent from the client. It is sent to protocol[0] callback as
1003 * no protocol has been negotiated on the connection yet.
1004 * Notice that the libwebsockets context and wsi are both NULL
1005 * during this callback. See
1006 * http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html
1007 * to understand more detail about the OpenSSL callback that
1008 * generates this libwebsockets callback and the meanings of the
1009 * arguments passed. In this callback, user is the x509_ctx,
1010 * in is the ssl pointer and len is preverify_ok
1011 * Notice that this callback maintains libwebsocket return
1012 * conventions, return 0 to mean the cert is OK or 1 to fail it.
1013 * This also means that if you don't handle this callback then
1014 * the default callback action of returning 0 allows the client
1016 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER = 24,
1017 /**< this callback happens
1018 * when a client handshake is being compiled. user is NULL,
1019 * in is a char **, it's pointing to a char * which holds the
1020 * next location in the header buffer where you can add
1021 * headers, and len is the remaining space in the header buffer,
1022 * which is typically some hundreds of bytes. So, to add a canned
1023 * cookie, your handler code might look similar to:
1025 * char **p = (char **)in;
1030 * *p += sprintf(*p, "Cookie: a=b\x0d\x0a");
1034 * Notice if you add anything, you just have to take care about
1035 * the CRLF on the line you added. Obviously this callback is
1036 * optional, if you don't handle it everything is fine.
1038 * Notice the callback is coming to protocols[0] all the time,
1039 * because there is no specific protocol negotiated yet. */
1040 LWS_CALLBACK_CONFIRM_EXTENSION_OKAY = 25,
1041 /**< When the server handshake code
1042 * sees that it does support a requested extension, before
1043 * accepting the extension by additing to the list sent back to
1044 * the client it gives this callback just to check that it's okay
1045 * to use that extension. It calls back to the requested protocol
1046 * and with in being the extension name, len is 0 and user is
1047 * valid. Note though at this time the ESTABLISHED callback hasn't
1048 * happened yet so if you initialize user content there, user
1049 * content during this callback might not be useful for anything. */
1050 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED = 26,
1052 * connection is being prepared to start a handshake to a server,
1053 * each supported extension is checked with protocols[0] callback
1054 * with this reason, giving the user code a chance to suppress the
1055 * claim to support that extension by returning non-zero. If
1056 * unhandled, by default 0 will be returned and the extension
1057 * support included in the header to the server. Notice this
1058 * callback comes to protocols[0]. */
1059 LWS_CALLBACK_PROTOCOL_INIT = 27,
1060 /**< One-time call per protocol, per-vhost using it, so it can
1061 * do initial setup / allocations etc */
1062 LWS_CALLBACK_PROTOCOL_DESTROY = 28,
1063 /**< One-time call per protocol, per-vhost using it, indicating
1064 * this protocol won't get used at all after this callback, the
1065 * vhost is getting destroyed. Take the opportunity to
1066 * deallocate everything that was allocated by the protocol. */
1067 LWS_CALLBACK_WSI_CREATE = 29,
1068 /**< outermost (earliest) wsi create notification to protocols[0] */
1069 LWS_CALLBACK_WSI_DESTROY = 30,
1070 /**< outermost (latest) wsi destroy notification to protocols[0] */
1071 LWS_CALLBACK_GET_THREAD_ID = 31,
1072 /**< lws can accept callback when writable requests from other
1073 * threads, if you implement this callback and return an opaque
1074 * current thread ID integer. */
1076 /* external poll() management support */
1077 LWS_CALLBACK_ADD_POLL_FD = 32,
1078 /**< lws normally deals with its poll() or other event loop
1079 * internally, but in the case you are integrating with another
1080 * server you will need to have lws sockets share a
1081 * polling array with the other server. This and the other
1082 * POLL_FD related callbacks let you put your specialized
1083 * poll array interface code in the callback for protocol 0, the
1084 * first protocol you support, usually the HTTP protocol in the
1086 * This callback happens when a socket needs to be
1087 * added to the polling loop: in points to a struct
1088 * lws_pollargs; the fd member of the struct is the file
1089 * descriptor, and events contains the active events
1091 * If you are using the internal lws polling / event loop
1092 * you can just ignore these callbacks. */
1093 LWS_CALLBACK_DEL_POLL_FD = 33,
1094 /**< This callback happens when a socket descriptor
1095 * needs to be removed from an external polling array. in is
1096 * again the struct lws_pollargs containing the fd member
1097 * to be removed. If you are using the internal polling
1098 * loop, you can just ignore it. */
1099 LWS_CALLBACK_CHANGE_MODE_POLL_FD = 34,
1100 /**< This callback happens when lws wants to modify the events for
1102 * in is the struct lws_pollargs with the fd to change.
1103 * The new event mask is in events member and the old mask is in
1104 * the prev_events member.
1105 * If you are using the internal polling loop, you can just ignore
1107 LWS_CALLBACK_LOCK_POLL = 35,
1108 /**< These allow the external poll changes driven
1109 * by lws to participate in an external thread locking
1110 * scheme around the changes, so the whole thing is threadsafe.
1111 * These are called around three activities in the library,
1112 * - inserting a new wsi in the wsi / fd table (len=1)
1113 * - deleting a wsi from the wsi / fd table (len=1)
1114 * - changing a wsi's POLLIN/OUT state (len=0)
1115 * Locking and unlocking external synchronization objects when
1116 * len == 1 allows external threads to be synchronized against
1117 * wsi lifecycle changes if it acquires the same lock for the
1118 * duration of wsi dereference from the other thread context. */
1119 LWS_CALLBACK_UNLOCK_POLL = 36,
1120 /**< See LWS_CALLBACK_LOCK_POLL, ignore if using lws internal poll */
1122 LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY = 37,
1123 /**< if configured for including OpenSSL support but no private key
1124 * file has been specified (ssl_private_key_filepath is NULL), this is
1125 * called to allow the user to set the private key directly via
1126 * libopenssl and perform further operations if required; this might be
1127 * useful in situations where the private key is not directly accessible
1128 * by the OS, for example if it is stored on a smartcard.
1129 * user is the server's OpenSSL SSL_CTX* */
1130 LWS_CALLBACK_WS_PEER_INITIATED_CLOSE = 38,
1131 /**< The peer has sent an unsolicited Close WS packet. in and
1132 * len are the optional close code (first 2 bytes, network
1133 * order) and the optional additional information which is not
1134 * defined in the standard, and may be a string or non-human- readable data.
1135 * If you return 0 lws will echo the close and then close the
1136 * connection. If you return nonzero lws will just close the
1139 LWS_CALLBACK_WS_EXT_DEFAULTS = 39,
1142 LWS_CALLBACK_CGI = 40,
1144 LWS_CALLBACK_CGI_TERMINATED = 41,
1146 LWS_CALLBACK_CGI_STDIN_DATA = 42,
1148 LWS_CALLBACK_CGI_STDIN_COMPLETED = 43,
1150 LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP = 44,
1152 LWS_CALLBACK_CLOSED_CLIENT_HTTP = 45,
1154 LWS_CALLBACK_RECEIVE_CLIENT_HTTP = 46,
1156 LWS_CALLBACK_COMPLETED_CLIENT_HTTP = 47,
1158 LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ = 48,
1160 LWS_CALLBACK_HTTP_BIND_PROTOCOL = 49,
1162 LWS_CALLBACK_HTTP_DROP_PROTOCOL = 50,
1164 LWS_CALLBACK_CHECK_ACCESS_RIGHTS = 51,
1166 LWS_CALLBACK_PROCESS_HTML = 52,
1168 LWS_CALLBACK_ADD_HEADERS = 53,
1170 LWS_CALLBACK_SESSION_INFO = 54,
1173 LWS_CALLBACK_GS_EVENT = 55,
1175 LWS_CALLBACK_HTTP_PMO = 56,
1176 /**< per-mount options for this connection, called before
1177 * the normal LWS_CALLBACK_HTTP when the mount has per-mount
1180 LWS_CALLBACK_CLIENT_HTTP_WRITEABLE = 57,
1181 /**< when doing an HTTP type client connection, you can call
1182 * lws_client_http_body_pending(wsi, 1) from
1183 * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER to get these callbacks
1184 * sending the HTTP headers.
1186 * From this callback, when you have sent everything, you should let
1187 * lws know by calling lws_client_http_body_pending(wsi, 0)
1189 LWS_CALLBACK_OPENSSL_PERFORM_SERVER_CERT_VERIFICATION = 58,
1190 /**< Similar to LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION
1191 * this callback is called during OpenSSL verification of the cert
1192 * sent from the server to the client. It is sent to protocol[0]
1193 * callback as no protocol has been negotiated on the connection yet.
1194 * Notice that the wsi is set because lws_client_connect_via_info was
1197 * See http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html
1198 * to understand more detail about the OpenSSL callback that
1199 * generates this libwebsockets callback and the meanings of the
1200 * arguments passed. In this callback, user is the x509_ctx,
1201 * in is the ssl pointer and len is preverify_ok.
1203 * THIS IS NOT RECOMMENDED BUT if a cert validation error shall be
1204 * overruled and cert shall be accepted as ok,
1205 * X509_STORE_CTX_set_error((X509_STORE_CTX*)user, X509_V_OK); must be
1206 * called and return value must be 0 to mean the cert is OK;
1207 * returning 1 will fail the cert in any case.
1209 * This also means that if you don't handle this callback then
1210 * the default callback action of returning 0 will not accept the
1211 * certificate in case of a validation error decided by the SSL lib.
1213 * This is expected and secure behaviour when validating certificates.
1215 * Note: LCCSCF_ALLOW_SELFSIGNED and
1216 * LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK still work without this
1217 * callback being implemented.
1219 LWS_CALLBACK_RAW_RX = 59,
1220 /**< RAW mode connection RX */
1221 LWS_CALLBACK_RAW_CLOSE = 60,
1222 /**< RAW mode connection is closing */
1223 LWS_CALLBACK_RAW_WRITEABLE = 61,
1224 /**< RAW mode connection may be written */
1225 LWS_CALLBACK_RAW_ADOPT = 62,
1226 /**< RAW mode connection was adopted (equivalent to 'wsi created') */
1227 LWS_CALLBACK_RAW_ADOPT_FILE = 63,
1228 /**< RAW mode file was adopted (equivalent to 'wsi created') */
1229 LWS_CALLBACK_RAW_RX_FILE = 64,
1230 /**< RAW mode file has something to read */
1231 LWS_CALLBACK_RAW_WRITEABLE_FILE = 65,
1232 /**< RAW mode file is writeable */
1233 LWS_CALLBACK_RAW_CLOSE_FILE = 66,
1234 /**< RAW mode wsi that adopted a file is closing */
1236 /****** add new things just above ---^ ******/
1238 LWS_CALLBACK_USER = 1000,
1239 /**< user code can use any including above without fear of clashes */
1245 * typedef lws_callback_function() - User server actions
1246 * \param wsi: Opaque websocket instance pointer
1247 * \param reason: The reason for the call
1248 * \param user: Pointer to per-session user data allocated by library
1249 * \param in: Pointer used for some callback reasons
1250 * \param len: Length set for some callback reasons
1252 * This callback is the way the user controls what is served. All the
1253 * protocol detail is hidden and handled by the library.
1255 * For each connection / session there is user data allocated that is
1256 * pointed to by "user". You set the size of this user data area when
1257 * the library is initialized with lws_create_server.
1260 lws_callback_function(struct lws *wsi, enum lws_callback_reasons reason,
1261 void *user, void *in, size_t len);
1264 /*! \defgroup extensions
1266 * ##Extension releated functions
1268 * Ws defines optional extensions, lws provides the ability to implement these
1269 * in user code if so desired.
1271 * We provide one extensions permessage-deflate.
1276 * NOTE: These public enums are part of the abi. If you want to add one,
1277 * add it at where specified so existing users are unaffected.
1279 enum lws_extension_callback_reasons {
1280 LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT = 0,
1281 LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT = 1,
1282 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT = 2,
1283 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT = 3,
1284 LWS_EXT_CB_CONSTRUCT = 4,
1285 LWS_EXT_CB_CLIENT_CONSTRUCT = 5,
1286 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE = 6,
1287 LWS_EXT_CB_CHECK_OK_TO_PROPOSE_EXTENSION = 7,
1288 LWS_EXT_CB_DESTROY = 8,
1289 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING = 9,
1290 LWS_EXT_CB_ANY_WSI_ESTABLISHED = 10,
1291 LWS_EXT_CB_PACKET_RX_PREPARSE = 11,
1292 LWS_EXT_CB_PACKET_TX_PRESEND = 12,
1293 LWS_EXT_CB_PACKET_TX_DO_SEND = 13,
1294 LWS_EXT_CB_HANDSHAKE_REPLY_TX = 14,
1295 LWS_EXT_CB_FLUSH_PENDING_TX = 15,
1296 LWS_EXT_CB_EXTENDED_PAYLOAD_RX = 16,
1297 LWS_EXT_CB_CAN_PROXY_CLIENT_CONNECTION = 17,
1298 LWS_EXT_CB_1HZ = 18,
1299 LWS_EXT_CB_REQUEST_ON_WRITEABLE = 19,
1300 LWS_EXT_CB_IS_WRITEABLE = 20,
1301 LWS_EXT_CB_PAYLOAD_TX = 21,
1302 LWS_EXT_CB_PAYLOAD_RX = 22,
1303 LWS_EXT_CB_OPTION_DEFAULT = 23,
1304 LWS_EXT_CB_OPTION_SET = 24,
1305 LWS_EXT_CB_OPTION_CONFIRM = 25,
1306 LWS_EXT_CB_NAMED_OPTION_SET = 26,
1308 /****** add new things just above ---^ ******/
1311 /** enum lws_ext_options_types */
1312 enum lws_ext_options_types {
1313 EXTARG_NONE, /**< does not take an argument */
1314 EXTARG_DEC, /**< requires a decimal argument */
1315 EXTARG_OPT_DEC /**< may have an optional decimal argument */
1317 /* Add new things just above here ---^
1318 * This is part of the ABI, don't needlessly break compatibility */
1321 /** struct lws_ext_options - Option arguments to the extension. These are
1322 * used in the negotiation at ws upgrade time.
1323 * The helper function lws_ext_parse_options()
1324 * uses these to generate callbacks */
1325 struct lws_ext_options {
1326 const char *name; /**< Option name, eg, "server_no_context_takeover" */
1327 enum lws_ext_options_types type; /**< What kind of args the option can take */
1329 /* Add new things just above here ---^
1330 * This is part of the ABI, don't needlessly break compatibility */
1333 /** struct lws_ext_option_arg */
1334 struct lws_ext_option_arg {
1335 const char *option_name; /**< may be NULL, option_index used then */
1336 int option_index; /**< argument ordinal to use if option_name missing */
1337 const char *start; /**< value */
1338 int len; /**< length of value */
1342 * typedef lws_extension_callback_function() - Hooks to allow extensions to operate
1343 * \param context: Websockets context
1344 * \param ext: This extension
1345 * \param wsi: Opaque websocket instance pointer
1346 * \param reason: The reason for the call
1347 * \param user: Pointer to ptr to per-session user data allocated by library
1348 * \param in: Pointer used for some callback reasons
1349 * \param len: Length set for some callback reasons
1351 * Each extension that is active on a particular connection receives
1352 * callbacks during the connection lifetime to allow the extension to
1353 * operate on websocket data and manage itself.
1355 * Libwebsockets takes care of allocating and freeing "user" memory for
1356 * each active extension on each connection. That is what is pointed to
1357 * by the user parameter.
1359 * LWS_EXT_CB_CONSTRUCT: called when the server has decided to
1360 * select this extension from the list provided by the client,
1361 * just before the server will send back the handshake accepting
1362 * the connection with this extension active. This gives the
1363 * extension a chance to initialize its connection context found
1366 * LWS_EXT_CB_CLIENT_CONSTRUCT: same as LWS_EXT_CB_CONSTRUCT
1367 * but called when client is instantiating this extension. Some
1368 * extensions will work the same on client and server side and then
1369 * you can just merge handlers for both CONSTRUCTS.
1371 * LWS_EXT_CB_DESTROY: called when the connection the extension was
1372 * being used on is about to be closed and deallocated. It's the
1373 * last chance for the extension to deallocate anything it has
1374 * allocated in the user data (pointed to by user) before the
1375 * user data is deleted. This same callback is used whether you
1376 * are in client or server instantiation context.
1378 * LWS_EXT_CB_PACKET_RX_PREPARSE: when this extension was active on
1379 * a connection, and a packet of data arrived at the connection,
1380 * it is passed to this callback to give the extension a chance to
1381 * change the data, eg, decompress it. user is pointing to the
1382 * extension's private connection context data, in is pointing
1383 * to an lws_tokens struct, it consists of a char * pointer called
1384 * token, and an int called token_len. At entry, these are
1385 * set to point to the received buffer and set to the content
1386 * length. If the extension will grow the content, it should use
1387 * a new buffer allocated in its private user context data and
1388 * set the pointed-to lws_tokens members to point to its buffer.
1390 * LWS_EXT_CB_PACKET_TX_PRESEND: this works the same way as
1391 * LWS_EXT_CB_PACKET_RX_PREPARSE above, except it gives the
1392 * extension a chance to change websocket data just before it will
1393 * be sent out. Using the same lws_token pointer scheme in in,
1394 * the extension can change the buffer and the length to be
1395 * transmitted how it likes. Again if it wants to grow the
1396 * buffer safely, it should copy the data into its own buffer and
1397 * set the lws_tokens token pointer to it.
1399 * LWS_EXT_CB_ARGS_VALIDATE:
1402 lws_extension_callback_function(struct lws_context *context,
1403 const struct lws_extension *ext, struct lws *wsi,
1404 enum lws_extension_callback_reasons reason,
1405 void *user, void *in, size_t len);
1407 /** struct lws_extension - An extension we support */
1408 struct lws_extension {
1409 const char *name; /**< Formal extension name, eg, "permessage-deflate" */
1410 lws_extension_callback_function *callback; /**< Service callback */
1411 const char *client_offer; /**< String containing exts and options client offers */
1413 /* Add new things just above here ---^
1414 * This is part of the ABI, don't needlessly break compatibility */
1418 * lws_set_extension_option(): set extension option if possible
1420 * \param wsi: websocket connection
1421 * \param ext_name: name of ext, like "permessage-deflate"
1422 * \param opt_name: name of option, like "rx_buf_size"
1423 * \param opt_val: value to set option to
1425 LWS_VISIBLE LWS_EXTERN int
1426 lws_set_extension_option(struct lws *wsi, const char *ext_name,
1427 const char *opt_name, const char *opt_val);
1429 #ifndef LWS_NO_EXTENSIONS
1430 /* lws_get_internal_extensions() - DEPRECATED
1432 * \Deprecated There is no longer a set internal extensions table. The table is provided
1433 * by user code along with application-specific settings. See the test
1434 * client and server for how to do.
1436 static LWS_INLINE LWS_WARN_DEPRECATED const struct lws_extension *
1437 lws_get_internal_extensions(void) { return NULL; }
1440 * lws_ext_parse_options() - deal with parsing negotiated extension options
1442 * \param ext: related extension struct
1443 * \param wsi: websocket connection
1444 * \param ext_user: per-connection extension private data
1445 * \param opts: list of supported options
1446 * \param o: option string to parse
1447 * \param len: length
1449 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
1450 lws_ext_parse_options(const struct lws_extension *ext, struct lws *wsi,
1451 void *ext_user, const struct lws_ext_options *opts,
1452 const char *o, int len);
1455 /** lws_extension_callback_pm_deflate() - extension for RFC7692
1457 * \param context: lws context
1458 * \param ext: related lws_extension struct
1459 * \param wsi: websocket connection
1460 * \param reason: incoming callback reason
1461 * \param user: per-connection extension private data
1462 * \param in: pointer parameter
1463 * \param len: length parameter
1465 * Built-in callback implementing RFC7692 permessage-deflate
1468 int lws_extension_callback_pm_deflate(
1469 struct lws_context *context, const struct lws_extension *ext,
1470 struct lws *wsi, enum lws_extension_callback_reasons reason,
1471 void *user, void *in, size_t len);
1474 * The internal exts are part of the public abi
1475 * If we add more extensions, publish the callback here ------v
1479 /*! \defgroup Protocols-and-Plugins Protocols and Plugins
1482 * ##Protocol and protocol plugin -related apis
1484 * Protocols bind ws protocol names to a custom callback specific to that
1485 * protocol implementaion.
1487 * A list of protocols can be passed in at context creation time, but it is
1488 * also legal to leave that NULL and add the protocols and their callback code
1491 * Plugins are much preferable compared to cut and pasting code into an
1492 * application each time, since they can be used standalone.
1495 /** struct lws_protocols - List of protocols and handlers client or server
1498 struct lws_protocols {
1500 /**< Protocol name that must match the one given in the client
1501 * Javascript new WebSocket(url, 'protocol') name. */
1502 lws_callback_function *callback;
1503 /**< The service callback used for this protocol. It allows the
1504 * service action for an entire protocol to be encapsulated in
1505 * the protocol-specific callback */
1506 size_t per_session_data_size;
1507 /**< Each new connection using this protocol gets
1508 * this much memory allocated on connection establishment and
1509 * freed on connection takedown. A pointer to this per-connection
1510 * allocation is passed into the callback in the 'user' parameter */
1511 size_t rx_buffer_size;
1512 /**< lws allocates this much space for rx data and informs callback
1513 * when something came. Due to rx flow control, the callback may not
1514 * be able to consume it all without having to return to the event
1515 * loop. That is supported in lws.
1517 * If .tx_packet_size is 0, this also controls how much may be sent at once
1518 * for backwards compatibility.
1521 /**< ignored by lws, but useful to contain user information bound
1522 * to the selected protocol. For example if this protocol was
1523 * called "myprotocol-v2", you might set id to 2, and the user
1524 * code that acts differently according to the version can do so by
1525 * switch (wsi->protocol->id), user code might use some bits as
1526 * capability flags based on selected protocol version, etc. */
1527 void *user; /**< ignored by lws, but user code can pass a pointer
1528 here it can later access from the protocol callback */
1529 size_t tx_packet_size;
1530 /**< 0 indicates restrict send() size to .rx_buffer_size for backwards-
1532 * If greater than zero, a single send() is restricted to this amount
1533 * and any remainder is buffered by lws and sent afterwards also in
1534 * these size chunks. Since that is expensive, it's preferable
1535 * to restrict one fragment you are trying to send to match this
1539 /* Add new things just above here ---^
1540 * This is part of the ABI, don't needlessly break compatibility */
1546 * lws_vhost_name_to_protocol() - get vhost's protocol object from its name
1548 * \param vh: vhost to search
1549 * \param name: protocol name
1551 * Returns NULL or a pointer to the vhost's protocol of the requested name
1553 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1554 lws_vhost_name_to_protocol(struct lws_vhost *vh, const char *name);
1557 * lws_get_protocol() - Returns a protocol pointer from a websocket
1559 * \param wsi: pointer to struct websocket you want to know the protocol of
1562 * Some apis can act on all live connections of a given protocol,
1563 * this is how you can get a pointer to the active protocol if needed.
1565 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1566 lws_get_protocol(struct lws *wsi);
1568 /** lws_protocol_get() - deprecated: use lws_get_protocol */
1569 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1570 lws_protocol_get(struct lws *wsi) LWS_WARN_DEPRECATED;
1573 * lws_protocol_vh_priv_zalloc() - Allocate and zero down a protocol's per-vhost
1575 * \param vhost: vhost the instance is related to
1576 * \param prot: protocol the instance is related to
1577 * \param size: bytes to allocate
1579 * Protocols often find it useful to allocate a per-vhost struct, this is a
1580 * helper to be called in the per-vhost init LWS_CALLBACK_PROTOCOL_INIT
1582 LWS_VISIBLE LWS_EXTERN void *
1583 lws_protocol_vh_priv_zalloc(struct lws_vhost *vhost, const struct lws_protocols *prot,
1587 * lws_protocol_vh_priv_get() - retreive a protocol's per-vhost storage
1589 * \param vhost: vhost the instance is related to
1590 * \param prot: protocol the instance is related to
1592 * Recover a pointer to the allocated per-vhost storage for the protocol created
1593 * by lws_protocol_vh_priv_zalloc() earlier
1595 LWS_VISIBLE LWS_EXTERN void *
1596 lws_protocol_vh_priv_get(struct lws_vhost *vhost, const struct lws_protocols *prot);
1599 * lws_finalize_startup() - drop initial process privileges
1601 * \param context: lws context
1603 * This is called after the end of the vhost protocol initializations, but
1604 * you may choose to call it earlier
1606 LWS_VISIBLE LWS_EXTERN int
1607 lws_finalize_startup(struct lws_context *context);
1609 LWS_VISIBLE LWS_EXTERN int
1610 lws_protocol_init(struct lws_context *context);
1612 #ifdef LWS_WITH_PLUGINS
1614 /* PLUGINS implies LIBUV */
1616 #define LWS_PLUGIN_API_MAGIC 180
1618 /** struct lws_plugin_capability - how a plugin introduces itself to lws */
1619 struct lws_plugin_capability {
1620 unsigned int api_magic; /**< caller fills this in, plugin fills rest */
1621 const struct lws_protocols *protocols; /**< array of supported protocols provided by plugin */
1622 int count_protocols; /**< how many protocols */
1623 const struct lws_extension *extensions; /**< array of extensions provided by plugin */
1624 int count_extensions; /**< how many extensions */
1627 typedef int (*lws_plugin_init_func)(struct lws_context *,
1628 struct lws_plugin_capability *);
1629 typedef int (*lws_plugin_destroy_func)(struct lws_context *);
1631 /** struct lws_plugin */
1633 struct lws_plugin *list; /**< linked list */
1634 #if (UV_VERSION_MAJOR > 0)
1635 uv_lib_t lib; /**< shared library pointer */
1637 void *l; /**< so we can compile on ancient libuv */
1639 char name[64]; /**< name of the plugin */
1640 struct lws_plugin_capability caps; /**< plugin capabilities */
1648 /*! \defgroup generic-sessions plugin: generic-sessions
1649 * \ingroup Protocols-and-Plugins
1651 * ##Plugin Generic-sessions related
1653 * generic-sessions plugin provides a reusable, generic session and login /
1654 * register / forgot password framework including email verification.
1658 #define LWSGS_EMAIL_CONTENT_SIZE 16384
1659 /**< Maximum size of email we might send */
1661 /* SHA-1 binary and hexified versions */
1662 /** typedef struct lwsgw_hash_bin */
1663 typedef struct { unsigned char bin[20]; /**< binary representation of hash */} lwsgw_hash_bin;
1664 /** typedef struct lwsgw_hash */
1665 typedef struct { char id[41]; /**< ascii hex representation of hash */ } lwsgw_hash;
1667 /** enum lwsgs_auth_bits */
1668 enum lwsgs_auth_bits {
1669 LWSGS_AUTH_LOGGED_IN = 1, /**< user is logged in as somebody */
1670 LWSGS_AUTH_ADMIN = 2, /**< logged in as the admin user */
1671 LWSGS_AUTH_VERIFIED = 4, /**< user has verified his email */
1672 LWSGS_AUTH_FORGOT_FLOW = 8, /**< he just completed "forgot password" flow */
1675 /** struct lws_session_info - information about user session status */
1676 struct lws_session_info {
1677 char username[32]; /**< username logged in as, or empty string */
1678 char email[100]; /**< email address associated with login, or empty string */
1679 char ip[72]; /**< ip address session was started from */
1680 unsigned int mask; /**< access rights mask associated with session
1681 * see enum lwsgs_auth_bits */
1682 char session[42]; /**< session id string, usable as opaque uid when not logged in */
1685 /** enum lws_gs_event */
1687 LWSGSE_CREATED, /**< a new user was created */
1688 LWSGSE_DELETED /**< an existing user was deleted */
1691 /** struct lws_gs_event_args */
1692 struct lws_gs_event_args {
1693 enum lws_gs_event event; /**< which event happened */
1694 const char *username; /**< which username the event happened to */
1695 const char *email; /**< the email address of that user */
1701 /*! \defgroup context-and-vhost
1704 * ##Context and Vhost releated functions
1706 * LWS requires that there is one context, in which you may define multiple
1707 * vhosts. Each vhost is a virtual host, with either its own listen port
1708 * or sharing an existing one. Each vhost has its own SSL context that can
1709 * be set up individually or left disabled.
1711 * If you don't care about multiple "site" support, you can ignore it and
1712 * lws will create a single default vhost at context creation time.
1717 * NOTE: These public enums are part of the abi. If you want to add one,
1718 * add it at where specified so existing users are unaffected.
1721 /** enum lws_context_options - context and vhost options */
1722 enum lws_context_options {
1723 LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT = (1 << 1) |
1725 /**< (VH) Don't allow the connection unless the client has a
1726 * client cert that we recognize; provides
1727 * LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT */
1728 LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME = (1 << 2),
1729 /**< (CTX) Don't try to get the server's hostname */
1730 LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT = (1 << 3) |
1732 /**< (VH) Allow non-SSL (plaintext) connections on the same
1733 * port as SSL is listening... undermines the security of SSL;
1734 * provides LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT */
1735 LWS_SERVER_OPTION_LIBEV = (1 << 4),
1736 /**< (CTX) Use libev event loop */
1737 LWS_SERVER_OPTION_DISABLE_IPV6 = (1 << 5),
1738 /**< (VH) Disable IPV6 support */
1739 LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS = (1 << 6),
1740 /**< (VH) Don't load OS CA certs, you will need to load your
1742 LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED = (1 << 7),
1743 /**< (VH) Accept connections with no valid Cert (eg, selfsigned) */
1744 LWS_SERVER_OPTION_VALIDATE_UTF8 = (1 << 8),
1745 /**< (VH) Check UT-8 correctness */
1746 LWS_SERVER_OPTION_SSL_ECDH = (1 << 9) |
1748 /**< (VH) initialize ECDH ciphers */
1749 LWS_SERVER_OPTION_LIBUV = (1 << 10),
1750 /**< (CTX) Use libuv event loop */
1751 LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS = (1 << 11) |
1753 /**< (VH) Use http redirect to force http to https
1754 * (deprecated: use mount redirection) */
1755 LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT = (1 << 12),
1756 /**< (CTX) Initialize the SSL library at all */
1757 LWS_SERVER_OPTION_EXPLICIT_VHOSTS = (1 << 13),
1758 /**< (CTX) Only create the context when calling context
1759 * create api, implies user code will create its own vhosts */
1760 LWS_SERVER_OPTION_UNIX_SOCK = (1 << 14),
1761 /**< (VH) Use Unix socket */
1762 LWS_SERVER_OPTION_STS = (1 << 15),
1763 /**< (VH) Send Strict Transport Security header, making
1764 * clients subsequently go to https even if user asked for http */
1765 LWS_SERVER_OPTION_IPV6_V6ONLY_MODIFY = (1 << 16),
1766 /**< (VH) Enable LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE to take effect */
1767 LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE = (1 << 17),
1768 /**< (VH) if set, only ipv6 allowed on the vhost */
1769 LWS_SERVER_OPTION_UV_NO_SIGSEGV_SIGFPE_SPIN = (1 << 18),
1770 /**< (CTX) Libuv only: Do not spin on SIGSEGV / SIGFPE. A segfault
1771 * normally makes the lib spin so you can attach a debugger to it
1772 * even if it happened without a debugger in place. You can disable
1773 * that by giving this option.
1775 LWS_SERVER_OPTION_JUST_USE_RAW_ORIGIN = (1 << 19),
1776 /**< For backwards-compatibility reasons, by default
1777 * lws prepends "http://" to the origin you give in the client
1778 * connection info struct. If you give this flag when you create
1779 * the context, only the string you give in the client connect
1780 * info for .origin (if any) will be used directly.
1782 LWS_SERVER_OPTION_FALLBACK_TO_RAW = (1 << 20),
1783 /**< (VH) if invalid http is coming in the first line, */
1784 LWS_SERVER_OPTION_LIBEVENT = (1 << 21),
1785 /**< (CTX) Use libevent event loop */
1786 LWS_SERVER_OPTION_ONLY_RAW = (1 << 22),
1787 /**< (VH) All connections to this vhost / port are RAW as soon as
1788 * the connection is accepted, no HTTP is going to be coming.
1791 /****** add new things just above ---^ ******/
1794 #define lws_check_opt(c, f) (((c) & (f)) == (f))
1796 struct lws_plat_file_ops;
1798 /** struct lws_context_creation_info - parameters to create context and /or vhost with
1800 * This is also used to create vhosts.... if LWS_SERVER_OPTION_EXPLICIT_VHOSTS
1801 * is not given, then for backwards compatibility one vhost is created at
1802 * context-creation time using the info from this struct.
1804 * If LWS_SERVER_OPTION_EXPLICIT_VHOSTS is given, then no vhosts are created
1805 * at the same time as the context, they are expected to be created afterwards.
1807 struct lws_context_creation_info {
1809 /**< VHOST: Port to listen on. Use CONTEXT_PORT_NO_LISTEN to suppress
1810 * listening for a client. Use CONTEXT_PORT_NO_LISTEN_SERVER if you are
1811 * writing a server but you are using \ref sock-adopt instead of the
1812 * built-in listener */
1814 /**< VHOST: NULL to bind the listen socket to all interfaces, or the
1815 * interface name, eg, "eth2"
1816 * If options specifies LWS_SERVER_OPTION_UNIX_SOCK, this member is
1817 * the pathname of a UNIX domain socket. you can use the UNIX domain
1818 * sockets in abstract namespace, by prepending an at symbol to the
1820 const struct lws_protocols *protocols;
1821 /**< VHOST: Array of structures listing supported protocols and a protocol-
1822 * specific callback for each one. The list is ended with an
1823 * entry that has a NULL callback pointer. */
1824 const struct lws_extension *extensions;
1825 /**< VHOST: NULL or array of lws_extension structs listing the
1826 * extensions this context supports. */
1827 const struct lws_token_limits *token_limits;
1828 /**< CONTEXT: NULL or struct lws_token_limits pointer which is initialized
1829 * with a token length limit for each possible WSI_TOKEN_ */
1830 const char *ssl_private_key_password;
1831 /**< VHOST: NULL or the passphrase needed for the private key */
1832 const char *ssl_cert_filepath;
1833 /**< VHOST: If libwebsockets was compiled to use ssl, and you want
1834 * to listen using SSL, set to the filepath to fetch the
1835 * server cert from, otherwise NULL for unencrypted */
1836 const char *ssl_private_key_filepath;
1837 /**< VHOST: filepath to private key if wanting SSL mode;
1838 * if this is set to NULL but sll_cert_filepath is set, the
1839 * OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY callback is called
1840 * to allow setting of the private key directly via openSSL
1842 const char *ssl_ca_filepath;
1843 /**< VHOST: CA certificate filepath or NULL */
1844 const char *ssl_cipher_list;
1845 /**< VHOST: List of valid ciphers to use (eg,
1846 * "RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL"
1847 * or you can leave it as NULL to get "DEFAULT" */
1848 const char *http_proxy_address;
1849 /**< VHOST: If non-NULL, attempts to proxy via the given address.
1850 * If proxy auth is required, use format "username:password\@server:port" */
1851 unsigned int http_proxy_port;
1852 /**< VHOST: If http_proxy_address was non-NULL, uses this port */
1854 /**< CONTEXT: group id to change to after setting listen socket, or -1. */
1856 /**< CONTEXT: user id to change to after setting listen socket, or -1. */
1857 unsigned int options;
1858 /**< VHOST + CONTEXT: 0, or LWS_SERVER_OPTION_... bitfields */
1860 /**< CONTEXT: optional user pointer that can be recovered via the context
1861 * pointer using lws_context_user */
1863 /**< CONTEXT: 0 for no TCP keepalive, otherwise apply this keepalive
1864 * timeout to all libwebsocket sockets, client or server */
1866 /**< CONTEXT: if ka_time was nonzero, after the timeout expires how many
1867 * times to try to get a response from the peer before giving up
1868 * and killing the connection */
1870 /**< CONTEXT: if ka_time was nonzero, how long to wait before each ka_probes
1872 #ifdef LWS_OPENSSL_SUPPORT
1873 SSL_CTX *provided_client_ssl_ctx;
1874 /**< CONTEXT: If non-null, swap out libwebsockets ssl
1875 * implementation for the one provided by provided_ssl_ctx.
1876 * Libwebsockets no longer is responsible for freeing the context
1877 * if this option is selected. */
1878 #else /* maintain structure layout either way */
1879 void *provided_client_ssl_ctx; /**< dummy if ssl disabled */
1882 short max_http_header_data;
1883 /**< CONTEXT: The max amount of header payload that can be handled
1884 * in an http request (unrecognized header payload is dropped) */
1885 short max_http_header_pool;
1886 /**< CONTEXT: The max number of connections with http headers that
1887 * can be processed simultaneously (the corresponding memory is
1888 * allocated for the lifetime of the context). If the pool is
1889 * busy new incoming connections must wait for accept until one
1892 unsigned int count_threads;
1893 /**< CONTEXT: how many contexts to create in an array, 0 = 1 */
1894 unsigned int fd_limit_per_thread;
1895 /**< CONTEXT: nonzero means restrict each service thread to this
1896 * many fds, 0 means the default which is divide the process fd
1897 * limit by the number of threads. */
1898 unsigned int timeout_secs;
1899 /**< VHOST: various processes involving network roundtrips in the
1900 * library are protected from hanging forever by timeouts. If
1901 * nonzero, this member lets you set the timeout used in seconds.
1902 * Otherwise a default timeout is used. */
1903 const char *ecdh_curve;
1904 /**< VHOST: if NULL, defaults to initializing server with "prime256v1" */
1905 const char *vhost_name;
1906 /**< VHOST: name of vhost, must match external DNS name used to
1907 * access the site, like "warmcat.com" as it's used to match
1908 * Host: header and / or SNI name for SSL. */
1909 const char * const *plugin_dirs;
1910 /**< CONTEXT: NULL, or NULL-terminated array of directories to
1911 * scan for lws protocol plugins at context creation time */
1912 const struct lws_protocol_vhost_options *pvo;
1913 /**< VHOST: pointer to optional linked list of per-vhost
1914 * options made accessible to protocols */
1915 int keepalive_timeout;
1916 /**< VHOST: (default = 0 = 60s) seconds to allow remote
1917 * client to hold on to an idle HTTP/1.1 connection */
1918 const char *log_filepath;
1919 /**< VHOST: filepath to append logs to... this is opened before
1920 * any dropping of initial privileges */
1921 const struct lws_http_mount *mounts;
1922 /**< VHOST: optional linked list of mounts for this vhost */
1923 const char *server_string;
1924 /**< CONTEXT: string used in HTTP headers to identify server
1925 * software, if NULL, "libwebsockets". */
1926 unsigned int pt_serv_buf_size;
1927 /**< CONTEXT: 0 = default of 4096. This buffer is used by
1928 * various service related features including file serving, it
1929 * defines the max chunk of file that can be sent at once.
1930 * At the risk of lws having to buffer failed large sends, it
1931 * can be increased to, eg, 128KiB to improve throughput. */
1932 unsigned int max_http_header_data2;
1933 /**< CONTEXT: if max_http_header_data is 0 and this
1934 * is nonzero, this will be used in place of the default. It's
1935 * like this for compatibility with the original short version,
1936 * this is unsigned int length. */
1937 long ssl_options_set;
1938 /**< VHOST: Any bits set here will be set as SSL options */
1939 long ssl_options_clear;
1940 /**< VHOST: Any bits set here will be cleared as SSL options */
1941 unsigned short ws_ping_pong_interval;
1942 /**< CONTEXT: 0 for none, else interval in seconds between sending
1943 * PINGs on idle websocket connections. When the PING is sent,
1944 * the PONG must come within the normal timeout_secs timeout period
1945 * or the connection will be dropped.
1946 * Any RX or TX traffic on the connection restarts the interval timer,
1947 * so a connection which always sends or receives something at intervals
1948 * less than the interval given here will never send PINGs / expect
1949 * PONGs. Conversely as soon as the ws connection is established, an
1950 * idle connection will do the PING / PONG roundtrip as soon as
1951 * ws_ping_pong_interval seconds has passed without traffic
1953 const struct lws_protocol_vhost_options *headers;
1954 /**< VHOST: pointer to optional linked list of per-vhost
1955 * canned headers that are added to server responses */
1957 const struct lws_protocol_vhost_options *reject_service_keywords;
1958 /**< CONTEXT: Optional list of keywords and rejection codes + text.
1960 * The keywords are checked for existing in the user agent string.
1962 * Eg, "badrobot" "404 Not Found"
1964 void *external_baggage_free_on_destroy;
1965 /**< CONTEXT: NULL, or pointer to something externally malloc'd, that
1966 * should be freed when the context is destroyed. This allows you to
1967 * automatically sync the freeing action to the context destruction
1968 * action, so there is no need for an external free() if the context
1969 * succeeded to create.
1972 #ifdef LWS_OPENSSL_SUPPORT
1973 /**< CONTEXT: NULL or struct lws_token_limits pointer which is initialized
1974 * with a token length limit for each possible WSI_TOKEN_ */
1975 const char *client_ssl_private_key_password;
1976 /**< VHOST: NULL or the passphrase needed for the private key */
1977 const char *client_ssl_cert_filepath;
1978 /**< VHOST: If libwebsockets was compiled to use ssl, and you want
1979 * to listen using SSL, set to the filepath to fetch the
1980 * server cert from, otherwise NULL for unencrypted */
1981 const char *client_ssl_private_key_filepath;
1982 /**< VHOST: filepath to private key if wanting SSL mode;
1983 * if this is set to NULL but sll_cert_filepath is set, the
1984 * OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY callback is called
1985 * to allow setting of the private key directly via openSSL
1987 const char *client_ssl_ca_filepath;
1988 /**< VHOST: CA certificate filepath or NULL */
1989 const char *client_ssl_cipher_list;
1990 /**< VHOST: List of valid ciphers to use (eg,
1991 * "RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL"
1992 * or you can leave it as NULL to get "DEFAULT" */
1995 const struct lws_plat_file_ops *fops;
1996 /**< CONTEXT: NULL, or pointer to an array of fops structs, terminated
1997 * by a sentinel with NULL .open.
1999 * If NULL, lws provides just the platform file operations struct for
2000 * backwards compatibility.
2002 int simultaneous_ssl_restriction;
2003 /**< CONTEXT: 0 (no limit) or limit of simultaneous SSL sessions possible.*/
2004 const char *socks_proxy_address;
2005 /**< VHOST: If non-NULL, attempts to proxy via the given address.
2006 * If proxy auth is required, use format "username:password\@server:port" */
2007 unsigned int socks_proxy_port;
2008 /**< VHOST: If socks_proxy_address was non-NULL, uses this port */
2009 #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP)
2010 cap_value_t caps[4];
2011 /**< CONTEXT: array holding Linux capabilities you want to
2012 * continue to be available to the server after it transitions
2013 * to a noprivileged user. Usually none are needed but for, eg,
2014 * .bind_iface, CAP_NET_RAW is required. This gives you a way
2015 * to still have the capability but drop root.
2018 /**< CONTEXT: count of Linux capabilities in .caps[]. 0 means
2019 * no capabilities will be inherited from root (the default) */
2022 /**< VHOST: nonzero to strictly bind sockets to the interface name in
2023 * .iface (eg, "eth2"), using SO_BIND_TO_DEVICE.
2025 * Requires SO_BINDTODEVICE support from your OS and CAP_NET_RAW
2028 * Notice that common things like access network interface IP from
2029 * your local machine use your lo / loopback interface and will be
2030 * disallowed by this.
2033 /* Add new things just above here ---^
2034 * This is part of the ABI, don't needlessly break compatibility
2036 * The below is to ensure later library versions with new
2037 * members added above will see 0 (default) even if the app
2038 * was not built against the newer headers.
2041 void *_unused[8]; /**< dummy */
2045 * lws_create_context() - Create the websocket handler
2046 * \param info: pointer to struct with parameters
2048 * This function creates the listening socket (if serving) and takes care
2049 * of all initialization in one step.
2051 * If option LWS_SERVER_OPTION_EXPLICIT_VHOSTS is given, no vhost is
2052 * created; you're expected to create your own vhosts afterwards using
2053 * lws_create_vhost(). Otherwise a vhost named "default" is also created
2054 * using the information in the vhost-related members, for compatibility.
2056 * After initialization, it returns a struct lws_context * that
2057 * represents this server. After calling, user code needs to take care
2058 * of calling lws_service() with the context pointer to get the
2059 * server's sockets serviced. This must be done in the same process
2060 * context as the initialization call.
2062 * The protocol callback functions are called for a handful of events
2063 * including http requests coming in, websocket connections becoming
2064 * established, and data arriving; it's also called periodically to allow
2065 * async transmission.
2067 * HTTP requests are sent always to the FIRST protocol in protocol, since
2068 * at that time websocket protocol has not been negotiated. Other
2069 * protocols after the first one never see any HTTP callback activity.
2071 * The server created is a simple http server by default; part of the
2072 * websocket standard is upgrading this http connection to a websocket one.
2074 * This allows the same server to provide files like scripts and favicon /
2075 * images or whatever over http and dynamic data over websockets all in
2076 * one place; they're all handled in the user callback.
2078 LWS_VISIBLE LWS_EXTERN struct lws_context *
2079 lws_create_context(struct lws_context_creation_info *info);
2082 * lws_context_destroy() - Destroy the websocket context
2083 * \param context: Websocket context
2085 * This function closes any active connections and then frees the
2086 * context. After calling this, any further use of the context is
2089 LWS_VISIBLE LWS_EXTERN void
2090 lws_context_destroy(struct lws_context *context);
2092 LWS_VISIBLE LWS_EXTERN void
2093 lws_context_destroy2(struct lws_context *context);
2095 typedef int (*lws_reload_func)(void);
2098 * lws_context_deprecate() - Deprecate the websocket context
2099 * \param context: Websocket context
2101 * This function is used on an existing context before superceding it
2102 * with a new context.
2104 * It closes any listen sockets in the context, so new connections are
2107 * And it marks the context to be deleted when the number of active
2108 * connections into it falls to zero.
2110 * Otherwise if you attach the deprecated context to the replacement
2111 * context when it has been created using lws_context_attach_deprecated()
2112 * both any deprecated and the new context will service their connections.
2114 * This is aimed at allowing seamless configuration reloads.
2116 * The callback cb will be called after the listen sockets are actually
2117 * closed and may be reopened. In the callback the new context should be
2118 * configured and created. (With libuv, socket close happens async after
2119 * more loop events).
2121 LWS_VISIBLE LWS_EXTERN void
2122 lws_context_deprecate(struct lws_context *context, lws_reload_func cb);
2124 LWS_VISIBLE LWS_EXTERN int
2125 lws_context_is_deprecated(struct lws_context *context);
2128 * lws_set_proxy() - Setups proxy to lws_context.
2129 * \param vhost: pointer to struct lws_vhost you want set proxy for
2130 * \param proxy: pointer to c string containing proxy in format address:port
2132 * Returns 0 if proxy string was parsed and proxy was setup.
2133 * Returns -1 if proxy is NULL or has incorrect format.
2135 * This is only required if your OS does not provide the http_proxy
2136 * environment variable (eg, OSX)
2138 * IMPORTANT! You should call this function right after creation of the
2139 * lws_context and before call to connect. If you call this
2140 * function after connect behavior is undefined.
2141 * This function will override proxy settings made on lws_context
2142 * creation with genenv() call.
2144 LWS_VISIBLE LWS_EXTERN int
2145 lws_set_proxy(struct lws_vhost *vhost, const char *proxy);
2148 * lws_set_socks() - Setup socks to lws_context.
2149 * \param vhost: pointer to struct lws_vhost you want set socks for
2150 * \param socks: pointer to c string containing socks in format address:port
2152 * Returns 0 if socks string was parsed and socks was setup.
2153 * Returns -1 if socks is NULL or has incorrect format.
2155 * This is only required if your OS does not provide the socks_proxy
2156 * environment variable (eg, OSX)
2158 * IMPORTANT! You should call this function right after creation of the
2159 * lws_context and before call to connect. If you call this
2160 * function after connect behavior is undefined.
2161 * This function will override proxy settings made on lws_context
2162 * creation with genenv() call.
2164 LWS_VISIBLE LWS_EXTERN int
2165 lws_set_socks(struct lws_vhost *vhost, const char *socks);
2170 * lws_create_vhost() - Create a vhost (virtual server context)
2171 * \param context: pointer to result of lws_create_context()
2172 * \param info: pointer to struct with parameters
2174 * This function creates a virtual server (vhost) using the vhost-related
2175 * members of the info struct. You can create many vhosts inside one context
2176 * if you created the context with the option LWS_SERVER_OPTION_EXPLICIT_VHOSTS
2178 LWS_EXTERN LWS_VISIBLE struct lws_vhost *
2179 lws_create_vhost(struct lws_context *context,
2180 struct lws_context_creation_info *info);
2183 * lwsws_get_config_globals() - Parse a JSON server config file
2184 * \param info: pointer to struct with parameters
2185 * \param d: filepath of the config file
2186 * \param config_strings: storage for the config strings extracted from JSON,
2187 * the pointer is incremented as strings are stored
2188 * \param len: pointer to the remaining length left in config_strings
2189 * the value is decremented as strings are stored
2191 * This function prepares a n lws_context_creation_info struct with global
2192 * settings from a file d.
2194 * Requires CMake option LWS_WITH_LEJP_CONF to have been enabled
2196 LWS_VISIBLE LWS_EXTERN int
2197 lwsws_get_config_globals(struct lws_context_creation_info *info, const char *d,
2198 char **config_strings, int *len);
2201 * lwsws_get_config_vhosts() - Create vhosts from a JSON server config file
2202 * \param context: pointer to result of lws_create_context()
2203 * \param info: pointer to struct with parameters
2204 * \param d: filepath of the config file
2205 * \param config_strings: storage for the config strings extracted from JSON,
2206 * the pointer is incremented as strings are stored
2207 * \param len: pointer to the remaining length left in config_strings
2208 * the value is decremented as strings are stored
2210 * This function creates vhosts into a context according to the settings in
2211 *JSON files found in directory d.
2213 * Requires CMake option LWS_WITH_LEJP_CONF to have been enabled
2215 LWS_VISIBLE LWS_EXTERN int
2216 lwsws_get_config_vhosts(struct lws_context *context,
2217 struct lws_context_creation_info *info, const char *d,
2218 char **config_strings, int *len);
2220 /** lws_vhost_get() - \deprecated deprecated: use lws_get_vhost() */
2221 LWS_VISIBLE LWS_EXTERN struct lws_vhost *
2222 lws_vhost_get(struct lws *wsi) LWS_WARN_DEPRECATED;
2225 * lws_get_vhost() - return the vhost a wsi belongs to
2227 * \param wsi: which connection
2229 LWS_VISIBLE LWS_EXTERN struct lws_vhost *
2230 lws_get_vhost(struct lws *wsi);
2233 * lws_json_dump_vhost() - describe vhost state and stats in JSON
2235 * \param vh: the vhost
2236 * \param buf: buffer to fill with JSON
2237 * \param len: max length of buf
2239 LWS_VISIBLE LWS_EXTERN int
2240 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len);
2243 * lws_json_dump_context() - describe context state and stats in JSON
2245 * \param context: the context
2246 * \param buf: buffer to fill with JSON
2247 * \param len: max length of buf
2249 LWS_VISIBLE LWS_EXTERN int
2250 lws_json_dump_context(const struct lws_context *context, char *buf, int len,
2254 * lws_context_user() - get the user data associated with the context
2255 * \param context: Websocket context
2257 * This returns the optional user allocation that can be attached to
2258 * the context the sockets live in at context_create time. It's a way
2259 * to let all sockets serviced in the same context share data without
2260 * using globals statics in the user code.
2262 LWS_VISIBLE LWS_EXTERN void *
2263 lws_context_user(struct lws_context *context);
2265 /*! \defgroup vhost-mounts Vhost mounts and options
2266 * \ingroup context-and-vhost-creation
2268 * ##Vhost mounts and options
2271 /** struct lws_protocol_vhost_options - linked list of per-vhost protocol
2272 * name=value options
2274 * This provides a general way to attach a linked-list of name=value pairs,
2275 * which can also have an optional child link-list using the options member.
2277 struct lws_protocol_vhost_options {
2278 const struct lws_protocol_vhost_options *next; /**< linked list */
2279 const struct lws_protocol_vhost_options *options; /**< child linked-list of more options for this node */
2280 const char *name; /**< name of name=value pair */
2281 const char *value; /**< value of name=value pair */
2284 /** enum lws_mount_protocols
2285 * This specifies the mount protocol for a mountpoint, whether it is to be
2286 * served from a filesystem, or it is a cgi etc.
2288 enum lws_mount_protocols {
2289 LWSMPRO_HTTP = 0, /**< not supported yet */
2290 LWSMPRO_HTTPS = 1, /**< not supported yet */
2291 LWSMPRO_FILE = 2, /**< serve from filesystem directory */
2292 LWSMPRO_CGI = 3, /**< pass to CGI to handle */
2293 LWSMPRO_REDIR_HTTP = 4, /**< redirect to http:// url */
2294 LWSMPRO_REDIR_HTTPS = 5, /**< redirect to https:// url */
2295 LWSMPRO_CALLBACK = 6, /**< hand by named protocol's callback */
2298 /** struct lws_http_mount
2300 * arguments for mounting something in a vhost's url namespace
2302 struct lws_http_mount {
2303 const struct lws_http_mount *mount_next;
2304 /**< pointer to next struct lws_http_mount */
2305 const char *mountpoint;
2306 /**< mountpoint in http pathspace, eg, "/" */
2308 /**< path to be mounted, eg, "/var/www/warmcat.com" */
2310 /**< default target, eg, "index.html" */
2311 const char *protocol;
2312 /**<"protocol-name" to handle mount */
2314 const struct lws_protocol_vhost_options *cgienv;
2315 /**< optional linked-list of cgi options. These are created
2316 * as environment variables for the cgi process
2318 const struct lws_protocol_vhost_options *extra_mimetypes;
2319 /**< optional linked-list of mimetype mappings */
2320 const struct lws_protocol_vhost_options *interpret;
2321 /**< optional linked-list of files to be interpreted */
2324 /**< seconds cgi is allowed to live, if cgi://mount type */
2326 /**< max-age for reuse of client cache of files, seconds */
2327 unsigned int auth_mask;
2328 /**< bits set here must be set for authorized client session */
2330 unsigned int cache_reusable:1; /**< set if client cache may reuse this */
2331 unsigned int cache_revalidate:1; /**< set if client cache should revalidate on use */
2332 unsigned int cache_intermediaries:1; /**< set if intermediaries are allowed to cache */
2334 unsigned char origin_protocol; /**< one of enum lws_mount_protocols */
2335 unsigned char mountpoint_len; /**< length of mountpoint string */
2337 const char *basic_auth_login_file;
2338 /**<NULL, or filepath to use to check basic auth logins against */
2340 /* Add new things just above here ---^
2341 * This is part of the ABI, don't needlessly break compatibility
2343 * The below is to ensure later library versions with new
2344 * members added above will see 0 (default) even if the app
2345 * was not built against the newer headers.
2348 void *_unused[2]; /**< dummy */
2353 /*! \defgroup client
2356 * ##Client releated functions
2360 /** enum lws_client_connect_ssl_connection_flags - flags that may be used
2361 * with struct lws_client_connect_info ssl_connection member to control if
2362 * and how SSL checks apply to the client connection being created
2365 enum lws_client_connect_ssl_connection_flags {
2366 LCCSCF_USE_SSL = (1 << 0),
2367 LCCSCF_ALLOW_SELFSIGNED = (1 << 1),
2368 LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK = (1 << 2),
2369 LCCSCF_ALLOW_EXPIRED = (1 << 3)
2372 /** struct lws_client_connect_info - parameters to connect with when using
2373 * lws_client_connect_via_info() */
2375 struct lws_client_connect_info {
2376 struct lws_context *context;
2377 /**< lws context to create connection in */
2378 const char *address;
2379 /**< remote address to connect to */
2381 /**< remote port to connect to */
2383 /**< nonzero for ssl */
2387 /**< content of host header */
2389 /**< content of origin header */
2390 const char *protocol;
2391 /**< list of ws protocols we could accept */
2392 int ietf_version_or_minus_one;
2393 /**< deprecated: currently leave at 0 or -1 */
2395 /**< if non-NULL, use this as wsi user_data instead of malloc it */
2396 const void *client_exts;
2397 /**< UNUSED... provide in info.extensions at context creation time */
2399 /**< if non-NULL, do this http method instead of ws[s] upgrade.
2400 * use "GET" to be a simple http client connection */
2401 struct lws *parent_wsi;
2402 /**< if another wsi is responsible for this connection, give it here.
2403 * this is used to make sure if the parent closes so do any
2404 * child connections first. */
2405 const char *uri_replace_from;
2406 /**< if non-NULL, when this string is found in URIs in
2407 * text/html content-encoding, it's replaced with uri_replace_to */
2408 const char *uri_replace_to;
2409 /**< see uri_replace_from */
2410 struct lws_vhost *vhost;
2411 /**< vhost to bind to (used to determine related SSL_CTX) */
2413 /**< if not NULL, store the new wsi here early in the connection
2414 * process. Although we return the new wsi, the call to create the
2415 * client connection does progress the connection somewhat and may
2416 * meet an error that will result in the connection being scrubbed and
2417 * NULL returned. While the wsi exists though, he may process a
2418 * callback like CLIENT_CONNECTION_ERROR with his wsi: this gives the
2419 * user callback a way to identify which wsi it is that faced the error
2420 * even before the new wsi is returned and even if ultimately no wsi
2424 /* Add new things just above here ---^
2425 * This is part of the ABI, don't needlessly break compatibility
2427 * The below is to ensure later library versions with new
2428 * members added above will see 0 (default) even if the app
2429 * was not built against the newer headers.
2432 void *_unused[4]; /**< dummy */
2436 * lws_client_connect_via_info() - Connect to another websocket server
2437 * \param ccinfo: pointer to lws_client_connect_info struct
2439 * This function creates a connection to a remote server using the
2440 * information provided in ccinfo.
2442 LWS_VISIBLE LWS_EXTERN struct lws *
2443 lws_client_connect_via_info(struct lws_client_connect_info * ccinfo);
2446 * lws_client_connect() - Connect to another websocket server
2447 * \deprecated DEPRECATED use lws_client_connect_via_info
2448 * \param clients: Websocket context
2449 * \param address: Remote server address, eg, "myserver.com"
2450 * \param port: Port to connect to on the remote server, eg, 80
2451 * \param ssl_connection: 0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
2453 * \param path: Websocket path on server
2454 * \param host: Hostname on server
2455 * \param origin: Socket origin name
2456 * \param protocol: Comma-separated list of protocols being asked for from
2457 * the server, or just one. The server will pick the one it
2458 * likes best. If you don't want to specify a protocol, which is
2459 * legal, use NULL here.
2460 * \param ietf_version_or_minus_one: -1 to ask to connect using the default, latest
2461 * protocol supported, or the specific protocol ordinal
2463 * This function creates a connection to a remote server
2465 /* deprecated, use lws_client_connect_via_info() */
2466 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
2467 lws_client_connect(struct lws_context *clients, const char *address,
2468 int port, int ssl_connection, const char *path,
2469 const char *host, const char *origin, const char *protocol,
2470 int ietf_version_or_minus_one) LWS_WARN_DEPRECATED;
2471 /* deprecated, use lws_client_connect_via_info() */
2473 * lws_client_connect_extended() - Connect to another websocket server
2474 * \deprecated DEPRECATED use lws_client_connect_via_info
2475 * \param clients: Websocket context
2476 * \param address: Remote server address, eg, "myserver.com"
2477 * \param port: Port to connect to on the remote server, eg, 80
2478 * \param ssl_connection: 0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
2480 * \param path: Websocket path on server
2481 * \param host: Hostname on server
2482 * \param origin: Socket origin name
2483 * \param protocol: Comma-separated list of protocols being asked for from
2484 * the server, or just one. The server will pick the one it
2486 * \param ietf_version_or_minus_one: -1 to ask to connect using the default, latest
2487 * protocol supported, or the specific protocol ordinal
2488 * \param userdata: Pre-allocated user data
2490 * This function creates a connection to a remote server
2492 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
2493 lws_client_connect_extended(struct lws_context *clients, const char *address,
2494 int port, int ssl_connection, const char *path,
2495 const char *host, const char *origin,
2496 const char *protocol, int ietf_version_or_minus_one,
2497 void *userdata) LWS_WARN_DEPRECATED;
2500 * lws_init_vhost_client_ssl() - also enable client SSL on an existing vhost
2502 * \param info: client ssl related info
2503 * \param vhost: which vhost to initialize client ssl operations on
2505 * You only need to call this if you plan on using SSL client connections on
2506 * the vhost. For non-SSL client connections, it's not necessary to call this.
2508 * The following members of info are used during the call
2510 * - options must have LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT set,
2511 * otherwise the call does nothing
2512 * - provided_client_ssl_ctx must be NULL to get a generated client
2513 * ssl context, otherwise you can pass a prepared one in by setting it
2514 * - ssl_cipher_list may be NULL or set to the client valid cipher list
2515 * - ssl_ca_filepath may be NULL or client cert filepath
2516 * - ssl_cert_filepath may be NULL or client cert filepath
2517 * - ssl_private_key_filepath may be NULL or client cert private key
2519 * You must create your vhost explicitly if you want to use this, so you have
2520 * a pointer to the vhost. Create the context first with the option flag
2521 * LWS_SERVER_OPTION_EXPLICIT_VHOSTS and then call lws_create_vhost() with
2522 * the same info struct.
2524 LWS_VISIBLE LWS_EXTERN int
2525 lws_init_vhost_client_ssl(const struct lws_context_creation_info *info,
2526 struct lws_vhost *vhost);
2528 * lws_http_client_read() - consume waiting received http client data
2530 * \param wsi: client connection
2531 * \param buf: pointer to buffer pointer - fill with pointer to your buffer
2532 * \param len: pointer to chunk length - fill with max length of buffer
2534 * This is called when the user code is notified client http data has arrived.
2535 * The user code may choose to delay calling it to consume the data, for example
2536 * waiting until an onward connection is writeable.
2538 * For non-chunked connections, up to len bytes of buf are filled with the
2539 * received content. len is set to the actual amount filled before return.
2541 * For chunked connections, the linear buffer content contains the chunking
2542 * headers and it cannot be passed in one lump. Instead, this function will
2543 * call back LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ with in pointing to the
2544 * chunk start and len set to the chunk length. There will be as many calls
2545 * as there are chunks or partial chunks in the buffer.
2547 LWS_VISIBLE LWS_EXTERN int
2548 lws_http_client_read(struct lws *wsi, char **buf, int *len);
2551 * lws_http_client_http_response() - get last HTTP response code
2553 * \param wsi: client connection
2555 * Returns the last server response code, eg, 200 for client http connections.
2557 LWS_VISIBLE LWS_EXTERN unsigned int
2558 lws_http_client_http_response(struct lws *wsi);
2560 LWS_VISIBLE LWS_EXTERN void
2561 lws_client_http_body_pending(struct lws *wsi, int something_left_to_send);
2564 * lws_client_http_body_pending() - control if client connection neeeds to send body
2566 * \param wsi: client connection
2567 * \param something_left_to_send: nonzero if need to send more body, 0 (default)
2568 * if nothing more to send
2570 * If you will send payload data with your HTTP client connection, eg, for POST,
2571 * when you set the related http headers in
2572 * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER callback you should also call
2573 * this API with something_left_to_send nonzero, and call
2574 * lws_callback_on_writable(wsi);
2576 * After sending the headers, lws will call your callback with
2577 * LWS_CALLBACK_CLIENT_HTTP_WRITEABLE reason when writable. You can send the
2578 * next part of the http body payload, calling lws_callback_on_writable(wsi);
2579 * if there is more to come, or lws_client_http_body_pending(wsi, 0); to
2580 * let lws know the last part is sent and the connection can move on.
2585 /** \defgroup service Built-in service loop entry
2587 * ##Built-in service loop entry
2589 * If you're not using libev / libuv, these apis are needed to enter the poll()
2590 * wait in lws and service any connections with pending events.
2595 * lws_service() - Service any pending websocket activity
2596 * \param context: Websocket context
2597 * \param timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
2598 * service otherwise block and service immediately, returning
2599 * after the timeout if nothing needed service.
2601 * This function deals with any pending websocket traffic, for three
2602 * kinds of event. It handles these events on both server and client
2603 * types of connection the same.
2605 * 1) Accept new connections to our context's server
2607 * 2) Call the receive callback for incoming frame data received by
2608 * server or client connections.
2610 * You need to call this service function periodically to all the above
2611 * functions to happen; if your application is single-threaded you can
2612 * just call it in your main event loop.
2614 * Alternatively you can fork a new process that asynchronously handles
2615 * calling this service in a loop. In that case you are happy if this
2616 * call blocks your thread until it needs to take care of something and
2617 * would call it with a large nonzero timeout. Your loop then takes no
2618 * CPU while there is nothing happening.
2620 * If you are calling it in a single-threaded app, you don't want it to
2621 * wait around blocking other things in your loop from happening, so you
2622 * would call it with a timeout_ms of 0, so it returns immediately if
2623 * nothing is pending, or as soon as it services whatever was pending.
2625 LWS_VISIBLE LWS_EXTERN int
2626 lws_service(struct lws_context *context, int timeout_ms);
2629 * lws_service() - Service any pending websocket activity
2631 * \param context: Websocket context
2632 * \param timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
2633 * service otherwise block and service immediately, returning
2634 * after the timeout if nothing needed service.
2636 * Same as lws_service(), but for a specific thread service index. Only needed
2637 * if you are spawning multiple service threads.
2639 LWS_VISIBLE LWS_EXTERN int
2640 lws_service_tsi(struct lws_context *context, int timeout_ms, int tsi);
2643 * lws_cancel_service_pt() - Cancel servicing of pending socket activity
2645 * \param wsi: Cancel service on the thread this wsi is serviced by
2647 * This function lets a call to lws_service() waiting for a timeout
2648 * immediately return.
2650 * It works by creating a phony event and then swallowing it silently.
2652 * The reason it may be needed is when waiting in poll(), changes to
2653 * the event masks are ignored by the OS until poll() is reentered. This
2654 * lets you halt the poll() wait and make the reentry happen immediately
2655 * instead of having the wait out the rest of the poll timeout.
2657 LWS_VISIBLE LWS_EXTERN void
2658 lws_cancel_service_pt(struct lws *wsi);
2661 * lws_cancel_service() - Cancel wait for new pending socket activity
2662 * \param context: Websocket context
2664 * This function let a call to lws_service() waiting for a timeout
2665 * immediately return.
2667 * What it basically does is provide a fake event that will be swallowed,
2668 * so the wait in poll() is ended. That's useful because poll() doesn't
2669 * attend to changes in POLLIN/OUT/ERR until it re-enters the wait.
2671 LWS_VISIBLE LWS_EXTERN void
2672 lws_cancel_service(struct lws_context *context);
2675 * lws_service_fd() - Service polled socket with something waiting
2676 * \param context: Websocket context
2677 * \param pollfd: The pollfd entry describing the socket fd and which events
2678 * happened, or NULL to tell lws to do only timeout servicing.
2680 * This function takes a pollfd that has POLLIN or POLLOUT activity and
2681 * services it according to the state of the associated
2684 * The one call deals with all "service" that might happen on a socket
2685 * including listen accepts, http files as well as websocket protocol.
2687 * If a pollfd says it has something, you can just pass it to
2688 * lws_service_fd() whether it is a socket handled by lws or not.
2689 * If it sees it is a lws socket, the traffic will be handled and
2690 * pollfd->revents will be zeroed now.
2692 * If the socket is foreign to lws, it leaves revents alone. So you can
2693 * see if you should service yourself by checking the pollfd revents
2694 * after letting lws try to service it.
2696 * You should also call this with pollfd = NULL to just allow the
2697 * once-per-second global timeout checks; if less than a second since the last
2698 * check it returns immediately then.
2700 LWS_VISIBLE LWS_EXTERN int
2701 lws_service_fd(struct lws_context *context, struct lws_pollfd *pollfd);
2704 * lws_service_fd_tsi() - Service polled socket in specific service thread
2705 * \param context: Websocket context
2706 * \param pollfd: The pollfd entry describing the socket fd and which events
2708 * \param tsi: thread service index
2710 * Same as lws_service_fd() but used with multiple service threads
2712 LWS_VISIBLE LWS_EXTERN int
2713 lws_service_fd_tsi(struct lws_context *context, struct lws_pollfd *pollfd,
2717 * lws_service_adjust_timeout() - Check for any connection needing forced service
2718 * \param context: Websocket context
2719 * \param timeout_ms: The original poll timeout value. You can just set this
2720 * to 1 if you don't really have a poll timeout.
2721 * \param tsi: thread service index
2723 * Under some conditions connections may need service even though there is no
2724 * pending network action on them, this is "forced service". For default
2725 * poll() and libuv / libev, the library takes care of calling this and
2726 * dealing with it for you. But for external poll() integration, you need
2727 * access to the apis.
2729 * If anybody needs "forced service", returned timeout is zero. In that case,
2730 * you can call lws_service_tsi() with a timeout of -1 to only service
2731 * guys who need forced service.
2733 LWS_VISIBLE LWS_EXTERN int
2734 lws_service_adjust_timeout(struct lws_context *context, int timeout_ms, int tsi);
2736 /* Backwards compatibility */
2737 #define lws_plat_service_tsi lws_service_tsi
2741 /*! \defgroup http HTTP
2743 Modules related to handling HTTP
2747 /*! \defgroup httpft HTTP File transfer
2750 APIs for sending local files in response to HTTP requests
2755 * lws_get_mimetype() - Determine mimetype to use from filename
2757 * \param file: filename
2758 * \param m: NULL, or mount context
2760 * This uses a canned list of known filetypes first, if no match and m is
2761 * non-NULL, then tries a list of per-mount file suffix to mimtype mappings.
2763 * Returns either NULL or a pointer to the mimetype matching the file.
2765 LWS_VISIBLE LWS_EXTERN const char *
2766 lws_get_mimetype(const char *file, const struct lws_http_mount *m);
2769 * lws_serve_http_file() - Send a file back to the client using http
2770 * \param wsi: Websocket instance (available from user callback)
2771 * \param file: The file to issue over http
2772 * \param content_type: The http content type, eg, text/html
2773 * \param other_headers: NULL or pointer to header string
2774 * \param other_headers_len: length of the other headers if non-NULL
2776 * This function is intended to be called from the callback in response
2777 * to http requests from the client. It allows the callback to issue
2778 * local files down the http link in a single step.
2780 * Returning <0 indicates error and the wsi should be closed. Returning
2781 * >0 indicates the file was completely sent and
2782 * lws_http_transaction_completed() called on the wsi (and close if != 0)
2783 * ==0 indicates the file transfer is started and needs more service later,
2784 * the wsi should be left alone.
2786 LWS_VISIBLE LWS_EXTERN int
2787 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
2788 const char *other_headers, int other_headers_len);
2790 LWS_VISIBLE LWS_EXTERN int
2791 lws_serve_http_file_fragment(struct lws *wsi);
2794 /*! \defgroup html-chunked-substitution HTML Chunked Substitution
2797 * ##HTML chunked Substitution
2799 * APIs for receiving chunks of text, replacing a set of variable names via
2800 * a callback, and then prepending and appending HTML chunked encoding
2806 HTTP_STATUS_OK = 200,
2807 HTTP_STATUS_NO_CONTENT = 204,
2808 HTTP_STATUS_PARTIAL_CONTENT = 206,
2810 HTTP_STATUS_MOVED_PERMANENTLY = 301,
2811 HTTP_STATUS_FOUND = 302,
2812 HTTP_STATUS_SEE_OTHER = 303,
2813 HTTP_STATUS_NOT_MODIFIED = 304,
2815 HTTP_STATUS_BAD_REQUEST = 400,
2816 HTTP_STATUS_UNAUTHORIZED,
2817 HTTP_STATUS_PAYMENT_REQUIRED,
2818 HTTP_STATUS_FORBIDDEN,
2819 HTTP_STATUS_NOT_FOUND,
2820 HTTP_STATUS_METHOD_NOT_ALLOWED,
2821 HTTP_STATUS_NOT_ACCEPTABLE,
2822 HTTP_STATUS_PROXY_AUTH_REQUIRED,
2823 HTTP_STATUS_REQUEST_TIMEOUT,
2824 HTTP_STATUS_CONFLICT,
2826 HTTP_STATUS_LENGTH_REQUIRED,
2827 HTTP_STATUS_PRECONDITION_FAILED,
2828 HTTP_STATUS_REQ_ENTITY_TOO_LARGE,
2829 HTTP_STATUS_REQ_URI_TOO_LONG,
2830 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE,
2831 HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE,
2832 HTTP_STATUS_EXPECTATION_FAILED,
2834 HTTP_STATUS_INTERNAL_SERVER_ERROR = 500,
2835 HTTP_STATUS_NOT_IMPLEMENTED,
2836 HTTP_STATUS_BAD_GATEWAY,
2837 HTTP_STATUS_SERVICE_UNAVAILABLE,
2838 HTTP_STATUS_GATEWAY_TIMEOUT,
2839 HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED,
2842 struct lws_process_html_args {
2843 char *p; /**< pointer to the buffer containing the data */
2844 int len; /**< length of the original data at p */
2845 int max_len; /**< maximum length we can grow the data to */
2846 int final; /**< set if this is the last chunk of the file */
2849 typedef const char *(*lws_process_html_state_cb)(void *data, int index);
2851 struct lws_process_html_state {
2852 char *start; /**< pointer to start of match */
2853 char swallow[16]; /**< matched character buffer */
2854 int pos; /**< position in match */
2855 void *data; /**< opaque pointer */
2856 const char * const *vars; /**< list of variable names */
2857 int count_vars; /**< count of variable names */
2859 lws_process_html_state_cb replace; /**< called on match to perform substitution */
2862 /*! lws_chunked_html_process() - generic chunked substitution
2863 * \param args: buffer to process using chunked encoding
2864 * \param s: current processing state
2866 LWS_VISIBLE LWS_EXTERN int
2867 lws_chunked_html_process(struct lws_process_html_args *args,
2868 struct lws_process_html_state *s);
2871 /** \defgroup HTTP-headers-read HTTP headers: read
2874 * ##HTTP header releated functions
2876 * In lws the client http headers are temporarily stored in a pool, only for the
2877 * duration of the http part of the handshake. It's because in most cases,
2878 * the header content is ignored for the whole rest of the connection lifetime
2879 * and would then just be taking up space needlessly.
2881 * During LWS_CALLBACK_HTTP when the URI path is delivered is the last time
2882 * the http headers are still allocated, you can use these apis then to
2883 * look at and copy out interesting header content (cookies, etc)
2885 * Notice that the header total length reported does not include a terminating
2886 * '\0', however you must allocate for it when using the _copy apis. So the
2887 * length reported for a header containing "123" is 3, but you must provide
2888 * a buffer of length 4 so that "123\0" may be copied into it, or the copy
2889 * will fail with a nonzero return code.
2891 * In the special case of URL arguments, like ?x=1&y=2, the arguments are
2892 * stored in a token named for the method, eg, WSI_TOKEN_GET_URI if it
2893 * was a GET or WSI_TOKEN_POST_URI if POST. You can check the total
2894 * length to confirm the method.
2896 * For URL arguments, each argument is stored urldecoded in a "fragment", so
2897 * you can use the fragment-aware api lws_hdr_copy_fragment() to access each
2898 * argument in turn: the fragments contain urldecoded strings like x=1 or y=2.
2900 * As a convenience, lws has an api that will find the fragment with a
2901 * given name= part, lws_get_urlarg_by_name().
2905 /** struct lws_tokens
2906 * you need these to look at headers that have been parsed if using the
2907 * LWS_CALLBACK_FILTER_CONNECTION callback. If a header from the enum
2908 * list below is absent, .token = NULL and token_len = 0. Otherwise .token
2909 * points to .token_len chars containing that header content.
2912 char *token; /**< pointer to start of the token */
2913 int token_len; /**< length of the token's value */
2916 /* enum lws_token_indexes
2917 * these have to be kept in sync with lextable.h / minilex.c
2919 * NOTE: These public enums are part of the abi. If you want to add one,
2920 * add it at where specified so existing users are unaffected.
2922 enum lws_token_indexes {
2923 WSI_TOKEN_GET_URI = 0,
2924 WSI_TOKEN_POST_URI = 1,
2925 WSI_TOKEN_OPTIONS_URI = 2,
2927 WSI_TOKEN_CONNECTION = 4,
2928 WSI_TOKEN_UPGRADE = 5,
2929 WSI_TOKEN_ORIGIN = 6,
2930 WSI_TOKEN_DRAFT = 7,
2931 WSI_TOKEN_CHALLENGE = 8,
2932 WSI_TOKEN_EXTENSIONS = 9,
2933 WSI_TOKEN_KEY1 = 10,
2934 WSI_TOKEN_KEY2 = 11,
2935 WSI_TOKEN_PROTOCOL = 12,
2936 WSI_TOKEN_ACCEPT = 13,
2937 WSI_TOKEN_NONCE = 14,
2938 WSI_TOKEN_HTTP = 15,
2939 WSI_TOKEN_HTTP2_SETTINGS = 16,
2940 WSI_TOKEN_HTTP_ACCEPT = 17,
2941 WSI_TOKEN_HTTP_AC_REQUEST_HEADERS = 18,
2942 WSI_TOKEN_HTTP_IF_MODIFIED_SINCE = 19,
2943 WSI_TOKEN_HTTP_IF_NONE_MATCH = 20,
2944 WSI_TOKEN_HTTP_ACCEPT_ENCODING = 21,
2945 WSI_TOKEN_HTTP_ACCEPT_LANGUAGE = 22,
2946 WSI_TOKEN_HTTP_PRAGMA = 23,
2947 WSI_TOKEN_HTTP_CACHE_CONTROL = 24,
2948 WSI_TOKEN_HTTP_AUTHORIZATION = 25,
2949 WSI_TOKEN_HTTP_COOKIE = 26,
2950 WSI_TOKEN_HTTP_CONTENT_LENGTH = 27,
2951 WSI_TOKEN_HTTP_CONTENT_TYPE = 28,
2952 WSI_TOKEN_HTTP_DATE = 29,
2953 WSI_TOKEN_HTTP_RANGE = 30,
2954 WSI_TOKEN_HTTP_REFERER = 31,
2956 WSI_TOKEN_VERSION = 33,
2957 WSI_TOKEN_SWORIGIN = 34,
2959 WSI_TOKEN_HTTP_COLON_AUTHORITY = 35,
2960 WSI_TOKEN_HTTP_COLON_METHOD = 36,
2961 WSI_TOKEN_HTTP_COLON_PATH = 37,
2962 WSI_TOKEN_HTTP_COLON_SCHEME = 38,
2963 WSI_TOKEN_HTTP_COLON_STATUS = 39,
2965 WSI_TOKEN_HTTP_ACCEPT_CHARSET = 40,
2966 WSI_TOKEN_HTTP_ACCEPT_RANGES = 41,
2967 WSI_TOKEN_HTTP_ACCESS_CONTROL_ALLOW_ORIGIN = 42,
2968 WSI_TOKEN_HTTP_AGE = 43,
2969 WSI_TOKEN_HTTP_ALLOW = 44,
2970 WSI_TOKEN_HTTP_CONTENT_DISPOSITION = 45,
2971 WSI_TOKEN_HTTP_CONTENT_ENCODING = 46,
2972 WSI_TOKEN_HTTP_CONTENT_LANGUAGE = 47,
2973 WSI_TOKEN_HTTP_CONTENT_LOCATION = 48,
2974 WSI_TOKEN_HTTP_CONTENT_RANGE = 49,
2975 WSI_TOKEN_HTTP_ETAG = 50,
2976 WSI_TOKEN_HTTP_EXPECT = 51,
2977 WSI_TOKEN_HTTP_EXPIRES = 52,
2978 WSI_TOKEN_HTTP_FROM = 53,
2979 WSI_TOKEN_HTTP_IF_MATCH = 54,
2980 WSI_TOKEN_HTTP_IF_RANGE = 55,
2981 WSI_TOKEN_HTTP_IF_UNMODIFIED_SINCE = 56,
2982 WSI_TOKEN_HTTP_LAST_MODIFIED = 57,
2983 WSI_TOKEN_HTTP_LINK = 58,
2984 WSI_TOKEN_HTTP_LOCATION = 59,
2985 WSI_TOKEN_HTTP_MAX_FORWARDS = 60,
2986 WSI_TOKEN_HTTP_PROXY_AUTHENTICATE = 61,
2987 WSI_TOKEN_HTTP_PROXY_AUTHORIZATION = 62,
2988 WSI_TOKEN_HTTP_REFRESH = 63,
2989 WSI_TOKEN_HTTP_RETRY_AFTER = 64,
2990 WSI_TOKEN_HTTP_SERVER = 65,
2991 WSI_TOKEN_HTTP_SET_COOKIE = 66,
2992 WSI_TOKEN_HTTP_STRICT_TRANSPORT_SECURITY = 67,
2993 WSI_TOKEN_HTTP_TRANSFER_ENCODING = 68,
2994 WSI_TOKEN_HTTP_USER_AGENT = 69,
2995 WSI_TOKEN_HTTP_VARY = 70,
2996 WSI_TOKEN_HTTP_VIA = 71,
2997 WSI_TOKEN_HTTP_WWW_AUTHENTICATE = 72,
2999 WSI_TOKEN_PATCH_URI = 73,
3000 WSI_TOKEN_PUT_URI = 74,
3001 WSI_TOKEN_DELETE_URI = 75,
3003 WSI_TOKEN_HTTP_URI_ARGS = 76,
3004 WSI_TOKEN_PROXY = 77,
3005 WSI_TOKEN_HTTP_X_REAL_IP = 78,
3006 WSI_TOKEN_HTTP1_0 = 79,
3007 WSI_TOKEN_X_FORWARDED_FOR = 80,
3008 WSI_TOKEN_CONNECT = 81,
3009 /****** add new things just above ---^ ******/
3011 /* use token storage to stash these internally, not for
3014 _WSI_TOKEN_CLIENT_SENT_PROTOCOLS,
3015 _WSI_TOKEN_CLIENT_PEER_ADDRESS,
3016 _WSI_TOKEN_CLIENT_URI,
3017 _WSI_TOKEN_CLIENT_HOST,
3018 _WSI_TOKEN_CLIENT_ORIGIN,
3019 _WSI_TOKEN_CLIENT_METHOD,
3021 /* always last real token index*/
3024 /* parser state additions, no storage associated */
3025 WSI_TOKEN_NAME_PART,
3027 WSI_TOKEN_SKIPPING_SAW_CR,
3028 WSI_PARSING_COMPLETE,
3029 WSI_INIT_TOKEN_MUXURL,
3032 struct lws_token_limits {
3033 unsigned short token_limit[WSI_TOKEN_COUNT]; /**< max chars for this token */
3037 * lws_token_to_string() - returns a textual representation of a hdr token index
3039 * \param: token index
3041 LWS_VISIBLE LWS_EXTERN const unsigned char *
3042 lws_token_to_string(enum lws_token_indexes token);
3046 * lws_hdr_total_length: report length of all fragments of a header totalled up
3047 * The returned length does not include the space for a
3050 * \param wsi: websocket connection
3051 * \param h: which header index we are interested in
3053 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3054 lws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h);
3057 * lws_hdr_fragment_length: report length of a single fragment of a header
3058 * The returned length does not include the space for a
3061 * \param wsi: websocket connection
3062 * \param h: which header index we are interested in
3063 * \param frag_idx: which fragment of h we want to get the length of
3065 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3066 lws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx);
3069 * lws_hdr_copy() - copy a single fragment of the given header to a buffer
3070 * The buffer length len must include space for an additional
3071 * terminating '\0', or it will fail returning -1.
3073 * \param wsi: websocket connection
3074 * \param dest: destination buffer
3075 * \param len: length of destination buffer
3076 * \param h: which header index we are interested in
3078 * copies the whole, aggregated header, even if it was delivered in
3079 * several actual headers piece by piece
3081 LWS_VISIBLE LWS_EXTERN int
3082 lws_hdr_copy(struct lws *wsi, char *dest, int len, enum lws_token_indexes h);
3085 * lws_hdr_copy_fragment() - copy a single fragment of the given header to a buffer
3086 * The buffer length len must include space for an additional
3087 * terminating '\0', or it will fail returning -1.
3088 * If the requested fragment index is not present, it fails
3091 * \param wsi: websocket connection
3092 * \param dest: destination buffer
3093 * \param len: length of destination buffer
3094 * \param h: which header index we are interested in
3095 * \param frag_idx: which fragment of h we want to copy
3097 * Normally this is only useful
3098 * to parse URI arguments like ?x=1&y=2, token index WSI_TOKEN_HTTP_URI_ARGS
3099 * fragment 0 will contain "x=1" and fragment 1 "y=2"
3101 LWS_VISIBLE LWS_EXTERN int
3102 lws_hdr_copy_fragment(struct lws *wsi, char *dest, int len,
3103 enum lws_token_indexes h, int frag_idx);
3106 * lws_get_urlarg_by_name() - return pointer to arg value if present
3107 * \param wsi: the connection to check
3108 * \param name: the arg name, like "token="
3109 * \param buf: the buffer to receive the urlarg (including the name= part)
3110 * \param len: the length of the buffer to receive the urlarg
3112 * Returns NULL if not found or a pointer inside buf to just after the
3115 LWS_VISIBLE LWS_EXTERN const char *
3116 lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len);
3119 /*! \defgroup HTTP-headers-create HTTP headers: create
3121 * ## HTTP headers: Create
3123 * These apis allow you to create HTTP response headers in a way compatible with
3124 * both HTTP/1.x and HTTP/2.
3126 * They each append to a buffer taking care about the buffer end, which is
3127 * passed in as a pointer. When data is written to the buffer, the current
3128 * position p is updated accordingly.
3130 * All of these apis are LWS_WARN_UNUSED_RESULT as they can run out of space
3131 * and fail with nonzero return.
3135 #define LWSAHH_CODE_MASK ((1 << 16) - 1)
3136 #define LWSAHH_FLAG_NO_SERVER_NAME (1 << 30)
3139 * lws_add_http_header_status() - add the HTTP response status code
3141 * \param wsi: the connection to check
3142 * \param code: an HTTP code like 200, 404 etc (see enum http_status)
3143 * \param p: pointer to current position in buffer pointer
3144 * \param end: pointer to end of buffer
3146 * Adds the initial response code, so should be called first.
3148 * Code may additionally take OR'd flags:
3150 * LWSAHH_FLAG_NO_SERVER_NAME: don't apply server name header this time
3152 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3153 lws_add_http_header_status(struct lws *wsi,
3154 unsigned int code, unsigned char **p,
3155 unsigned char *end);
3157 * lws_add_http_header_by_name() - append named header and value
3159 * \param wsi: the connection to check
3160 * \param name: the hdr name, like "my-header"
3161 * \param value: the value after the = for this header
3162 * \param length: the length of the value
3163 * \param p: pointer to current position in buffer pointer
3164 * \param end: pointer to end of buffer
3166 * Appends name: value to the headers
3168 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3169 lws_add_http_header_by_name(struct lws *wsi, const unsigned char *name,
3170 const unsigned char *value, int length,
3171 unsigned char **p, unsigned char *end);
3173 * lws_add_http_header_by_token() - append given header and value
3175 * \param wsi: the connection to check
3176 * \param token: the token index for the hdr
3177 * \param value: the value after the = for this header
3178 * \param length: the length of the value
3179 * \param p: pointer to current position in buffer pointer
3180 * \param end: pointer to end of buffer
3182 * Appends name=value to the headers, but is able to take advantage of better
3183 * HTTP/2 coding mechanisms where possible.
3185 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3186 lws_add_http_header_by_token(struct lws *wsi, enum lws_token_indexes token,
3187 const unsigned char *value, int length,
3188 unsigned char **p, unsigned char *end);
3190 * lws_add_http_header_content_length() - append content-length helper
3192 * \param wsi: the connection to check
3193 * \param content_length: the content length to use
3194 * \param p: pointer to current position in buffer pointer
3195 * \param end: pointer to end of buffer
3197 * Appends content-length: content_length to the headers
3199 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3200 lws_add_http_header_content_length(struct lws *wsi,
3201 lws_filepos_t content_length,
3202 unsigned char **p, unsigned char *end);
3204 * lws_finalize_http_header() - terminate header block
3206 * \param wsi: the connection to check
3207 * \param p: pointer to current position in buffer pointer
3208 * \param end: pointer to end of buffer
3210 * Indicates no more headers will be added
3212 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3213 lws_finalize_http_header(struct lws *wsi, unsigned char **p,
3214 unsigned char *end);
3217 /** \defgroup form-parsing Form Parsing
3219 * ##POSTed form parsing functions
3221 * These lws_spa (stateful post arguments) apis let you parse and urldecode
3222 * POSTed form arguments, both using simple urlencoded and multipart transfer
3225 * It's capable of handling file uploads as well a named input parsing,
3226 * and the apis are the same for both form upload styles.
3228 * You feed it a list of parameter names and it creates pointers to the
3229 * urldecoded arguments: file upload parameters pass the file data in chunks to
3230 * a user-supplied callback as they come.
3232 * Since it's stateful, it handles the incoming data needing more than one
3233 * POST_BODY callback and has no limit on uploaded file size.
3237 /** enum lws_spa_fileupload_states */
3238 enum lws_spa_fileupload_states {
3240 /**< a chunk of file content has arrived */
3241 LWS_UFS_FINAL_CONTENT,
3242 /**< the last chunk (possibly zero length) of file content has arrived */
3244 /**< a new file is starting to arrive */
3248 * lws_spa_fileupload_cb() - callback to receive file upload data
3250 * \param data: opt_data pointer set in lws_spa_create
3251 * \param name: name of the form field being uploaded
3252 * \param filename: original filename from client
3253 * \param buf: start of data to receive
3254 * \param len: length of data to receive
3255 * \param state: information about how this call relates to file
3257 * Notice name and filename shouldn't be trusted, as they are passed from
3258 * HTTP provided by the client.
3260 typedef int (*lws_spa_fileupload_cb)(void *data, const char *name,
3261 const char *filename, char *buf, int len,
3262 enum lws_spa_fileupload_states state);
3264 /** struct lws_spa - opaque urldecode parser capable of handling multipart
3265 * and file uploads */
3269 * lws_spa_create() - create urldecode parser
3271 * \param wsi: lws connection (used to find Content Type)
3272 * \param param_names: array of form parameter names, like "username"
3273 * \param count_params: count of param_names
3274 * \param max_storage: total amount of form parameter values we can store
3275 * \param opt_cb: NULL, or callback to receive file upload data.
3276 * \param opt_data: NULL, or user pointer provided to opt_cb.
3278 * Creates a urldecode parser and initializes it.
3280 * opt_cb can be NULL if you just want normal name=value parsing, however
3281 * if one or more entries in your form are bulk data (file transfer), you
3282 * can provide this callback and filter on the name callback parameter to
3283 * treat that urldecoded data separately. The callback should return -1
3284 * in case of fatal error, and 0 if OK.
3286 LWS_VISIBLE LWS_EXTERN struct lws_spa *
3287 lws_spa_create(struct lws *wsi, const char * const *param_names,
3288 int count_params, int max_storage, lws_spa_fileupload_cb opt_cb,
3292 * lws_spa_process() - parses a chunk of input data
3294 * \param spa: the parser object previously created
3295 * \param in: incoming, urlencoded data
3296 * \param len: count of bytes valid at \param in
3298 LWS_VISIBLE LWS_EXTERN int
3299 lws_spa_process(struct lws_spa *spa, const char *in, int len);
3302 * lws_spa_finalize() - indicate incoming data completed
3304 * \param spa: the parser object previously created
3306 LWS_VISIBLE LWS_EXTERN int
3307 lws_spa_finalize(struct lws_spa *spa);
3310 * lws_spa_get_length() - return length of parameter value
3312 * \param spa: the parser object previously created
3313 * \param n: parameter ordinal to return length of value for
3315 LWS_VISIBLE LWS_EXTERN int
3316 lws_spa_get_length(struct lws_spa *spa, int n);
3319 * lws_spa_get_string() - return pointer to parameter value
3320 * \param spa: the parser object previously created
3321 * \param n: parameter ordinal to return pointer to value for
3323 LWS_VISIBLE LWS_EXTERN const char *
3324 lws_spa_get_string(struct lws_spa *spa, int n);
3327 * lws_spa_destroy() - destroy parser object
3329 * \param spa: the parser object previously created
3331 LWS_VISIBLE LWS_EXTERN int
3332 lws_spa_destroy(struct lws_spa *spa);
3335 /*! \defgroup urlendec Urlencode and Urldecode
3338 * ##HTML chunked Substitution
3340 * APIs for receiving chunks of text, replacing a set of variable names via
3341 * a callback, and then prepending and appending HTML chunked encoding
3347 * lws_urlencode() - like strncpy but with urlencoding
3349 * \param escaped: output buffer
3350 * \param string: input buffer ('/0' terminated)
3351 * \param len: output buffer max length
3353 * Because urlencoding expands the output string, it's not
3354 * possible to do it in-place, ie, with escaped == string
3356 LWS_VISIBLE LWS_EXTERN const char *
3357 lws_urlencode(char *escaped, const char *string, int len);
3362 * This simple urldecode only operates until the first '\0' and requires the
3363 * data to exist all at once
3366 * lws_urldecode() - like strncpy but with urldecoding
3368 * \param string: output buffer
3369 * \param escaped: input buffer ('\0' terminated)
3370 * \param len: output buffer max length
3372 * This is only useful for '\0' terminated strings
3374 * Since urldecoding only shrinks the output string, it is possible to
3375 * do it in-place, ie, string == escaped
3377 LWS_VISIBLE LWS_EXTERN int
3378 lws_urldecode(char *string, const char *escaped, int len);
3381 * lws_return_http_status() - Return simple http status
3382 * \param wsi: Websocket instance (available from user callback)
3383 * \param code: Status index, eg, 404
3384 * \param html_body: User-readable HTML description < 1KB, or NULL
3386 * Helper to report HTTP errors back to the client cleanly and
3389 LWS_VISIBLE LWS_EXTERN int
3390 lws_return_http_status(struct lws *wsi, unsigned int code,
3391 const char *html_body);
3394 * lws_http_redirect() - write http redirect into buffer
3396 * \param wsi: websocket connection
3397 * \param code: HTTP response code (eg, 301)
3398 * \param loc: where to redirect to
3399 * \param len: length of loc
3400 * \param p: pointer current position in buffer (updated as we write)
3401 * \param end: pointer to end of buffer
3403 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3404 lws_http_redirect(struct lws *wsi, int code, const unsigned char *loc, int len,
3405 unsigned char **p, unsigned char *end);
3408 * lws_http_transaction_completed() - wait for new http transaction or close
3409 * \param wsi: websocket connection
3411 * Returns 1 if the HTTP connection must close now
3412 * Returns 0 and resets connection to wait for new HTTP header /
3413 * transaction if possible
3415 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3416 lws_http_transaction_completed(struct lws *wsi);
3419 /*! \defgroup pur Sanitize / purify SQL and JSON helpers
3421 * ##Sanitize / purify SQL and JSON helpers
3423 * APIs for escaping untrusted JSON and SQL safely before use
3428 * lws_sql_purify() - like strncpy but with escaping for sql quotes
3430 * \param escaped: output buffer
3431 * \param string: input buffer ('/0' terminated)
3432 * \param len: output buffer max length
3434 * Because escaping expands the output string, it's not
3435 * possible to do it in-place, ie, with escaped == string
3437 LWS_VISIBLE LWS_EXTERN const char *
3438 lws_sql_purify(char *escaped, const char *string, int len);
3441 * lws_json_purify() - like strncpy but with escaping for json chars
3443 * \param escaped: output buffer
3444 * \param string: input buffer ('/0' terminated)
3445 * \param len: output buffer max length
3447 * Because escaping expands the output string, it's not
3448 * possible to do it in-place, ie, with escaped == string
3450 LWS_VISIBLE LWS_EXTERN const char *
3451 lws_json_purify(char *escaped, const char *string, int len);
3454 /*! \defgroup ev libev helpers
3458 * APIs specific to libev event loop itegration
3462 #ifdef LWS_USE_LIBEV
3463 typedef void (lws_ev_signal_cb_t)(EV_P_ struct ev_signal *w, int revents);
3465 LWS_VISIBLE LWS_EXTERN int
3466 lws_ev_sigint_cfg(struct lws_context *context, int use_ev_sigint,
3467 lws_ev_signal_cb_t *cb);
3469 LWS_VISIBLE LWS_EXTERN int
3470 lws_ev_initloop(struct lws_context *context, struct ev_loop *loop, int tsi);
3472 LWS_VISIBLE LWS_EXTERN void
3473 lws_ev_sigint_cb(struct ev_loop *loop, struct ev_signal *watcher, int revents);
3474 #endif /* LWS_USE_LIBEV */
3478 /*! \defgroup uv libuv helpers
3482 * APIs specific to libuv event loop itegration
3485 #ifdef LWS_USE_LIBUV
3486 LWS_VISIBLE LWS_EXTERN int
3487 lws_uv_sigint_cfg(struct lws_context *context, int use_uv_sigint,
3490 LWS_VISIBLE LWS_EXTERN void
3491 lws_libuv_run(const struct lws_context *context, int tsi);
3493 LWS_VISIBLE LWS_EXTERN void
3494 lws_libuv_stop(struct lws_context *context);
3496 LWS_VISIBLE LWS_EXTERN void
3497 lws_libuv_stop_without_kill(const struct lws_context *context, int tsi);
3499 LWS_VISIBLE LWS_EXTERN int
3500 lws_uv_initloop(struct lws_context *context, uv_loop_t *loop, int tsi);
3502 LWS_VISIBLE LWS_EXTERN uv_loop_t *
3503 lws_uv_getloop(struct lws_context *context, int tsi);
3505 LWS_VISIBLE LWS_EXTERN void
3506 lws_uv_sigint_cb(uv_signal_t *watcher, int signum);
3507 #endif /* LWS_USE_LIBUV */
3510 /*! \defgroup event libevent helpers
3512 * ##libevent helpers
3514 * APIs specific to libevent event loop itegration
3518 #ifdef LWS_USE_LIBEVENT
3519 typedef void (lws_event_signal_cb_t) (evutil_socket_t sock_fd, short revents,
3522 LWS_VISIBLE LWS_EXTERN int
3523 lws_event_sigint_cfg(struct lws_context *context, int use_event_sigint,
3524 lws_event_signal_cb_t cb);
3526 LWS_VISIBLE LWS_EXTERN int
3527 lws_event_initloop(struct lws_context *context, struct event_base *loop,
3530 LWS_VISIBLE LWS_EXTERN void
3531 lws_event_sigint_cb(evutil_socket_t sock_fd, short revents,
3533 #endif /* LWS_USE_LIBEVENT */
3537 /*! \defgroup timeout Connection timeouts
3539 APIs related to setting connection timeouts
3544 * NOTE: These public enums are part of the abi. If you want to add one,
3545 * add it at where specified so existing users are unaffected.
3547 enum pending_timeout {
3548 NO_PENDING_TIMEOUT = 0,
3549 PENDING_TIMEOUT_AWAITING_PROXY_RESPONSE = 1,
3550 PENDING_TIMEOUT_AWAITING_CONNECT_RESPONSE = 2,
3551 PENDING_TIMEOUT_ESTABLISH_WITH_SERVER = 3,
3552 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE = 4,
3553 PENDING_TIMEOUT_AWAITING_PING = 5,
3554 PENDING_TIMEOUT_CLOSE_ACK = 6,
3555 PENDING_TIMEOUT_AWAITING_EXTENSION_CONNECT_RESPONSE = 7,
3556 PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE = 8,
3557 PENDING_TIMEOUT_SSL_ACCEPT = 9,
3558 PENDING_TIMEOUT_HTTP_CONTENT = 10,
3559 PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND = 11,
3560 PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE = 12,
3561 PENDING_TIMEOUT_SHUTDOWN_FLUSH = 13,
3562 PENDING_TIMEOUT_CGI = 14,
3563 PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE = 15,
3564 PENDING_TIMEOUT_WS_PONG_CHECK_SEND_PING = 16,
3565 PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG = 17,
3566 PENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD = 18,
3567 PENDING_TIMEOUT_AWAITING_SOCKS_GREETING_REPLY = 19,
3568 PENDING_TIMEOUT_AWAITING_SOCKS_CONNECT_REPLY = 20,
3569 PENDING_TIMEOUT_AWAITING_SOCKS_AUTH_REPLY = 21,
3571 /****** add new things just above ---^ ******/
3575 * lws_set_timeout() - marks the wsi as subject to a timeout
3577 * You will not need this unless you are doing something special
3579 * \param wsi: Websocket connection instance
3580 * \param reason: timeout reason
3581 * \param secs: how many seconds
3583 LWS_VISIBLE LWS_EXTERN void
3584 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs);
3587 /*! \defgroup sending-data Sending data
3589 APIs related to writing data on a connection
3592 #if !defined(LWS_SIZEOFPTR)
3593 #define LWS_SIZEOFPTR (sizeof (void *))
3595 #if !defined(u_int64_t)
3596 #define u_int64_t unsigned long long
3599 #if defined(__x86_64__)
3600 #define _LWS_PAD_SIZE 16 /* Intel recommended for best performance */
3602 #define _LWS_PAD_SIZE LWS_SIZEOFPTR /* Size of a pointer on the target arch */
3604 #define _LWS_PAD(n) (((n) % _LWS_PAD_SIZE) ? \
3605 ((n) + (_LWS_PAD_SIZE - ((n) % _LWS_PAD_SIZE))) : (n))
3606 #define LWS_PRE _LWS_PAD(4 + 10)
3607 /* used prior to 1.7 and retained for backward compatibility */
3608 #define LWS_SEND_BUFFER_PRE_PADDING LWS_PRE
3609 #define LWS_SEND_BUFFER_POST_PADDING 0
3612 * NOTE: These public enums are part of the abi. If you want to add one,
3613 * add it at where specified so existing users are unaffected.
3615 enum lws_write_protocol {
3617 /**< Send a ws TEXT message,the pointer must have LWS_PRE valid
3618 * memory behind it. The receiver expects only valid utf-8 in the
3620 LWS_WRITE_BINARY = 1,
3621 /**< Send a ws BINARY message, the pointer must have LWS_PRE valid
3622 * memory behind it. Any sequence of bytes is valid */
3623 LWS_WRITE_CONTINUATION = 2,
3624 /**< Continue a previous ws message, the pointer must have LWS_PRE valid
3625 * memory behind it */
3627 /**< Send HTTP content */
3629 /* LWS_WRITE_CLOSE is handled by lws_close_reason() */
3633 /* Same as write_http but we know this write ends the transaction */
3634 LWS_WRITE_HTTP_FINAL = 7,
3638 LWS_WRITE_HTTP_HEADERS = 8,
3639 /**< Send http headers (http2 encodes this payload and LWS_WRITE_HTTP
3640 * payload differently, http 1.x links also handle this correctly. so
3641 * to be compatible with both in the future,header response part should
3642 * be sent using this regardless of http version expected)
3645 /****** add new things just above ---^ ******/
3649 LWS_WRITE_NO_FIN = 0x40,
3650 /**< This part of the message is not the end of the message */
3652 LWS_WRITE_CLIENT_IGNORE_XOR_MASK = 0x80
3653 /**< client packet payload goes out on wire unmunged
3654 * only useful for security tests since normal servers cannot
3655 * decode the content if used */
3660 * lws_write() - Apply protocol then write data to client
3661 * \param wsi: Websocket instance (available from user callback)
3662 * \param buf: The data to send. For data being sent on a websocket
3663 * connection (ie, not default http), this buffer MUST have
3664 * LWS_PRE bytes valid BEFORE the pointer.
3665 * This is so the protocol header data can be added in-situ.
3666 * \param len: Count of the data bytes in the payload starting from buf
3667 * \param protocol: Use LWS_WRITE_HTTP to reply to an http connection, and one
3668 * of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
3669 * data on a websockets connection. Remember to allow the extra
3670 * bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
3673 * This function provides the way to issue data back to the client
3674 * for both http and websocket protocols.
3678 * When sending with websocket protocol
3682 * LWS_WRITE_CONTINUATION,
3686 * the send buffer has to have LWS_PRE bytes valid BEFORE
3687 * the buffer pointer you pass to lws_write().
3689 * This allows us to add protocol info before and after the data, and send as
3690 * one packet on the network without payload copying, for maximum efficiency.
3692 * So for example you need this kind of code to use lws_write with a
3695 * char buf[LWS_PRE + 128];
3697 * // fill your part of the buffer... for example here it's all zeros
3698 * memset(&buf[LWS_PRE], 0, 128);
3700 * lws_write(wsi, &buf[LWS_PRE], 128, LWS_WRITE_TEXT);
3702 * When sending HTTP, with
3705 * LWS_WRITE_HTTP_HEADERS
3706 * LWS_WRITE_HTTP_FINAL
3708 * there is no protocol data prepended, and don't need to take care about the
3709 * LWS_PRE bytes valid before the buffer pointer.
3711 * LWS_PRE is at least the frame nonce + 2 header + 8 length
3712 * LWS_SEND_BUFFER_POST_PADDING is deprecated, it's now 0 and can be left off.
3713 * The example apps no longer use it.
3715 * Pad LWS_PRE to the CPU word size, so that word references
3716 * to the address immediately after the padding won't cause an unaligned access
3717 * error. Sometimes for performance reasons the recommended padding is even
3718 * larger than sizeof(void *).
3720 * In the case of sending using websocket protocol, be sure to allocate
3721 * valid storage before and after buf as explained above. This scheme
3722 * allows maximum efficiency of sending data and protocol in a single
3723 * packet while not burdening the user code with any protocol knowledge.
3725 * Return may be -1 for a fatal error needing connection close, or the
3726 * number of bytes sent.
3731 * The OS may not accept everything you asked to write on the connection.
3733 * Posix defines POLLOUT indication from poll() to show that the connection
3734 * will accept more write data, but it doesn't specifiy how much. It may just
3735 * accept one byte of whatever you wanted to send.
3737 * LWS will buffer the remainder automatically, and send it out autonomously.
3739 * During that time, WRITABLE callbacks will be suppressed.
3741 * This is to handle corner cases where unexpectedly the OS refuses what we
3742 * usually expect it to accept. You should try to send in chunks that are
3743 * almost always accepted in order to avoid the inefficiency of the buffering.
3745 LWS_VISIBLE LWS_EXTERN int
3746 lws_write(struct lws *wsi, unsigned char *buf, size_t len,
3747 enum lws_write_protocol protocol);
3749 /* helper for case where buffer may be const */
3750 #define lws_write_http(wsi, buf, len) \
3751 lws_write(wsi, (unsigned char *)(buf), len, LWS_WRITE_HTTP)
3754 /** \defgroup callback-when-writeable Callback when writeable
3756 * ##Callback When Writeable
3758 * lws can only write data on a connection when it is able to accept more
3759 * data without blocking.
3761 * So a basic requirement is we should only use the lws_write() apis when the
3762 * connection we want to write on says that he can accept more data.
3764 * When lws cannot complete your send at the time, it will buffer the data
3765 * and send it in the background, suppressing any further WRITEABLE callbacks
3766 * on that connection until it completes. So it is important to write new
3767 * things in a new writeable callback.
3769 * These apis reflect the various ways we can indicate we would like to be
3770 * called back when one or more connections is writeable.
3775 * lws_callback_on_writable() - Request a callback when this socket
3776 * becomes able to be written to without
3779 * \param wsi: Websocket connection instance to get callback for
3781 * - Which: only this wsi
3782 * - When: when the individual connection becomes writeable
3783 * - What: LWS_CALLBACK_*_WRITEABLE
3785 LWS_VISIBLE LWS_EXTERN int
3786 lws_callback_on_writable(struct lws *wsi);
3789 * lws_callback_on_writable_all_protocol() - Request a callback for all
3790 * connections on same vhost using the given protocol when it
3791 * becomes possible to write to each socket without
3794 * \param context: lws_context
3795 * \param protocol: Protocol whose connections will get callbacks
3797 * - Which: connections using this protocol on ANY VHOST
3798 * - When: when the individual connection becomes writeable
3799 * - What: LWS_CALLBACK_*_WRITEABLE
3801 LWS_VISIBLE LWS_EXTERN int
3802 lws_callback_on_writable_all_protocol(const struct lws_context *context,
3803 const struct lws_protocols *protocol);
3806 * lws_callback_on_writable_all_protocol_vhost() - Request a callback for
3807 * all connections using the given protocol when it
3808 * becomes possible to write to each socket without
3811 * \param vhost: Only consider connections on this lws_vhost
3812 * \param protocol: Protocol whose connections will get callbacks
3814 * - Which: connections using this protocol on GIVEN VHOST ONLY
3815 * - When: when the individual connection becomes writeable
3816 * - What: LWS_CALLBACK_*_WRITEABLE
3818 LWS_VISIBLE LWS_EXTERN int
3819 lws_callback_on_writable_all_protocol_vhost(const struct lws_vhost *vhost,
3820 const struct lws_protocols *protocol);
3823 * lws_callback_all_protocol() - Callback all connections using
3824 * the given protocol with the given reason
3826 * \param context: lws_context
3827 * \param protocol: Protocol whose connections will get callbacks
3828 * \param reason: Callback reason index
3830 * - Which: connections using this protocol on ALL VHOSTS
3831 * - When: before returning
3834 * This isn't normally what you want... normally any update of connection-
3835 * specific information can wait until a network-related callback like rx,
3836 * writable, or close.
3838 LWS_VISIBLE LWS_EXTERN int
3839 lws_callback_all_protocol(struct lws_context *context,
3840 const struct lws_protocols *protocol, int reason);
3843 * lws_callback_all_protocol_vhost() - Callback all connections using
3844 * the given protocol with the given reason
3846 * \param vh: Vhost whose connections will get callbacks
3847 * \param protocol: Which protocol to match
3848 * \param reason: Callback reason index
3850 * - Which: connections using this protocol on GIVEN VHOST ONLY
3854 LWS_VISIBLE LWS_EXTERN int
3855 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
3856 const struct lws_protocols *protocol, int reason);
3859 * lws_callback_vhost_protocols() - Callback all protocols enabled on a vhost
3860 * with the given reason
3862 * \param wsi: wsi whose vhost will get callbacks
3863 * \param reason: Callback reason index
3864 * \param in: in argument to callback
3865 * \param len: len argument to callback
3867 * - Which: connections using this protocol on same VHOST as wsi ONLY
3871 LWS_VISIBLE LWS_EXTERN int
3872 lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len);
3874 LWS_VISIBLE LWS_EXTERN int
3875 lws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason,
3876 void *user, void *in, size_t len);
3879 * lws_get_socket_fd() - returns the socket file descriptor
3881 * You will not need this unless you are doing something special
3883 * \param wsi: Websocket connection instance
3885 LWS_VISIBLE LWS_EXTERN int
3886 lws_get_socket_fd(struct lws *wsi);
3889 * lws_get_peer_write_allowance() - get the amount of data writeable to peer
3892 * \param wsi: Websocket connection instance
3894 * if the protocol does not have any guidance, returns -1. Currently only
3895 * http2 connections get send window information from this API. But your code
3896 * should use it so it can work properly with any protocol.
3898 * If nonzero return is the amount of payload data the peer or intermediary has
3899 * reported it has buffer space for. That has NO relationship with the amount
3900 * of buffer space your OS can accept on this connection for a write action.
3902 * This number represents the maximum you could send to the peer or intermediary
3903 * on this connection right now without the protocol complaining.
3905 * lws manages accounting for send window updates and payload writes
3906 * automatically, so this number reflects the situation at the peer or
3907 * intermediary dynamically.
3909 LWS_VISIBLE LWS_EXTERN size_t
3910 lws_get_peer_write_allowance(struct lws *wsi);
3914 * lws_rx_flow_control() - Enable and disable socket servicing for
3917 * If the output side of a server process becomes choked, this allows flow
3918 * control for the input side.
3920 * \param wsi: Websocket connection instance to get callback for
3921 * \param enable: 0 = disable read servicing for this connection, 1 = enable
3923 LWS_VISIBLE LWS_EXTERN int
3924 lws_rx_flow_control(struct lws *wsi, int enable);
3927 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
3929 * When the user server code realizes it can accept more input, it can
3930 * call this to have the RX flow restriction removed from all connections using
3931 * the given protocol.
3932 * \param context: lws_context
3933 * \param protocol: all connections using this protocol will be allowed to receive
3935 LWS_VISIBLE LWS_EXTERN void
3936 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
3937 const struct lws_protocols *protocol);
3940 * lws_remaining_packet_payload() - Bytes to come before "overall"
3941 * rx packet is complete
3942 * \param wsi: Websocket instance (available from user callback)
3944 * This function is intended to be called from the callback if the
3945 * user code is interested in "complete packets" from the client.
3946 * libwebsockets just passes through payload as it comes and issues a buffer
3947 * additionally when it hits a built-in limit. The LWS_CALLBACK_RECEIVE
3948 * callback handler can use this API to find out if the buffer it has just
3949 * been given is the last piece of a "complete packet" from the client --
3950 * when that is the case lws_remaining_packet_payload() will return
3953 * Many protocols won't care becuse their packets are always small.
3955 LWS_VISIBLE LWS_EXTERN size_t
3956 lws_remaining_packet_payload(struct lws *wsi);
3959 /** \defgroup sock-adopt Socket adoption helpers
3960 * ##Socket adoption helpers
3962 * When integrating with an external app with its own event loop, these can
3963 * be used to accept connections from someone else's listening socket.
3965 * When using lws own event loop, these are not needed.
3970 * lws_adopt_socket() - adopt foreign socket as if listen socket accepted it
3971 * for the default vhost of context.
3972 * \param context: lws context
3973 * \param accept_fd: fd of already-accepted socket to adopt
3975 * Either returns new wsi bound to accept_fd, or closes accept_fd and
3976 * returns NULL, having cleaned up any new wsi pieces.
3978 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
3979 * to ws or just serve http.
3981 LWS_VISIBLE LWS_EXTERN struct lws *
3982 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd);
3984 * lws_adopt_socket_vhost() - adopt foreign socket as if listen socket accepted it
3986 * \param vhost: lws vhost
3987 * \param accept_fd: fd of already-accepted socket to adopt
3989 * Either returns new wsi bound to accept_fd, or closes accept_fd and
3990 * returns NULL, having cleaned up any new wsi pieces.
3992 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
3993 * to ws or just serve http.
3995 LWS_VISIBLE LWS_EXTERN struct lws *
3996 lws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd);
3999 LWS_ADOPT_RAW_FILE_DESC = 0, /* convenience constant */
4000 LWS_ADOPT_HTTP = 1, /* flag: absent implies RAW */
4001 LWS_ADOPT_SOCKET = 2, /* flag: absent implies file descr */
4002 LWS_ADOPT_ALLOW_SSL = 4 /* flag: if set requires LWS_ADOPT_SOCKET */
4003 } lws_adoption_type;
4006 lws_sockfd_type sockfd;
4007 lws_filefd_type filefd;
4008 } lws_sock_file_fd_type;
4011 * lws_adopt_descriptor_vhost() - adopt foreign socket or file descriptor
4012 * if socket descriptor, should already have been accepted from listen socket
4014 * \param vhost: lws vhost
4015 * \param type: OR-ed combinations of lws_adoption_type flags
4016 * \param fd: union with either .sockfd or .filefd set
4017 * \param vh_prot_name: NULL or vh protocol name to bind raw connection to
4018 * \param parent: NULL or struct lws to attach new_wsi to as a child
4020 * Either returns new wsi bound to accept_fd, or closes accept_fd and
4021 * returns NULL, having cleaned up any new wsi pieces.
4023 * If LWS_ADOPT_SOCKET is set, LWS adopts the socket in http serving mode, it's
4024 * ready to accept an upgrade to ws or just serve http.
4026 * parent may be NULL, if given it should be an existing wsi that will become the
4027 * parent of the new wsi created by this call.
4029 LWS_VISIBLE struct lws *
4030 lws_adopt_descriptor_vhost(struct lws_vhost *vh, lws_adoption_type type,
4031 lws_sock_file_fd_type fd, const char *vh_prot_name,
4032 struct lws *parent);
4035 * lws_adopt_socket_readbuf() - adopt foreign socket and first rx as if listen socket accepted it
4036 * for the default vhost of context.
4037 * \param context: lws context
4038 * \param accept_fd: fd of already-accepted socket to adopt
4039 * \param readbuf: NULL or pointer to data that must be drained before reading from
4041 * \param len: The length of the data held at \param readbuf
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 * If your external code did not already read from the socket, you can use
4050 * lws_adopt_socket() instead.
4052 * This api is guaranteed to use the data at \param readbuf first, before reading from
4055 * readbuf is limited to the size of the ah rx buf, currently 2048 bytes.
4057 LWS_VISIBLE LWS_EXTERN struct lws *
4058 lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
4059 const char *readbuf, size_t len);
4061 * lws_adopt_socket_vhost_readbuf() - adopt foreign socket and first rx as if listen socket
4062 * accepted it for vhost.
4063 * \param vhost: lws vhost
4064 * \param accept_fd: fd of already-accepted socket to adopt
4065 * \param readbuf: NULL or pointer to data that must be drained before reading from
4067 * \param len: The length of the data held at \param readbuf
4069 * Either returns new wsi bound to accept_fd, or closes accept_fd and
4070 * returns NULL, having cleaned up any new wsi pieces.
4072 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
4073 * to ws or just serve http.
4075 * If your external code did not already read from the socket, you can use
4076 * lws_adopt_socket() instead.
4078 * This api is guaranteed to use the data at \param readbuf first, before reading from
4081 * readbuf is limited to the size of the ah rx buf, currently 2048 bytes.
4083 LWS_VISIBLE LWS_EXTERN struct lws *
4084 lws_adopt_socket_vhost_readbuf(struct lws_vhost *vhost, lws_sockfd_type accept_fd,
4085 const char *readbuf, size_t len);
4088 /** \defgroup net Network related helper APIs
4089 * ##Network related helper APIs
4091 * These wrap miscellaneous useful network-related functions
4096 * lws_canonical_hostname() - returns this host's hostname
4098 * This is typically used by client code to fill in the host parameter
4099 * when making a client connection. You can only call it after the context
4102 * \param context: Websocket context
4104 LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
4105 lws_canonical_hostname(struct lws_context *context);
4108 * lws_get_peer_addresses() - Get client address information
4109 * \param wsi: Local struct lws associated with
4110 * \param fd: Connection socket descriptor
4111 * \param name: Buffer to take client address name
4112 * \param name_len: Length of client address name buffer
4113 * \param rip: Buffer to take client address IP dotted quad
4114 * \param rip_len: Length of client address IP buffer
4116 * This function fills in name and rip with the name and IP of
4117 * the client connected with socket descriptor fd. Names may be
4118 * truncated if there is not enough room. If either cannot be
4119 * determined, they will be returned as valid zero-length strings.
4121 LWS_VISIBLE LWS_EXTERN void
4122 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
4123 int name_len, char *rip, int rip_len);
4126 * lws_get_peer_simple() - Get client address information without RDNS
4128 * \param wsi: Local struct lws associated with
4129 * \param name: Buffer to take client address name
4130 * \param namelen: Length of client address name buffer
4132 * This provides a 123.123.123.123 type IP address in name from the
4133 * peer that has connected to wsi
4135 LWS_VISIBLE LWS_EXTERN const char *
4136 lws_get_peer_simple(struct lws *wsi, char *name, int namelen);
4137 #if !defined(LWS_WITH_ESP8266) && !defined(LWS_WITH_ESP32)
4139 * lws_interface_to_sa() - Convert interface name or IP to sockaddr struct
4141 * \param ipv6: Allow IPV6 addresses
4142 * \param ifname: Interface name or IP
4143 * \param addr: struct sockaddr_in * to be written
4144 * \param addrlen: Length of addr
4146 * This converts a textual network interface name to a sockaddr usable by
4147 * other network functions
4149 LWS_VISIBLE LWS_EXTERN int
4150 lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr,
4155 /** \defgroup misc Miscellaneous APIs
4156 * ##Miscellaneous APIs
4158 * Various APIs outside of other categories
4163 * lws_snprintf(): snprintf that truncates the returned length too
4165 * \param str: destination buffer
4166 * \param size: bytes left in destination buffer
4167 * \param format: format string
4168 * \param ...: args for format
4170 * This lets you correctly truncate buffers by concatenating lengths, if you
4171 * reach the limit the reported length doesn't exceed the limit.
4173 LWS_VISIBLE LWS_EXTERN int
4174 lws_snprintf(char *str, size_t size, const char *format, ...) LWS_FORMAT(3);
4177 * lws_get_random(): fill a buffer with platform random data
4179 * \param context: the lws context
4180 * \param buf: buffer to fill
4181 * \param len: how much to fill
4183 * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
4184 * it's interested to see if the frame it's dealing with was sent in binary
4187 LWS_VISIBLE LWS_EXTERN int
4188 lws_get_random(struct lws_context *context, void *buf, int len);
4190 * lws_daemonize(): make current process run in the background
4192 * \param _lock_path: the filepath to write the lock file
4194 * Spawn lws as a background process, taking care of various things
4196 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4197 lws_daemonize(const char *_lock_path);
4199 * lws_get_library_version(): return string describing the version of lws
4201 * On unix, also includes the git describe
4203 LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
4204 lws_get_library_version(void);
4207 * lws_wsi_user() - get the user data associated with the connection
4208 * \param wsi: lws connection
4210 * Not normally needed since it's passed into the callback
4212 LWS_VISIBLE LWS_EXTERN void *
4213 lws_wsi_user(struct lws *wsi);
4216 * lws_wsi_set_user() - set the user data associated with the client connection
4217 * \param wsi: lws connection
4218 * \param user: user data
4220 * By default lws allocates this and it's not legal to externally set it
4221 * yourself. However client connections may have it set externally when the
4222 * connection is created... if so, this api can be used to modify it at
4223 * runtime additionally.
4225 LWS_VISIBLE LWS_EXTERN void
4226 lws_set_wsi_user(struct lws *wsi, void *user);
4229 * lws_parse_uri: cut up prot:/ads:port/path into pieces
4230 * Notice it does so by dropping '\0' into input string
4231 * and the leading / on the path is consequently lost
4233 * \param p: incoming uri string.. will get written to
4234 * \param prot: result pointer for protocol part (https://)
4235 * \param ads: result pointer for address part
4236 * \param port: result pointer for port part
4237 * \param path: result pointer for path part
4239 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4240 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
4244 * lws_now_secs(): return seconds since 1970-1-1
4246 LWS_VISIBLE LWS_EXTERN unsigned long
4250 * lws_get_context - Allow geting lws_context from a Websocket connection
4253 * With this function, users can access context in the callback function.
4254 * Otherwise users may have to declare context as a global variable.
4256 * \param wsi: Websocket connection instance
4258 LWS_VISIBLE LWS_EXTERN struct lws_context * LWS_WARN_UNUSED_RESULT
4259 lws_get_context(const struct lws *wsi);
4262 * lws_get_count_threads(): how many service threads the context uses
4264 * \param context: the lws context
4266 * By default this is always 1, if you asked for more than lws can handle it
4267 * will clip the number of threads. So you can use this to find out how many
4268 * threads are actually in use.
4270 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4271 lws_get_count_threads(struct lws_context *context);
4274 * lws_get_parent() - get parent wsi or NULL
4275 * \param wsi: lws connection
4277 * Specialized wsi like cgi stdin/out/err are associated to a parent wsi,
4278 * this allows you to get their parent.
4280 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
4281 lws_get_parent(const struct lws *wsi);
4284 * lws_get_child() - get child wsi or NULL
4285 * \param wsi: lws connection
4287 * Allows you to find a related wsi from the parent wsi.
4289 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
4290 lws_get_child(const struct lws *wsi);
4294 * \deprecated DEPRECATED Note: this is not normally needed as a user api.
4295 * It's provided in case it is
4296 * useful when integrating with other app poll loop service code.
4298 LWS_VISIBLE LWS_EXTERN int
4299 lws_read(struct lws *wsi, unsigned char *buf, size_t len);
4302 * lws_set_allocator() - custom allocator support
4306 * Allows you to replace the allocator (and deallocator) used by lws
4308 LWS_VISIBLE LWS_EXTERN void
4309 lws_set_allocator(void *(*realloc)(void *ptr, size_t size));
4312 /** \defgroup wsstatus Websocket status APIs
4313 * ##Websocket connection status APIs
4315 * These provide information about ws connection or message status
4319 * lws_send_pipe_choked() - tests if socket is writable or not
4320 * \param wsi: lws connection
4322 * Allows you to check if you can write more on the socket
4324 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4325 lws_send_pipe_choked(struct lws *wsi);
4328 * lws_is_final_fragment() - tests if last part of ws message
4329 * \param wsi: lws connection
4331 LWS_VISIBLE LWS_EXTERN int
4332 lws_is_final_fragment(struct lws *wsi);
4335 * lws_get_reserved_bits() - access reserved bits of ws frame
4336 * \param wsi: lws connection
4338 LWS_VISIBLE LWS_EXTERN unsigned char
4339 lws_get_reserved_bits(struct lws *wsi);
4342 * lws_partial_buffered() - find out if lws buffered the last write
4343 * \param wsi: websocket connection to check
4345 * Returns 1 if you cannot use lws_write because the last
4346 * write on this connection is still buffered, and can't be cleared without
4347 * returning to the service loop and waiting for the connection to be
4350 * If you will try to do >1 lws_write call inside a single
4351 * WRITEABLE callback, you must check this after every write and bail if
4352 * set, ask for a new writeable callback and continue writing from there.
4354 * This is never set at the start of a writeable callback, but any write
4357 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4358 lws_partial_buffered(struct lws *wsi);
4361 * lws_frame_is_binary(): true if the current frame was sent in binary mode
4363 * \param wsi: the connection we are inquiring about
4365 * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
4366 * it's interested to see if the frame it's dealing with was sent in binary
4369 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4370 lws_frame_is_binary(struct lws *wsi);
4373 * lws_is_ssl() - Find out if connection is using SSL
4374 * \param wsi: websocket connection to check
4376 * Returns 0 if the connection is not using SSL, 1 if using SSL and
4377 * using verified cert, and 2 if using SSL but the cert was not
4378 * checked (appears for client wsi told to skip check on connection)
4380 LWS_VISIBLE LWS_EXTERN int
4381 lws_is_ssl(struct lws *wsi);
4383 * lws_is_cgi() - find out if this wsi is running a cgi process
4384 * \param wsi: lws connection
4386 LWS_VISIBLE LWS_EXTERN int
4387 lws_is_cgi(struct lws *wsi);
4389 #ifdef LWS_OPENSSL_SUPPORT
4391 * lws_get_ssl() - Return wsi's SSL context structure
4392 * \param wsi: websocket connection
4394 * Returns pointer to the SSL library's context structure
4396 LWS_VISIBLE LWS_EXTERN SSL*
4397 lws_get_ssl(struct lws *wsi);
4402 /** \defgroup sha SHA and B64 helpers
4403 * ##SHA and B64 helpers
4405 * These provide SHA-1 and B64 helper apis
4408 #ifdef LWS_SHA1_USE_OPENSSL_NAME
4409 #define lws_SHA1 SHA1
4412 * lws_SHA1(): make a SHA-1 digest of a buffer
4414 * \param d: incoming buffer
4415 * \param n: length of incoming buffer
4416 * \param md: buffer for message digest (must be >= 20 bytes)
4418 * Reduces any size buffer into a 20-byte SHA-1 hash.
4420 LWS_VISIBLE LWS_EXTERN unsigned char *
4421 lws_SHA1(const unsigned char *d, size_t n, unsigned char *md);
4424 * lws_b64_encode_string(): encode a string into base 64
4426 * \param in: incoming buffer
4427 * \param in_len: length of incoming buffer
4428 * \param out: result buffer
4429 * \param out_size: length of result buffer
4431 * Encodes a string using b64
4433 LWS_VISIBLE LWS_EXTERN int
4434 lws_b64_encode_string(const char *in, int in_len, char *out, int out_size);
4436 * lws_b64_decode_string(): decode a string from base 64
4438 * \param in: incoming buffer
4439 * \param out: result buffer
4440 * \param out_size: length of result buffer
4442 * Decodes a string using b64
4444 LWS_VISIBLE LWS_EXTERN int
4445 lws_b64_decode_string(const char *in, char *out, int out_size);
4449 /*! \defgroup cgi cgi handling
4453 * These functions allow low-level control over stdin/out/err of the cgi.
4455 * However for most cases, binding the cgi to http in and out, the default
4456 * lws implementation already does the right thing.
4459 enum lws_enum_stdinouterr {
4465 enum lws_cgi_hdr_state {
4477 struct lws_cgi_args {
4478 struct lws **stdwsi; /**< get fd with lws_get_socket_fd() */
4479 enum lws_enum_stdinouterr ch; /**< channel index */
4480 unsigned char *data; /**< for messages with payload */
4481 enum lws_cgi_hdr_state hdr_state; /**< track where we are in cgi headers */
4482 int len; /**< length */
4487 * lws_cgi: spawn network-connected cgi process
4489 * \param wsi: connection to own the process
4490 * \param exec_array: array of "exec-name" "arg1" ... "argn" NULL
4491 * \param script_uri_path_len: how many chars on the left of the uri are the path to the cgi
4492 * \param timeout_secs: seconds script should be allowed to run
4493 * \param mp_cgienv: pvo list with per-vhost cgi options to put in env
4495 LWS_VISIBLE LWS_EXTERN int
4496 lws_cgi(struct lws *wsi, const char * const *exec_array,
4497 int script_uri_path_len, int timeout_secs,
4498 const struct lws_protocol_vhost_options *mp_cgienv);
4501 * lws_cgi_write_split_stdout_headers: write cgi output accounting for header part
4503 * \param wsi: connection to own the process
4505 LWS_VISIBLE LWS_EXTERN int
4506 lws_cgi_write_split_stdout_headers(struct lws *wsi);
4509 * lws_cgi_kill: terminate cgi process associated with wsi
4511 * \param wsi: connection to own the process
4513 LWS_VISIBLE LWS_EXTERN int
4514 lws_cgi_kill(struct lws *wsi);
4519 /*! \defgroup fops file operation wrapping
4521 * ##File operation wrapping
4523 * Use these helper functions if you want to access a file from the perspective
4524 * of a specific wsi, which is usually the case. If you just want contextless
4525 * file access, use the fops callbacks directly with NULL wsi instead of these
4528 * If so, then it calls the platform handler or user overrides where present
4529 * (as defined in info->fops)
4531 * The advantage from all this is user code can be portable for file operations
4532 * without having to deal with differences between platforms.
4536 /** struct lws_plat_file_ops - Platform-specific file operations
4538 * These provide platform-agnostic ways to deal with filesystem access in the
4539 * library and in the user code.
4542 #if defined(LWS_WITH_ESP32)
4543 /* sdk preprocessor defs? compiler issue? gets confused with member names */
4544 #define LWS_FOP_OPEN _open
4545 #define LWS_FOP_CLOSE _close
4546 #define LWS_FOP_SEEK_CUR _seek_cur
4547 #define LWS_FOP_READ _read
4548 #define LWS_FOP_WRITE _write
4550 #define LWS_FOP_OPEN open
4551 #define LWS_FOP_CLOSE close
4552 #define LWS_FOP_SEEK_CUR seek_cur
4553 #define LWS_FOP_READ read
4554 #define LWS_FOP_WRITE write
4557 #define LWS_FOP_FLAGS_MASK ((1 << 23) - 1)
4558 #define LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP (1 << 24)
4559 #define LWS_FOP_FLAG_COMPR_IS_GZIP (1 << 25)
4560 #define LWS_FOP_FLAG_MOD_TIME_VALID (1 << 26)
4561 #define LWS_FOP_FLAG_VIRTUAL (1 << 27)
4563 struct lws_plat_file_ops;
4567 /**< real file descriptor related to the file... */
4568 const struct lws_plat_file_ops *fops;
4569 /**< fops that apply to this fop_fd */
4570 void *filesystem_priv;
4571 /**< ignored by lws; owned by the fops handlers */
4573 /**< generic "position in file" */
4575 /**< generic "length of file" */
4576 lws_fop_flags_t flags;
4577 /**< copy of the returned flags */
4579 /**< optional "modification time of file", only valid if .open()
4580 * set the LWS_FOP_FLAG_MOD_TIME_VALID flag */
4582 typedef struct lws_fop_fd *lws_fop_fd_t;
4584 struct lws_fops_index {
4585 const char *sig; /* NULL or vfs signature, eg, ".zip/" */
4586 uint8_t len; /* length of above string */
4589 struct lws_plat_file_ops {
4590 lws_fop_fd_t (*LWS_FOP_OPEN)(const struct lws_plat_file_ops *fops,
4591 const char *filename, const char *vpath,
4592 lws_fop_flags_t *flags);
4593 /**< Open file (always binary access if plat supports it)
4594 * vpath may be NULL, or if the fops understands it, the point at which
4595 * the filename's virtual part starts.
4596 * *flags & LWS_FOP_FLAGS_MASK should be set to O_RDONLY or O_RDWR.
4597 * If the file may be gzip-compressed,
4598 * LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP is set. If it actually is
4599 * gzip-compressed, then the open handler should OR
4600 * LWS_FOP_FLAG_COMPR_IS_GZIP on to *flags before returning.
4602 int (*LWS_FOP_CLOSE)(lws_fop_fd_t *fop_fd);
4603 /**< close file AND set the pointer to NULL */
4604 lws_fileofs_t (*LWS_FOP_SEEK_CUR)(lws_fop_fd_t fop_fd,
4605 lws_fileofs_t offset_from_cur_pos);
4606 /**< seek from current position */
4607 int (*LWS_FOP_READ)(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4608 uint8_t *buf, lws_filepos_t len);
4609 /**< Read from file, on exit *amount is set to amount actually read */
4610 int (*LWS_FOP_WRITE)(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4611 uint8_t *buf, lws_filepos_t len);
4612 /**< Write to file, on exit *amount is set to amount actually written */
4614 struct lws_fops_index fi[3];
4615 /**< vfs path signatures implying use of this fops */
4617 const struct lws_plat_file_ops *next;
4618 /**< NULL or next fops in list */
4620 /* Add new things just above here ---^
4621 * This is part of the ABI, don't needlessly break compatibility */
4625 * lws_get_fops() - get current file ops
4627 * \param context: context
4629 LWS_VISIBLE LWS_EXTERN struct lws_plat_file_ops * LWS_WARN_UNUSED_RESULT
4630 lws_get_fops(struct lws_context *context);
4631 LWS_VISIBLE LWS_EXTERN void
4632 lws_set_fops(struct lws_context *context, const struct lws_plat_file_ops *fops);
4634 * lws_vfs_tell() - get current file position
4636 * \param fop_fd: fop_fd we are asking about
4638 LWS_VISIBLE LWS_EXTERN lws_filepos_t LWS_WARN_UNUSED_RESULT
4639 lws_vfs_tell(lws_fop_fd_t fop_fd);
4641 * lws_vfs_get_length() - get current file total length in bytes
4643 * \param fop_fd: fop_fd we are asking about
4645 LWS_VISIBLE LWS_EXTERN lws_filepos_t LWS_WARN_UNUSED_RESULT
4646 lws_vfs_get_length(lws_fop_fd_t fop_fd);
4648 * lws_vfs_get_mod_time() - get time file last modified
4650 * \param fop_fd: fop_fd we are asking about
4652 LWS_VISIBLE LWS_EXTERN uint32_t LWS_WARN_UNUSED_RESULT
4653 lws_vfs_get_mod_time(lws_fop_fd_t fop_fd);
4655 * lws_vfs_file_seek_set() - seek relative to start of file
4657 * \param fop_fd: fop_fd we are seeking in
4658 * \param offset: offset from start of file
4660 LWS_VISIBLE LWS_EXTERN lws_fileofs_t
4661 lws_vfs_file_seek_set(lws_fop_fd_t fop_fd, lws_fileofs_t offset);
4663 * lws_vfs_file_seek_end() - seek relative to end of file
4665 * \param fop_fd: fop_fd we are seeking in
4666 * \param offset: offset from start of file
4668 LWS_VISIBLE LWS_EXTERN lws_fileofs_t
4669 lws_vfs_file_seek_end(lws_fop_fd_t fop_fd, lws_fileofs_t offset);
4671 extern struct lws_plat_file_ops fops_zip;
4674 * lws_plat_file_open() - open vfs filepath
4676 * \param fops: file ops struct that applies to this descriptor
4677 * \param vfs_path: filename to open
4678 * \param flags: pointer to open flags
4680 * The vfs_path is scanned for known fops signatures, and the open directed
4681 * to any matching fops open.
4683 * User code should use this api to perform vfs opens.
4685 * returns semi-opaque handle
4687 LWS_VISIBLE LWS_EXTERN lws_fop_fd_t LWS_WARN_UNUSED_RESULT
4688 lws_vfs_file_open(const struct lws_plat_file_ops *fops, const char *vfs_path,
4689 lws_fop_flags_t *flags);
4692 * lws_plat_file_close() - close file
4694 * \param fop_fd: file handle to close
4696 static LWS_INLINE int
4697 lws_vfs_file_close(lws_fop_fd_t *fop_fd)
4699 return (*fop_fd)->fops->LWS_FOP_CLOSE(fop_fd);
4703 * lws_plat_file_seek_cur() - close file
4706 * \param fop_fd: file handle
4707 * \param offset: position to seek to
4709 static LWS_INLINE lws_fileofs_t
4710 lws_vfs_file_seek_cur(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
4712 return fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, offset);
4715 * lws_plat_file_read() - read from file
4717 * \param fop_fd: file handle
4718 * \param amount: how much to read (rewritten by call)
4719 * \param buf: buffer to write to
4720 * \param len: max length
4722 static LWS_INLINE int LWS_WARN_UNUSED_RESULT
4723 lws_vfs_file_read(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4724 uint8_t *buf, lws_filepos_t len)
4726 return fop_fd->fops->LWS_FOP_READ(fop_fd, amount, buf, len);
4729 * lws_plat_file_write() - write from file
4731 * \param fop_fd: file handle
4732 * \param amount: how much to write (rewritten by call)
4733 * \param buf: buffer to read from
4734 * \param len: max length
4736 static LWS_INLINE int LWS_WARN_UNUSED_RESULT
4737 lws_vfs_file_write(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4738 uint8_t *buf, lws_filepos_t len)
4740 return fop_fd->fops->LWS_FOP_WRITE(fop_fd, amount, buf, len);
4743 /* these are the platform file operations implementations... they can
4744 * be called directly and used in fops arrays
4747 LWS_VISIBLE LWS_EXTERN lws_fop_fd_t
4748 _lws_plat_file_open(const struct lws_plat_file_ops *fops, const char *filename,
4749 const char *vpath, lws_fop_flags_t *flags);
4750 LWS_VISIBLE LWS_EXTERN int
4751 _lws_plat_file_close(lws_fop_fd_t *fop_fd);
4752 LWS_VISIBLE LWS_EXTERN lws_fileofs_t
4753 _lws_plat_file_seek_cur(lws_fop_fd_t fop_fd, lws_fileofs_t offset);
4754 LWS_VISIBLE LWS_EXTERN int
4755 _lws_plat_file_read(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4756 uint8_t *buf, lws_filepos_t len);
4757 LWS_VISIBLE LWS_EXTERN int
4758 _lws_plat_file_write(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4759 uint8_t *buf, lws_filepos_t len);
4761 LWS_VISIBLE LWS_EXTERN int
4762 lws_alloc_vfs_file(struct lws_context *context, const char *filename, uint8_t **buf,
4763 lws_filepos_t *amount);
4768 * ##SMTP related functions
4770 * These apis let you communicate with a local SMTP server to send email from
4771 * lws. It handles all the SMTP sequencing and protocol actions.
4773 * Your system should have postfix, sendmail or another MTA listening on port
4774 * 25 and able to send email using the "mail" commandline app. Usually distro
4775 * MTAs are configured for this by default.
4777 * It runs via its own libuv events if initialized (which requires giving it
4778 * a libuv loop to attach to).
4780 * It operates using three callbacks, on_next() queries if there is a new email
4781 * to send, on_get_body() asks for the body of the email, and on_sent() is
4782 * called after the email is successfully sent.
4786 * - create an lws_email struct
4788 * - initialize data, loop, the email_* strings, max_content_size and
4791 * - call lws_email_init()
4793 * When you have at least one email to send, call lws_email_check() to
4794 * schedule starting to send it.
4797 #ifdef LWS_WITH_SMTP
4799 /** enum lwsgs_smtp_states - where we are in SMTP protocol sequence */
4800 enum lwsgs_smtp_states {
4801 LGSSMTP_IDLE, /**< awaiting new email */
4802 LGSSMTP_CONNECTING, /**< opening tcp connection to MTA */
4803 LGSSMTP_CONNECTED, /**< tcp connection to MTA is connected */
4804 LGSSMTP_SENT_HELO, /**< sent the HELO */
4805 LGSSMTP_SENT_FROM, /**< sent FROM */
4806 LGSSMTP_SENT_TO, /**< sent TO */
4807 LGSSMTP_SENT_DATA, /**< sent DATA request */
4808 LGSSMTP_SENT_BODY, /**< sent the email body */
4809 LGSSMTP_SENT_QUIT, /**< sent the session quit */
4812 /** struct lws_email - abstract context for performing SMTP operations */
4815 /**< opaque pointer set by user code and available to the callbacks */
4817 /**< the libuv loop we will work on */
4819 char email_smtp_ip[32]; /**< Fill before init, eg, "127.0.0.1" */
4820 char email_helo[32]; /**< Fill before init, eg, "myserver.com" */
4821 char email_from[100]; /**< Fill before init or on_next */
4822 char email_to[100]; /**< Fill before init or on_next */
4824 unsigned int max_content_size;
4825 /**< largest possible email body size */
4827 /* Fill all the callbacks before init */
4829 int (*on_next)(struct lws_email *email);
4830 /**< (Fill in before calling lws_email_init)
4831 * called when idle, 0 = another email to send, nonzero is idle.
4832 * If you return 0, all of the email_* char arrays must be set
4833 * to something useful. */
4834 int (*on_sent)(struct lws_email *email);
4835 /**< (Fill in before calling lws_email_init)
4836 * called when transfer of the email to the SMTP server was
4837 * successful, your callback would remove the current email
4839 int (*on_get_body)(struct lws_email *email, char *buf, int len);
4840 /**< (Fill in before calling lws_email_init)
4841 * called when the body part of the queued email is about to be
4842 * sent to the SMTP server. */
4845 /* private things */
4846 uv_timer_t timeout_email; /**< private */
4847 enum lwsgs_smtp_states estate; /**< private */
4848 uv_connect_t email_connect_req; /**< private */
4849 uv_tcp_t email_client; /**< private */
4850 time_t email_connect_started; /**< private */
4851 char email_buf[256]; /**< private */
4852 char *content; /**< private */
4856 * lws_email_init() - Initialize a struct lws_email
4858 * \param email: struct lws_email to init
4859 * \param loop: libuv loop to use
4860 * \param max_content: max email content size
4862 * Prepares a struct lws_email for use ending SMTP
4864 LWS_VISIBLE LWS_EXTERN int
4865 lws_email_init(struct lws_email *email, uv_loop_t *loop, int max_content);
4868 * lws_email_check() - Request check for new email
4870 * \param email: struct lws_email context to check
4872 * Schedules a check for new emails in 1s... call this when you have queued an
4875 LWS_VISIBLE LWS_EXTERN void
4876 lws_email_check(struct lws_email *email);
4878 * lws_email_destroy() - stop using the struct lws_email
4880 * \param email: the struct lws_email context
4882 * Stop sending email using email and free allocations
4884 LWS_VISIBLE LWS_EXTERN void
4885 lws_email_destroy(struct lws_email *email);
4891 * Stats are all uint64_t numbers that start at 0.
4892 * Index names here have the convention
4896 * _MS_ millisecond count
4900 LWSSTATS_C_CONNECTIONS, /**< count incoming connections */
4901 LWSSTATS_C_API_CLOSE, /**< count calls to close api */
4902 LWSSTATS_C_API_READ, /**< count calls to read from socket api */
4903 LWSSTATS_C_API_LWS_WRITE, /**< count calls to lws_write API */
4904 LWSSTATS_C_API_WRITE, /**< count calls to write API */
4905 LWSSTATS_C_WRITE_PARTIALS, /**< count of partial writes */
4906 LWSSTATS_C_WRITEABLE_CB_REQ, /**< count of writable callback requests */
4907 LWSSTATS_C_WRITEABLE_CB_EFF_REQ, /**< count of effective writable callback requests */
4908 LWSSTATS_C_WRITEABLE_CB, /**< count of writable callbacks */
4909 LWSSTATS_C_SSL_CONNECTIONS_FAILED, /**< count of failed SSL connections */
4910 LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED, /**< count of accepted SSL connections */
4911 LWSSTATS_C_SSL_CONNS_HAD_RX, /**< count of accepted SSL conns that have had some RX */
4912 LWSSTATS_C_TIMEOUTS, /**< count of timed-out connections */
4913 LWSSTATS_C_SERVICE_ENTRY, /**< count of entries to lws service loop */
4914 LWSSTATS_B_READ, /**< aggregate bytes read */
4915 LWSSTATS_B_WRITE, /**< aggregate bytes written */
4916 LWSSTATS_B_PARTIALS_ACCEPTED_PARTS, /**< aggreate of size of accepted write data from new partials */
4917 LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY, /**< aggregate delay in accepting connection */
4918 LWSSTATS_MS_WRITABLE_DELAY, /**< aggregate delay between asking for writable and getting cb */
4919 LWSSTATS_MS_WORST_WRITABLE_DELAY, /**< single worst delay between asking for writable and getting cb */
4920 LWSSTATS_MS_SSL_RX_DELAY, /**< aggregate delay between ssl accept complete and first RX */
4922 /* Add new things just above here ---^
4923 * This is part of the ABI, don't needlessly break compatibility */
4927 #if defined(LWS_WITH_STATS)
4929 LWS_VISIBLE LWS_EXTERN uint64_t
4930 lws_stats_get(struct lws_context *context, int index);
4931 LWS_VISIBLE LWS_EXTERN void
4932 lws_stats_log_dump(struct lws_context *context);
4934 static LWS_INLINE uint64_t
4935 lws_stats_get(struct lws_context *context, int index) { return 0; }
4936 static LWS_INLINE void
4937 lws_stats_log_dump(struct lws_context *context) { }