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 */
106 #if defined(__NetBSD__) || defined(__FreeBSD__)
107 #include <netinet/in.h>
110 #define LWS_INLINE inline
111 #define LWS_O_RDONLY O_RDONLY
112 #define LWS_O_WRONLY O_WRONLY
113 #define LWS_O_CREAT O_CREAT
114 #define LWS_O_TRUNC O_TRUNC
116 #if !defined(LWS_WITH_ESP8266) && !defined(OPTEE_TA) && !defined(LWS_WITH_ESP32)
119 #define LWS_INVALID_FILE -1
121 #define getdtablesize() (30)
122 #if defined(LWS_WITH_ESP32)
123 #define LWS_INVALID_FILE NULL
125 #define LWS_INVALID_FILE NULL
129 #if defined(__GNUC__)
131 /* warn_unused_result attribute only supported by GCC 3.4 or later */
132 #if __GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
133 #define LWS_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
135 #define LWS_WARN_UNUSED_RESULT
138 #define LWS_VISIBLE __attribute__((visibility("default")))
139 #define LWS_WARN_DEPRECATED __attribute__ ((deprecated))
140 #define LWS_FORMAT(string_index) __attribute__ ((format(printf, string_index, string_index+1)))
143 #define LWS_WARN_UNUSED_RESULT
144 #define LWS_WARN_DEPRECATED
145 #define LWS_FORMAT(string_index)
148 #if defined(__ANDROID__)
150 #define getdtablesize() sysconf(_SC_OPEN_MAX)
157 #endif /* LWS_USE_LIBEV */
160 #ifdef LWS_HAVE_UV_VERSION_H
161 #include <uv-version.h>
163 #endif /* LWS_USE_LIBUV */
164 #ifdef LWS_USE_LIBEVENT
165 #include <event2/event.h>
166 #endif /* LWS_USE_LIBEVENT */
169 #define LWS_EXTERN extern
175 #if !defined(OPTEE_TA)
176 #include <sys/time.h>
181 #ifdef LWS_OPENSSL_SUPPORT
184 #ifdef USE_OLD_CYASSL
185 #include <cyassl/openssl/ssl.h>
186 #include <cyassl/error-ssl.h>
188 #include <wolfssl/openssl/ssl.h>
189 #include <wolfssl/error-ssl.h>
190 #endif /* not USE_OLD_CYASSL */
192 #include <openssl/ssl.h>
193 #if !defined(LWS_WITH_ESP32)
194 #include <openssl/err.h>
196 #endif /* not USE_WOLFSSL */
200 #define CONTEXT_PORT_NO_LISTEN -1
201 #define CONTEXT_PORT_NO_LISTEN_SERVER -2
203 /** \defgroup log Logging
207 * Lws provides flexible and filterable logging facilities, which can be
208 * used inside lws and in user code.
210 * Log categories may be individually filtered bitwise, and directed to built-in
211 * sinks for syslog-compatible logging, or a user-defined function.
215 enum lws_log_levels {
225 LLL_LATENCY = 1 << 9,
228 LLL_COUNT = 11 /* set to count of valid flags */
231 LWS_VISIBLE LWS_EXTERN void _lws_log(int filter, const char *format, ...) LWS_FORMAT(2);
232 LWS_VISIBLE LWS_EXTERN void _lws_logv(int filter, const char *format, va_list vl);
234 * lwsl_timestamp: generate logging timestamp string
236 * \param level: logging level
237 * \param p: char * buffer to take timestamp
238 * \param len: length of p
240 * returns length written in p
242 LWS_VISIBLE LWS_EXTERN int
243 lwsl_timestamp(int level, char *p, int len);
245 /* these guys are unconditionally included */
247 #define lwsl_err(...) _lws_log(LLL_ERR, __VA_ARGS__)
248 #define lwsl_user(...) _lws_log(LLL_USER, __VA_ARGS__)
250 #if !defined(LWS_WITH_NO_LOGS)
251 /* notice and warn are usually included by being compiled in */
252 #define lwsl_warn(...) _lws_log(LLL_WARN, __VA_ARGS__)
253 #define lwsl_notice(...) _lws_log(LLL_NOTICE, __VA_ARGS__)
256 * weaker logging can be deselected by telling CMake to build in RELEASE mode
257 * that gets rid of the overhead of checking while keeping _warn and _err
261 #if defined(LWS_WITH_ESP8266)
266 #if defined(LWS_WITH_NO_LOGS)
267 /* notice, warn and log are always compiled in */
268 #define lwsl_warn(...) _lws_log(LLL_WARN, __VA_ARGS__)
269 #define lwsl_notice(...) _lws_log(LLL_NOTICE, __VA_ARGS__)
271 #define lwsl_info(...) _lws_log(LLL_INFO, __VA_ARGS__)
272 #define lwsl_debug(...) _lws_log(LLL_DEBUG, __VA_ARGS__)
273 #define lwsl_parser(...) _lws_log(LLL_PARSER, __VA_ARGS__)
274 #define lwsl_header(...) _lws_log(LLL_HEADER, __VA_ARGS__)
275 #define lwsl_ext(...) _lws_log(LLL_EXT, __VA_ARGS__)
276 #define lwsl_client(...) _lws_log(LLL_CLIENT, __VA_ARGS__)
277 #define lwsl_latency(...) _lws_log(LLL_LATENCY, __VA_ARGS__)
279 * lwsl_hexdump() - helper to hexdump a buffer (DEBUG builds only)
281 * \param buf: buffer start to dump
282 * \param len: length of buffer to dump
284 LWS_VISIBLE LWS_EXTERN void lwsl_hexdump(void *buf, size_t len);
287 #if defined(LWS_WITH_NO_LOGS)
288 #define lwsl_warn(...) do {} while(0)
289 #define lwsl_notice(...) do {} while(0)
291 #define lwsl_info(...) do {} while(0)
292 #define lwsl_debug(...) do {} while(0)
293 #define lwsl_parser(...) do {} while(0)
294 #define lwsl_header(...) do {} while(0)
295 #define lwsl_ext(...) do {} while(0)
296 #define lwsl_client(...) do {} while(0)
297 #define lwsl_latency(...) do {} while(0)
298 #define lwsl_hexdump(a, b)
302 static LWS_INLINE int lws_is_be(void) {
303 const int probe = ~0xff;
305 return *(const char *)&probe;
309 * lws_set_log_level() - Set the logging bitfield
310 * \param level: OR together the LLL_ debug contexts you want output from
311 * \param log_emit_function: NULL to leave it as it is, or a user-supplied
312 * function to perform log string emission instead of
313 * the default stderr one.
315 * log level defaults to "err", "warn" and "notice" contexts enabled and
316 * emission on stderr.
318 LWS_VISIBLE LWS_EXTERN void
319 lws_set_log_level(int level,
320 void (*log_emit_function)(int level, const char *line));
323 * lwsl_emit_syslog() - helper log emit function writes to system log
325 * \param level: one of LLL_ log level indexes
326 * \param line: log string
328 * You use this by passing the function pointer to lws_set_log_level(), to set
329 * it as the log emit function, it is not called directly.
331 LWS_VISIBLE LWS_EXTERN void
332 lwsl_emit_syslog(int level, const char *line);
335 * lwsl_visible() - returns true if the log level should be printed
337 * \param level: one of LLL_ log level indexes
339 * This is useful if you have to do work to generate the log content, you
340 * can skip the work if the log level used to print it is not actually
341 * enabled at runtime.
343 LWS_VISIBLE LWS_EXTERN int
344 lwsl_visible(int level);
351 #ifndef lws_container_of
352 #define lws_container_of(P,T,M) ((T *)((char *)(P) - offsetof(T, M)))
358 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
361 /* api change list for user code to test against */
363 #define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_ARG
365 /* the struct lws_protocols has the id field present */
366 #define LWS_FEATURE_PROTOCOLS_HAS_ID_FIELD
368 /* you can call lws_get_peer_write_allowance */
369 #define LWS_FEATURE_PROTOCOLS_HAS_PEER_WRITE_ALLOWANCE
371 /* extra parameter introduced in 917f43ab821 */
372 #define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_LEN
374 /* File operations stuff exists */
375 #define LWS_FEATURE_FOPS
379 typedef SOCKET lws_sockfd_type;
380 typedef HANDLE lws_filefd_type;
381 #define lws_sockfd_valid(sfd) (!!sfd)
383 lws_sockfd_type fd; /**< file descriptor */
384 SHORT events; /**< which events to respond to */
385 SHORT revents; /**< which events happened */
387 #define LWS_POLLHUP (FD_CLOSE)
388 #define LWS_POLLIN (FD_READ | FD_ACCEPT)
389 #define LWS_POLLOUT (FD_WRITE)
393 #if defined(LWS_WITH_ESP8266)
395 #include <user_interface.h>
398 typedef struct espconn * lws_sockfd_type;
399 typedef void * lws_filefd_type;
400 #define lws_sockfd_valid(sfd) (!!sfd)
402 lws_sockfd_type fd; /**< fd related to */
403 short events; /**< which POLL... events to respond to */
404 short revents; /**< which POLL... events occurred */
406 #define POLLIN 0x0001
407 #define POLLPRI 0x0002
408 #define POLLOUT 0x0004
409 #define POLLERR 0x0008
410 #define POLLHUP 0x0010
411 #define POLLNVAL 0x0020
415 lws_sockfd_type esp8266_create_tcp_listen_socket(struct lws_vhost *vh);
416 void esp8266_tcp_stream_accept(lws_sockfd_type fd, struct lws *wsi);
422 int ets_snprintf(char *str, size_t size, const char *format, ...) LWS_FORMAT(3);
423 #define snprintf ets_snprintf
425 typedef os_timer_t uv_timer_t;
426 typedef void uv_cb_t(uv_timer_t *);
428 void os_timer_disarm(void *);
429 void os_timer_setfn(os_timer_t *, os_timer_func_t *, void *);
431 void ets_timer_arm_new(os_timer_t *, int, int, int);
433 //void os_timer_arm(os_timer_t *, int, int);
435 #define UV_VERSION_MAJOR 1
437 #define lws_uv_getloop(a, b) (NULL)
439 static inline void uv_timer_init(void *l, uv_timer_t *t)
442 memset(t, 0, sizeof(*t));
446 static inline void uv_timer_start(uv_timer_t *t, uv_cb_t *cb, int first, int rep)
448 os_timer_setfn(t, (os_timer_func_t *)cb, t);
450 os_timer_arm(t, first, !!rep);
453 static inline void uv_timer_stop(uv_timer_t *t)
459 #if defined(LWS_WITH_ESP32)
461 typedef int lws_sockfd_type;
462 typedef int lws_filefd_type;
463 #define lws_sockfd_valid(sfd) (sfd >= 0)
465 lws_sockfd_type fd; /**< fd related to */
466 short events; /**< which POLL... events to respond to */
467 short revents; /**< which POLL... events occurred */
469 #define POLLIN 0x0001
470 #define POLLPRI 0x0002
471 #define POLLOUT 0x0004
472 #define POLLERR 0x0008
473 #define POLLHUP 0x0010
474 #define POLLNVAL 0x0020
476 #include <freertos/FreeRTOS.h>
477 #include <freertos/event_groups.h>
479 #include "esp_wifi.h"
480 #include "esp_system.h"
481 #include "esp_event.h"
482 #include "esp_event_loop.h"
484 #include "driver/gpio.h"
485 #include "esp_spi_flash.h"
486 #include "freertos/timers.h"
488 #if !defined(CONFIG_FREERTOS_HZ)
489 #define CONFIG_FREERTOS_HZ 100
492 typedef TimerHandle_t uv_timer_t;
493 typedef void uv_cb_t(uv_timer_t *);
494 typedef void * uv_handle_t;
496 struct timer_mapping {
501 #define UV_VERSION_MAJOR 1
503 #define lws_uv_getloop(a, b) (NULL)
505 static inline void uv_timer_init(void *l, uv_timer_t *t)
511 extern void esp32_uvtimer_cb(TimerHandle_t t);
513 static inline void uv_timer_start(uv_timer_t *t, uv_cb_t *cb, int first, int rep)
515 struct timer_mapping *tm = (struct timer_mapping *)malloc(sizeof(*tm));
523 *t = xTimerCreate("x", pdMS_TO_TICKS(first), !!rep, tm,
524 (TimerCallbackFunction_t)esp32_uvtimer_cb);
528 static inline void uv_timer_stop(uv_timer_t *t)
533 static inline void uv_close(uv_handle_t *h, void *v)
535 free(pvTimerGetTimerID((uv_timer_t)h));
536 xTimerDelete(*(uv_timer_t *)h, 0);
539 /* ESP32 helper declarations */
542 #include <esp_partition.h>
544 #define LWS_PLUGIN_STATIC
545 #define LWS_MAGIC_REBOOT_TYPE_ADS 0x50001ffc
546 #define LWS_MAGIC_REBOOT_TYPE_REQ_FACTORY 0xb00bcafe
547 #define LWS_MAGIC_REBOOT_TYPE_FORCED_FACTORY 0xfaceb00b
548 #define LWS_MAGIC_REBOOT_TYPE_FORCED_FACTORY_BUTTON 0xf0cedfac
551 /* user code provides these */
554 lws_esp32_identify_physical_device(void);
556 /* lws-plat-esp32 provides these */
558 typedef void (*lws_cb_scan_done)(uint16_t count, wifi_ap_record_t *recs, void *arg);
561 LWSESP32_GENLED__INIT,
562 LWSESP32_GENLED__LOST_NETWORK,
563 LWSESP32_GENLED__NO_NETWORK,
564 LWSESP32_GENLED__CONN_AP,
565 LWSESP32_GENLED__GOT_IP,
569 struct lws_group_member {
570 struct lws_group_member *next;
577 struct ip4_addr addr;
578 struct ip6_addr addrv6;
582 #define LWS_SYSTEM_GROUP_MEMBER_ADD 1
583 #define LWS_SYSTEM_GROUP_MEMBER_CHANGE 2
584 #define LWS_SYSTEM_GROUP_MEMBER_REMOVE 3
586 #define LWS_GROUP_FLAG_SELF 1
598 char password[4][32];
599 char active_ssid[32];
608 enum genled_state genled;
611 lws_cb_scan_done scan_consumer;
612 void *scan_consumer_arg;
613 struct lws_group_member *first;
614 int extant_group_members;
617 struct lws_esp32_image {
624 extern struct lws_esp32 lws_esp32;
627 lws_esp32_event_passthru(void *ctx, system_event_t *event);
629 lws_esp32_wlan_config(void);
631 lws_esp32_wlan_start_ap(void);
633 lws_esp32_wlan_start_station(void);
634 struct lws_context_creation_info;
636 lws_esp32_set_creation_defaults(struct lws_context_creation_info *info);
637 extern struct lws_context *
638 lws_esp32_init(struct lws_context_creation_info *);
640 lws_esp32_wlan_nvs_get(int retry);
642 lws_nvs_set_str(nvs_handle handle, const char* key, const char* value);
644 lws_esp32_restart_guided(uint32_t type);
645 extern const esp_partition_t *
646 lws_esp_ota_get_boot_partition(void);
648 lws_esp32_get_image_info(const esp_partition_t *part, struct lws_esp32_image *i, char *json, int json_len);
650 lws_esp32_leds_network_indication(void);
652 extern uint32_t lws_esp32_get_reboot_type(void);
653 extern uint16_t lws_esp32_sine_interp(int n);
655 /* required in external code by esp32 plat (may just return if no leds) */
656 extern void lws_esp32_leds_timer_cb(TimerHandle_t th);
658 typedef int lws_sockfd_type;
659 typedef int lws_filefd_type;
660 #define lws_sockfd_valid(sfd) (sfd >= 0)
664 #define lws_pollfd pollfd
665 #define LWS_POLLHUP (POLLHUP|POLLERR)
666 #define LWS_POLLIN (POLLIN)
667 #define LWS_POLLOUT (POLLOUT)
670 /** struct lws_pollargs - argument structure for all external poll related calls
671 * passed in via 'in' */
672 struct lws_pollargs {
673 lws_sockfd_type fd; /**< applicable socket descriptor */
674 int events; /**< the new event mask */
675 int prev_events; /**< the previous event mask */
679 struct lws_token_limits;
681 /*! \defgroup wsclose Websocket Close
683 * ##Websocket close frame control
685 * When we close a ws connection, we can send a reason code and a short
686 * UTF-8 description back with the close packet.
691 * NOTE: These public enums are part of the abi. If you want to add one,
692 * add it at where specified so existing users are unaffected.
694 /** enum lws_close_status - RFC6455 close status codes */
695 enum lws_close_status {
696 LWS_CLOSE_STATUS_NOSTATUS = 0,
697 LWS_CLOSE_STATUS_NORMAL = 1000,
698 /**< 1000 indicates a normal closure, meaning that the purpose for
699 which the connection was established has been fulfilled. */
700 LWS_CLOSE_STATUS_GOINGAWAY = 1001,
701 /**< 1001 indicates that an endpoint is "going away", such as a server
702 going down or a browser having navigated away from a page. */
703 LWS_CLOSE_STATUS_PROTOCOL_ERR = 1002,
704 /**< 1002 indicates that an endpoint is terminating the connection due
705 to a protocol error. */
706 LWS_CLOSE_STATUS_UNACCEPTABLE_OPCODE = 1003,
707 /**< 1003 indicates that an endpoint is terminating the connection
708 because it has received a type of data it cannot accept (e.g., an
709 endpoint that understands only text data MAY send this if it
710 receives a binary message). */
711 LWS_CLOSE_STATUS_RESERVED = 1004,
712 /**< Reserved. The specific meaning might be defined in the future. */
713 LWS_CLOSE_STATUS_NO_STATUS = 1005,
714 /**< 1005 is a reserved value and MUST NOT be set as a status code in a
715 Close control frame by an endpoint. It is designated for use in
716 applications expecting a status code to indicate that no status
717 code was actually present. */
718 LWS_CLOSE_STATUS_ABNORMAL_CLOSE = 1006,
719 /**< 1006 is a reserved value and MUST NOT be set as a status code in a
720 Close control frame by an endpoint. It is designated for use in
721 applications expecting a status code to indicate that the
722 connection was closed abnormally, e.g., without sending or
723 receiving a Close control frame. */
724 LWS_CLOSE_STATUS_INVALID_PAYLOAD = 1007,
725 /**< 1007 indicates that an endpoint is terminating the connection
726 because it has received data within a message that was not
727 consistent with the type of the message (e.g., non-UTF-8 [RFC3629]
728 data within a text message). */
729 LWS_CLOSE_STATUS_POLICY_VIOLATION = 1008,
730 /**< 1008 indicates that an endpoint is terminating the connection
731 because it has received a message that violates its policy. This
732 is a generic status code that can be returned when there is no
733 other more suitable status code (e.g., 1003 or 1009) or if there
734 is a need to hide specific details about the policy. */
735 LWS_CLOSE_STATUS_MESSAGE_TOO_LARGE = 1009,
736 /**< 1009 indicates that an endpoint is terminating the connection
737 because it has received a message that is too big for it to
739 LWS_CLOSE_STATUS_EXTENSION_REQUIRED = 1010,
740 /**< 1010 indicates that an endpoint (client) is terminating the
741 connection because it has expected the server to negotiate one or
742 more extension, but the server didn't return them in the response
743 message of the WebSocket handshake. The list of extensions that
744 are needed SHOULD appear in the /reason/ part of the Close frame.
745 Note that this status code is not used by the server, because it
746 can fail the WebSocket handshake instead */
747 LWS_CLOSE_STATUS_UNEXPECTED_CONDITION = 1011,
748 /**< 1011 indicates that a server is terminating the connection because
749 it encountered an unexpected condition that prevented it from
750 fulfilling the request. */
751 LWS_CLOSE_STATUS_TLS_FAILURE = 1015,
752 /**< 1015 is a reserved value and MUST NOT be set as a status code in a
753 Close control frame by an endpoint. It is designated for use in
754 applications expecting a status code to indicate that the
755 connection was closed due to a failure to perform a TLS handshake
756 (e.g., the server certificate can't be verified). */
758 /****** add new things just above ---^ ******/
760 LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY = 9999,
764 * lws_close_reason - Set reason and aux data to send with Close packet
765 * If you are going to return nonzero from the callback
766 * requesting the connection to close, you can optionally
767 * call this to set the reason the peer will be told if
770 * \param wsi: The websocket connection to set the close reason on
771 * \param status: A valid close status from websocket standard
772 * \param buf: NULL or buffer containing up to 124 bytes of auxiliary data
773 * \param len: Length of data in \param buf to send
775 LWS_VISIBLE LWS_EXTERN void
776 lws_close_reason(struct lws *wsi, enum lws_close_status status,
777 unsigned char *buf, size_t len);
783 /* needed even with extensions disabled for create context */
784 struct lws_extension;
786 /*! \defgroup usercb User Callback
788 * ##User protocol callback
790 * The protocol callback is the primary way lws interacts with
791 * user code. For one of a list of a few dozen reasons the callback gets
792 * called at some event to be handled.
794 * All of the events can be ignored, returning 0 is taken as "OK" and returning
795 * nonzero in most cases indicates that the connection should be closed.
801 * NOTE: These public enums are part of the abi. If you want to add one,
802 * add it at where specified so existing users are unaffected.
804 /** enum lws_callback_reasons - reason you're getting a protocol callback */
805 enum lws_callback_reasons {
806 LWS_CALLBACK_ESTABLISHED = 0,
807 /**< (VH) after the server completes a handshake with an incoming
808 * client. If you built the library with ssl support, in is a
809 * pointer to the ssl struct associated with the connection or NULL.*/
810 LWS_CALLBACK_CLIENT_CONNECTION_ERROR = 1,
811 /**< the request client connection has been unable to complete a
812 * handshake with the remote server. If in is non-NULL, you can
813 * find an error string of length len where it points to
815 * Diagnostic strings that may be returned include
817 * "getaddrinfo (ipv6) failed"
818 * "unknown address family"
819 * "getaddrinfo (ipv4) failed"
820 * "set socket opts failed"
821 * "insert wsi failed"
822 * "lws_ssl_client_connect1 failed"
823 * "lws_ssl_client_connect2 failed"
827 * "HS: Redirect code but no Location"
828 * "HS: URI did not parse"
829 * "HS: Redirect failed"
830 * "HS: Server did not return 200"
832 * "HS: disallowed by client filter"
833 * "HS: disallowed at ESTABLISHED"
834 * "HS: ACCEPT missing"
835 * "HS: ws upgrade response not 101"
836 * "HS: UPGRADE missing"
837 * "HS: Upgrade to something other than websocket"
838 * "HS: CONNECTION missing"
839 * "HS: UPGRADE malformed"
840 * "HS: PROTOCOL malformed"
841 * "HS: Cannot match protocol"
842 * "HS: EXT: list too big"
843 * "HS: EXT: failed setting defaults"
844 * "HS: EXT: failed parsing defaults"
845 * "HS: EXT: failed parsing options"
846 * "HS: EXT: Rejects server options"
847 * "HS: EXT: unknown ext"
848 * "HS: Accept hash wrong"
849 * "HS: Rejected by filter cb"
851 * "HS: SO_SNDBUF failed"
852 * "HS: Rejected at CLIENT_ESTABLISHED"
854 LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH = 2,
855 /**< this is the last chance for the client user code to examine the
856 * http headers and decide to reject the connection. If the
857 * content in the headers is interesting to the
858 * client (url, etc) it needs to copy it out at
859 * this point since it will be destroyed before
860 * the CLIENT_ESTABLISHED call */
861 LWS_CALLBACK_CLIENT_ESTABLISHED = 3,
862 /**< after your client connection completed
863 * a handshake with the remote server */
864 LWS_CALLBACK_CLOSED = 4,
865 /**< when the websocket session ends */
866 LWS_CALLBACK_CLOSED_HTTP = 5,
867 /**< when a HTTP (non-websocket) session ends */
868 LWS_CALLBACK_RECEIVE = 6,
869 /**< data has appeared for this server endpoint from a
870 * remote client, it can be found at *in and is
872 LWS_CALLBACK_RECEIVE_PONG = 7,
873 /**< servers receive PONG packets with this callback reason */
874 LWS_CALLBACK_CLIENT_RECEIVE = 8,
875 /**< data has appeared from the server for the client connection, it
876 * can be found at *in and is len bytes long */
877 LWS_CALLBACK_CLIENT_RECEIVE_PONG = 9,
878 /**< clients receive PONG packets with this callback reason */
879 LWS_CALLBACK_CLIENT_WRITEABLE = 10,
880 /**< If you call lws_callback_on_writable() on a connection, you will
881 * get one of these callbacks coming when the connection socket
882 * is able to accept another write packet without blocking.
883 * If it already was able to take another packet without blocking,
884 * you'll get this callback at the next call to the service loop
885 * function. Notice that CLIENTs get LWS_CALLBACK_CLIENT_WRITEABLE
886 * and servers get LWS_CALLBACK_SERVER_WRITEABLE. */
887 LWS_CALLBACK_SERVER_WRITEABLE = 11,
888 /**< See LWS_CALLBACK_CLIENT_WRITEABLE */
889 LWS_CALLBACK_HTTP = 12,
890 /**< an http request has come from a client that is not
891 * asking to upgrade the connection to a websocket
892 * one. This is a chance to serve http content,
893 * for example, to send a script to the client
894 * which will then open the websockets connection.
895 * in points to the URI path requested and
896 * lws_serve_http_file() makes it very
897 * simple to send back a file to the client.
898 * Normally after sending the file you are done
899 * with the http connection, since the rest of the
900 * activity will come by websockets from the script
901 * that was delivered by http, so you will want to
902 * return 1; to close and free up the connection. */
903 LWS_CALLBACK_HTTP_BODY = 13,
904 /**< the next len bytes data from the http
905 * request body HTTP connection is now available in in. */
906 LWS_CALLBACK_HTTP_BODY_COMPLETION = 14,
907 /**< the expected amount of http request body has been delivered */
908 LWS_CALLBACK_HTTP_FILE_COMPLETION = 15,
909 /**< a file requested to be sent down http link has completed. */
910 LWS_CALLBACK_HTTP_WRITEABLE = 16,
911 /**< you can write more down the http protocol link now. */
912 LWS_CALLBACK_FILTER_NETWORK_CONNECTION = 17,
913 /**< called when a client connects to
914 * the server at network level; the connection is accepted but then
915 * passed to this callback to decide whether to hang up immediately
916 * or not, based on the client IP. in contains the connection
917 * socket's descriptor. Since the client connection information is
918 * not available yet, wsi still pointing to the main server socket.
919 * Return non-zero to terminate the connection before sending or
920 * receiving anything. Because this happens immediately after the
921 * network connection from the client, there's no websocket protocol
922 * selected yet so this callback is issued only to protocol 0. */
923 LWS_CALLBACK_FILTER_HTTP_CONNECTION = 18,
924 /**< called when the request has
925 * been received and parsed from the client, but the response is
926 * not sent yet. Return non-zero to disallow the connection.
927 * user is a pointer to the connection user space allocation,
928 * in is the URI, eg, "/"
929 * In your handler you can use the public APIs
930 * lws_hdr_total_length() / lws_hdr_copy() to access all of the
931 * headers using the header enums lws_token_indexes from
932 * libwebsockets.h to check for and read the supported header
933 * presence and content before deciding to allow the http
934 * connection to proceed or to kill the connection. */
935 LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED = 19,
936 /**< A new client just had
937 * been connected, accepted, and instantiated into the pool. This
938 * callback allows setting any relevant property to it. Because this
939 * happens immediately after the instantiation of a new client,
940 * there's no websocket protocol selected yet so this callback is
941 * issued only to protocol 0. Only wsi is defined, pointing to the
942 * new client, and the return value is ignored. */
943 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION = 20,
944 /**< called when the handshake has
945 * been received and parsed from the client, but the response is
946 * not sent yet. Return non-zero to disallow the connection.
947 * user is a pointer to the connection user space allocation,
948 * in is the requested protocol name
949 * In your handler you can use the public APIs
950 * lws_hdr_total_length() / lws_hdr_copy() to access all of the
951 * headers using the header enums lws_token_indexes from
952 * libwebsockets.h to check for and read the supported header
953 * presence and content before deciding to allow the handshake
954 * to proceed or to kill the connection. */
955 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS = 21,
956 /**< if configured for
957 * including OpenSSL support, this callback allows your user code
958 * to perform extra SSL_CTX_load_verify_locations() or similar
959 * calls to direct OpenSSL where to find certificates the client
960 * can use to confirm the remote server identity. user is the
961 * OpenSSL SSL_CTX* */
962 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS = 22,
963 /**< if configured for
964 * including OpenSSL support, this callback allows your user code
965 * to load extra certifcates into the server which allow it to
966 * verify the validity of certificates returned by clients. user
967 * is the server's OpenSSL SSL_CTX* */
968 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION = 23,
969 /**< if the libwebsockets vhost was created with the option
970 * LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT, then this
971 * callback is generated during OpenSSL verification of the cert
972 * sent from the client. It is sent to protocol[0] callback as
973 * no protocol has been negotiated on the connection yet.
974 * Notice that the libwebsockets context and wsi are both NULL
975 * during this callback. See
976 * http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html
977 * to understand more detail about the OpenSSL callback that
978 * generates this libwebsockets callback and the meanings of the
979 * arguments passed. In this callback, user is the x509_ctx,
980 * in is the ssl pointer and len is preverify_ok
981 * Notice that this callback maintains libwebsocket return
982 * conventions, return 0 to mean the cert is OK or 1 to fail it.
983 * This also means that if you don't handle this callback then
984 * the default callback action of returning 0 allows the client
986 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER = 24,
987 /**< this callback happens
988 * when a client handshake is being compiled. user is NULL,
989 * in is a char **, it's pointing to a char * which holds the
990 * next location in the header buffer where you can add
991 * headers, and len is the remaining space in the header buffer,
992 * which is typically some hundreds of bytes. So, to add a canned
993 * cookie, your handler code might look similar to:
995 * char **p = (char **)in;
1000 * *p += sprintf(*p, "Cookie: a=b\x0d\x0a");
1004 * Notice if you add anything, you just have to take care about
1005 * the CRLF on the line you added. Obviously this callback is
1006 * optional, if you don't handle it everything is fine.
1008 * Notice the callback is coming to protocols[0] all the time,
1009 * because there is no specific protocol negotiated yet. */
1010 LWS_CALLBACK_CONFIRM_EXTENSION_OKAY = 25,
1011 /**< When the server handshake code
1012 * sees that it does support a requested extension, before
1013 * accepting the extension by additing to the list sent back to
1014 * the client it gives this callback just to check that it's okay
1015 * to use that extension. It calls back to the requested protocol
1016 * and with in being the extension name, len is 0 and user is
1017 * valid. Note though at this time the ESTABLISHED callback hasn't
1018 * happened yet so if you initialize user content there, user
1019 * content during this callback might not be useful for anything. */
1020 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED = 26,
1022 * connection is being prepared to start a handshake to a server,
1023 * each supported extension is checked with protocols[0] callback
1024 * with this reason, giving the user code a chance to suppress the
1025 * claim to support that extension by returning non-zero. If
1026 * unhandled, by default 0 will be returned and the extension
1027 * support included in the header to the server. Notice this
1028 * callback comes to protocols[0]. */
1029 LWS_CALLBACK_PROTOCOL_INIT = 27,
1030 /**< One-time call per protocol, per-vhost using it, so it can
1031 * do initial setup / allocations etc */
1032 LWS_CALLBACK_PROTOCOL_DESTROY = 28,
1033 /**< One-time call per protocol, per-vhost using it, indicating
1034 * this protocol won't get used at all after this callback, the
1035 * vhost is getting destroyed. Take the opportunity to
1036 * deallocate everything that was allocated by the protocol. */
1037 LWS_CALLBACK_WSI_CREATE = 29,
1038 /**< outermost (earliest) wsi create notification to protocols[0] */
1039 LWS_CALLBACK_WSI_DESTROY = 30,
1040 /**< outermost (latest) wsi destroy notification to protocols[0] */
1041 LWS_CALLBACK_GET_THREAD_ID = 31,
1042 /**< lws can accept callback when writable requests from other
1043 * threads, if you implement this callback and return an opaque
1044 * current thread ID integer. */
1046 /* external poll() management support */
1047 LWS_CALLBACK_ADD_POLL_FD = 32,
1048 /**< lws normally deals with its poll() or other event loop
1049 * internally, but in the case you are integrating with another
1050 * server you will need to have lws sockets share a
1051 * polling array with the other server. This and the other
1052 * POLL_FD related callbacks let you put your specialized
1053 * poll array interface code in the callback for protocol 0, the
1054 * first protocol you support, usually the HTTP protocol in the
1056 * This callback happens when a socket needs to be
1057 * added to the polling loop: in points to a struct
1058 * lws_pollargs; the fd member of the struct is the file
1059 * descriptor, and events contains the active events
1061 * If you are using the internal lws polling / event loop
1062 * you can just ignore these callbacks. */
1063 LWS_CALLBACK_DEL_POLL_FD = 33,
1064 /**< This callback happens when a socket descriptor
1065 * needs to be removed from an external polling array. in is
1066 * again the struct lws_pollargs containing the fd member
1067 * to be removed. If you are using the internal polling
1068 * loop, you can just ignore it. */
1069 LWS_CALLBACK_CHANGE_MODE_POLL_FD = 34,
1070 /**< This callback happens when lws wants to modify the events for
1072 * in is the struct lws_pollargs with the fd to change.
1073 * The new event mask is in events member and the old mask is in
1074 * the prev_events member.
1075 * If you are using the internal polling loop, you can just ignore
1077 LWS_CALLBACK_LOCK_POLL = 35,
1078 /**< These allow the external poll changes driven
1079 * by lws to participate in an external thread locking
1080 * scheme around the changes, so the whole thing is threadsafe.
1081 * These are called around three activities in the library,
1082 * - inserting a new wsi in the wsi / fd table (len=1)
1083 * - deleting a wsi from the wsi / fd table (len=1)
1084 * - changing a wsi's POLLIN/OUT state (len=0)
1085 * Locking and unlocking external synchronization objects when
1086 * len == 1 allows external threads to be synchronized against
1087 * wsi lifecycle changes if it acquires the same lock for the
1088 * duration of wsi dereference from the other thread context. */
1089 LWS_CALLBACK_UNLOCK_POLL = 36,
1090 /**< See LWS_CALLBACK_LOCK_POLL, ignore if using lws internal poll */
1092 LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY = 37,
1093 /**< if configured for including OpenSSL support but no private key
1094 * file has been specified (ssl_private_key_filepath is NULL), this is
1095 * called to allow the user to set the private key directly via
1096 * libopenssl and perform further operations if required; this might be
1097 * useful in situations where the private key is not directly accessible
1098 * by the OS, for example if it is stored on a smartcard.
1099 * user is the server's OpenSSL SSL_CTX* */
1100 LWS_CALLBACK_WS_PEER_INITIATED_CLOSE = 38,
1101 /**< The peer has sent an unsolicited Close WS packet. in and
1102 * len are the optional close code (first 2 bytes, network
1103 * order) and the optional additional information which is not
1104 * defined in the standard, and may be a string or non-human- readable data.
1105 * If you return 0 lws will echo the close and then close the
1106 * connection. If you return nonzero lws will just close the
1109 LWS_CALLBACK_WS_EXT_DEFAULTS = 39,
1112 LWS_CALLBACK_CGI = 40,
1114 LWS_CALLBACK_CGI_TERMINATED = 41,
1116 LWS_CALLBACK_CGI_STDIN_DATA = 42,
1118 LWS_CALLBACK_CGI_STDIN_COMPLETED = 43,
1120 LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP = 44,
1122 LWS_CALLBACK_CLOSED_CLIENT_HTTP = 45,
1124 LWS_CALLBACK_RECEIVE_CLIENT_HTTP = 46,
1126 LWS_CALLBACK_COMPLETED_CLIENT_HTTP = 47,
1128 LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ = 48,
1130 LWS_CALLBACK_HTTP_BIND_PROTOCOL = 49,
1132 LWS_CALLBACK_HTTP_DROP_PROTOCOL = 50,
1134 LWS_CALLBACK_CHECK_ACCESS_RIGHTS = 51,
1136 LWS_CALLBACK_PROCESS_HTML = 52,
1138 LWS_CALLBACK_ADD_HEADERS = 53,
1140 LWS_CALLBACK_SESSION_INFO = 54,
1143 LWS_CALLBACK_GS_EVENT = 55,
1145 LWS_CALLBACK_HTTP_PMO = 56,
1146 /**< per-mount options for this connection, called before
1147 * the normal LWS_CALLBACK_HTTP when the mount has per-mount
1150 LWS_CALLBACK_CLIENT_HTTP_WRITEABLE = 57,
1151 /**< when doing an HTTP type client connection, you can call
1152 * lws_client_http_body_pending(wsi, 1) from
1153 * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER to get these callbacks
1154 * sending the HTTP headers.
1156 * From this callback, when you have sent everything, you should let
1157 * lws know by calling lws_client_http_body_pending(wsi, 0)
1159 LWS_CALLBACK_OPENSSL_PERFORM_SERVER_CERT_VERIFICATION = 58,
1160 /**< Similar to LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION
1161 * this callback is called during OpenSSL verification of the cert
1162 * sent from the server to the client. It is sent to protocol[0]
1163 * callback as no protocol has been negotiated on the connection yet.
1164 * Notice that the wsi is set because lws_client_connect_via_info was
1167 * See http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html
1168 * to understand more detail about the OpenSSL callback that
1169 * generates this libwebsockets callback and the meanings of the
1170 * arguments passed. In this callback, user is the x509_ctx,
1171 * in is the ssl pointer and len is preverify_ok.
1173 * THIS IS NOT RECOMMENDED BUT if a cert validation error shall be
1174 * overruled and cert shall be accepted as ok,
1175 * X509_STORE_CTX_set_error((X509_STORE_CTX*)user, X509_V_OK); must be
1176 * called and return value must be 0 to mean the cert is OK;
1177 * returning 1 will fail the cert in any case.
1179 * This also means that if you don't handle this callback then
1180 * the default callback action of returning 0 will not accept the
1181 * certificate in case of a validation error decided by the SSL lib.
1183 * This is expected and secure behaviour when validating certificates.
1185 * Note: LCCSCF_ALLOW_SELFSIGNED and
1186 * LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK still work without this
1187 * callback being implemented.
1189 LWS_CALLBACK_RAW_RX = 59,
1190 /**< RAW mode connection RX */
1191 LWS_CALLBACK_RAW_CLOSE = 60,
1192 /**< RAW mode connection is closing */
1193 LWS_CALLBACK_RAW_WRITEABLE = 61,
1194 /**< RAW mode connection may be written */
1195 LWS_CALLBACK_RAW_ADOPT = 62,
1196 /**< RAW mode connection was adopted (equivalent to 'wsi created') */
1197 LWS_CALLBACK_RAW_ADOPT_FILE = 63,
1198 /**< RAW mode file was adopted (equivalent to 'wsi created') */
1199 LWS_CALLBACK_RAW_RX_FILE = 64,
1200 /**< RAW mode file has something to read */
1201 LWS_CALLBACK_RAW_WRITEABLE_FILE = 65,
1202 /**< RAW mode file is writeable */
1203 LWS_CALLBACK_RAW_CLOSE_FILE = 66,
1204 /**< RAW mode wsi that adopted a file is closing */
1206 /****** add new things just above ---^ ******/
1208 LWS_CALLBACK_USER = 1000,
1209 /**< user code can use any including above without fear of clashes */
1215 * typedef lws_callback_function() - User server actions
1216 * \param wsi: Opaque websocket instance pointer
1217 * \param reason: The reason for the call
1218 * \param user: Pointer to per-session user data allocated by library
1219 * \param in: Pointer used for some callback reasons
1220 * \param len: Length set for some callback reasons
1222 * This callback is the way the user controls what is served. All the
1223 * protocol detail is hidden and handled by the library.
1225 * For each connection / session there is user data allocated that is
1226 * pointed to by "user". You set the size of this user data area when
1227 * the library is initialized with lws_create_server.
1230 lws_callback_function(struct lws *wsi, enum lws_callback_reasons reason,
1231 void *user, void *in, size_t len);
1234 /*! \defgroup extensions
1236 * ##Extension releated functions
1238 * Ws defines optional extensions, lws provides the ability to implement these
1239 * in user code if so desired.
1241 * We provide one extensions permessage-deflate.
1246 * NOTE: These public enums are part of the abi. If you want to add one,
1247 * add it at where specified so existing users are unaffected.
1249 enum lws_extension_callback_reasons {
1250 LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT = 0,
1251 LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT = 1,
1252 LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT = 2,
1253 LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT = 3,
1254 LWS_EXT_CB_CONSTRUCT = 4,
1255 LWS_EXT_CB_CLIENT_CONSTRUCT = 5,
1256 LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE = 6,
1257 LWS_EXT_CB_CHECK_OK_TO_PROPOSE_EXTENSION = 7,
1258 LWS_EXT_CB_DESTROY = 8,
1259 LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING = 9,
1260 LWS_EXT_CB_ANY_WSI_ESTABLISHED = 10,
1261 LWS_EXT_CB_PACKET_RX_PREPARSE = 11,
1262 LWS_EXT_CB_PACKET_TX_PRESEND = 12,
1263 LWS_EXT_CB_PACKET_TX_DO_SEND = 13,
1264 LWS_EXT_CB_HANDSHAKE_REPLY_TX = 14,
1265 LWS_EXT_CB_FLUSH_PENDING_TX = 15,
1266 LWS_EXT_CB_EXTENDED_PAYLOAD_RX = 16,
1267 LWS_EXT_CB_CAN_PROXY_CLIENT_CONNECTION = 17,
1268 LWS_EXT_CB_1HZ = 18,
1269 LWS_EXT_CB_REQUEST_ON_WRITEABLE = 19,
1270 LWS_EXT_CB_IS_WRITEABLE = 20,
1271 LWS_EXT_CB_PAYLOAD_TX = 21,
1272 LWS_EXT_CB_PAYLOAD_RX = 22,
1273 LWS_EXT_CB_OPTION_DEFAULT = 23,
1274 LWS_EXT_CB_OPTION_SET = 24,
1275 LWS_EXT_CB_OPTION_CONFIRM = 25,
1276 LWS_EXT_CB_NAMED_OPTION_SET = 26,
1278 /****** add new things just above ---^ ******/
1281 /** enum lws_ext_options_types */
1282 enum lws_ext_options_types {
1283 EXTARG_NONE, /**< does not take an argument */
1284 EXTARG_DEC, /**< requires a decimal argument */
1285 EXTARG_OPT_DEC /**< may have an optional decimal argument */
1287 /* Add new things just above here ---^
1288 * This is part of the ABI, don't needlessly break compatibility */
1291 /** struct lws_ext_options - Option arguments to the extension. These are
1292 * used in the negotiation at ws upgrade time.
1293 * The helper function lws_ext_parse_options()
1294 * uses these to generate callbacks */
1295 struct lws_ext_options {
1296 const char *name; /**< Option name, eg, "server_no_context_takeover" */
1297 enum lws_ext_options_types type; /**< What kind of args the option can take */
1299 /* Add new things just above here ---^
1300 * This is part of the ABI, don't needlessly break compatibility */
1303 /** struct lws_ext_option_arg */
1304 struct lws_ext_option_arg {
1305 const char *option_name; /**< may be NULL, option_index used then */
1306 int option_index; /**< argument ordinal to use if option_name missing */
1307 const char *start; /**< value */
1308 int len; /**< length of value */
1312 * typedef lws_extension_callback_function() - Hooks to allow extensions to operate
1313 * \param context: Websockets context
1314 * \param ext: This extension
1315 * \param wsi: Opaque websocket instance pointer
1316 * \param reason: The reason for the call
1317 * \param user: Pointer to ptr to per-session user data allocated by library
1318 * \param in: Pointer used for some callback reasons
1319 * \param len: Length set for some callback reasons
1321 * Each extension that is active on a particular connection receives
1322 * callbacks during the connection lifetime to allow the extension to
1323 * operate on websocket data and manage itself.
1325 * Libwebsockets takes care of allocating and freeing "user" memory for
1326 * each active extension on each connection. That is what is pointed to
1327 * by the user parameter.
1329 * LWS_EXT_CB_CONSTRUCT: called when the server has decided to
1330 * select this extension from the list provided by the client,
1331 * just before the server will send back the handshake accepting
1332 * the connection with this extension active. This gives the
1333 * extension a chance to initialize its connection context found
1336 * LWS_EXT_CB_CLIENT_CONSTRUCT: same as LWS_EXT_CB_CONSTRUCT
1337 * but called when client is instantiating this extension. Some
1338 * extensions will work the same on client and server side and then
1339 * you can just merge handlers for both CONSTRUCTS.
1341 * LWS_EXT_CB_DESTROY: called when the connection the extension was
1342 * being used on is about to be closed and deallocated. It's the
1343 * last chance for the extension to deallocate anything it has
1344 * allocated in the user data (pointed to by user) before the
1345 * user data is deleted. This same callback is used whether you
1346 * are in client or server instantiation context.
1348 * LWS_EXT_CB_PACKET_RX_PREPARSE: when this extension was active on
1349 * a connection, and a packet of data arrived at the connection,
1350 * it is passed to this callback to give the extension a chance to
1351 * change the data, eg, decompress it. user is pointing to the
1352 * extension's private connection context data, in is pointing
1353 * to an lws_tokens struct, it consists of a char * pointer called
1354 * token, and an int called token_len. At entry, these are
1355 * set to point to the received buffer and set to the content
1356 * length. If the extension will grow the content, it should use
1357 * a new buffer allocated in its private user context data and
1358 * set the pointed-to lws_tokens members to point to its buffer.
1360 * LWS_EXT_CB_PACKET_TX_PRESEND: this works the same way as
1361 * LWS_EXT_CB_PACKET_RX_PREPARSE above, except it gives the
1362 * extension a chance to change websocket data just before it will
1363 * be sent out. Using the same lws_token pointer scheme in in,
1364 * the extension can change the buffer and the length to be
1365 * transmitted how it likes. Again if it wants to grow the
1366 * buffer safely, it should copy the data into its own buffer and
1367 * set the lws_tokens token pointer to it.
1369 * LWS_EXT_CB_ARGS_VALIDATE:
1372 lws_extension_callback_function(struct lws_context *context,
1373 const struct lws_extension *ext, struct lws *wsi,
1374 enum lws_extension_callback_reasons reason,
1375 void *user, void *in, size_t len);
1377 /** struct lws_extension - An extension we support */
1378 struct lws_extension {
1379 const char *name; /**< Formal extension name, eg, "permessage-deflate" */
1380 lws_extension_callback_function *callback; /**< Service callback */
1381 const char *client_offer; /**< String containing exts and options client offers */
1383 /* Add new things just above here ---^
1384 * This is part of the ABI, don't needlessly break compatibility */
1388 * lws_set_extension_option(): set extension option if possible
1390 * \param wsi: websocket connection
1391 * \param ext_name: name of ext, like "permessage-deflate"
1392 * \param opt_name: name of option, like "rx_buf_size"
1393 * \param opt_val: value to set option to
1395 LWS_VISIBLE LWS_EXTERN int
1396 lws_set_extension_option(struct lws *wsi, const char *ext_name,
1397 const char *opt_name, const char *opt_val);
1399 #ifndef LWS_NO_EXTENSIONS
1400 /* lws_get_internal_extensions() - DEPRECATED
1402 * \Deprecated There is no longer a set internal extensions table. The table is provided
1403 * by user code along with application-specific settings. See the test
1404 * client and server for how to do.
1406 static LWS_INLINE LWS_WARN_DEPRECATED const struct lws_extension *
1407 lws_get_internal_extensions(void) { return NULL; }
1410 * lws_ext_parse_options() - deal with parsing negotiated extension options
1412 * \param ext: related extension struct
1413 * \param wsi: websocket connection
1414 * \param ext_user: per-connection extension private data
1415 * \param opts: list of supported options
1416 * \param o: option string to parse
1417 * \param len: length
1419 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
1420 lws_ext_parse_options(const struct lws_extension *ext, struct lws *wsi,
1421 void *ext_user, const struct lws_ext_options *opts,
1422 const char *o, int len);
1425 /** lws_extension_callback_pm_deflate() - extension for RFC7692
1427 * \param context: lws context
1428 * \param ext: related lws_extension struct
1429 * \param wsi: websocket connection
1430 * \param reason: incoming callback reason
1431 * \param user: per-connection extension private data
1432 * \param in: pointer parameter
1433 * \param len: length parameter
1435 * Built-in callback implementing RFC7692 permessage-deflate
1438 int lws_extension_callback_pm_deflate(
1439 struct lws_context *context, const struct lws_extension *ext,
1440 struct lws *wsi, enum lws_extension_callback_reasons reason,
1441 void *user, void *in, size_t len);
1444 * The internal exts are part of the public abi
1445 * If we add more extensions, publish the callback here ------v
1449 /*! \defgroup Protocols-and-Plugins Protocols and Plugins
1452 * ##Protocol and protocol plugin -related apis
1454 * Protocols bind ws protocol names to a custom callback specific to that
1455 * protocol implementaion.
1457 * A list of protocols can be passed in at context creation time, but it is
1458 * also legal to leave that NULL and add the protocols and their callback code
1461 * Plugins are much preferable compared to cut and pasting code into an
1462 * application each time, since they can be used standalone.
1465 /** struct lws_protocols - List of protocols and handlers client or server
1468 struct lws_protocols {
1470 /**< Protocol name that must match the one given in the client
1471 * Javascript new WebSocket(url, 'protocol') name. */
1472 lws_callback_function *callback;
1473 /**< The service callback used for this protocol. It allows the
1474 * service action for an entire protocol to be encapsulated in
1475 * the protocol-specific callback */
1476 size_t per_session_data_size;
1477 /**< Each new connection using this protocol gets
1478 * this much memory allocated on connection establishment and
1479 * freed on connection takedown. A pointer to this per-connection
1480 * allocation is passed into the callback in the 'user' parameter */
1481 size_t rx_buffer_size;
1482 /**< lws allocates this much space for rx data and informs callback
1483 * when something came. Due to rx flow control, the callback may not
1484 * be able to consume it all without having to return to the event
1485 * loop. That is supported in lws.
1487 * If .tx_packet_size is 0, this also controls how much may be sent at once
1488 * for backwards compatibility.
1491 /**< ignored by lws, but useful to contain user information bound
1492 * to the selected protocol. For example if this protocol was
1493 * called "myprotocol-v2", you might set id to 2, and the user
1494 * code that acts differently according to the version can do so by
1495 * switch (wsi->protocol->id), user code might use some bits as
1496 * capability flags based on selected protocol version, etc. */
1497 void *user; /**< ignored by lws, but user code can pass a pointer
1498 here it can later access from the protocol callback */
1499 size_t tx_packet_size;
1500 /**< 0 indicates restrict send() size to .rx_buffer_size for backwards-
1502 * If greater than zero, a single send() is restricted to this amount
1503 * and any remainder is buffered by lws and sent afterwards also in
1504 * these size chunks. Since that is expensive, it's preferable
1505 * to restrict one fragment you are trying to send to match this
1509 /* Add new things just above here ---^
1510 * This is part of the ABI, don't needlessly break compatibility */
1516 * lws_vhost_name_to_protocol() - get vhost's protocol object from its name
1518 * \param vh: vhost to search
1519 * \param name: protocol name
1521 * Returns NULL or a pointer to the vhost's protocol of the requested name
1523 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1524 lws_vhost_name_to_protocol(struct lws_vhost *vh, const char *name);
1527 * lws_get_protocol() - Returns a protocol pointer from a websocket
1529 * \param wsi: pointer to struct websocket you want to know the protocol of
1532 * Some apis can act on all live connections of a given protocol,
1533 * this is how you can get a pointer to the active protocol if needed.
1535 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1536 lws_get_protocol(struct lws *wsi);
1538 /** lws_protocol_get() - deprecated: use lws_get_protocol */
1539 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1540 lws_protocol_get(struct lws *wsi) LWS_WARN_DEPRECATED;
1543 * lws_protocol_vh_priv_zalloc() - Allocate and zero down a protocol's per-vhost
1545 * \param vhost: vhost the instance is related to
1546 * \param prot: protocol the instance is related to
1547 * \param size: bytes to allocate
1549 * Protocols often find it useful to allocate a per-vhost struct, this is a
1550 * helper to be called in the per-vhost init LWS_CALLBACK_PROTOCOL_INIT
1552 LWS_VISIBLE LWS_EXTERN void *
1553 lws_protocol_vh_priv_zalloc(struct lws_vhost *vhost, const struct lws_protocols *prot,
1557 * lws_protocol_vh_priv_get() - retreive a protocol's per-vhost storage
1559 * \param vhost: vhost the instance is related to
1560 * \param prot: protocol the instance is related to
1562 * Recover a pointer to the allocated per-vhost storage for the protocol created
1563 * by lws_protocol_vh_priv_zalloc() earlier
1565 LWS_VISIBLE LWS_EXTERN void *
1566 lws_protocol_vh_priv_get(struct lws_vhost *vhost, const struct lws_protocols *prot);
1569 * lws_finalize_startup() - drop initial process privileges
1571 * \param context: lws context
1573 * This is called after the end of the vhost protocol initializations, but
1574 * you may choose to call it earlier
1576 LWS_VISIBLE LWS_EXTERN int
1577 lws_finalize_startup(struct lws_context *context);
1579 LWS_VISIBLE LWS_EXTERN int
1580 lws_protocol_init(struct lws_context *context);
1582 #ifdef LWS_WITH_PLUGINS
1584 /* PLUGINS implies LIBUV */
1586 #define LWS_PLUGIN_API_MAGIC 180
1588 /** struct lws_plugin_capability - how a plugin introduces itself to lws */
1589 struct lws_plugin_capability {
1590 unsigned int api_magic; /**< caller fills this in, plugin fills rest */
1591 const struct lws_protocols *protocols; /**< array of supported protocols provided by plugin */
1592 int count_protocols; /**< how many protocols */
1593 const struct lws_extension *extensions; /**< array of extensions provided by plugin */
1594 int count_extensions; /**< how many extensions */
1597 typedef int (*lws_plugin_init_func)(struct lws_context *,
1598 struct lws_plugin_capability *);
1599 typedef int (*lws_plugin_destroy_func)(struct lws_context *);
1601 /** struct lws_plugin */
1603 struct lws_plugin *list; /**< linked list */
1604 #if (UV_VERSION_MAJOR > 0)
1605 uv_lib_t lib; /**< shared library pointer */
1607 void *l; /**< so we can compile on ancient libuv */
1609 char name[64]; /**< name of the plugin */
1610 struct lws_plugin_capability caps; /**< plugin capabilities */
1618 /*! \defgroup generic-sessions plugin: generic-sessions
1619 * \ingroup Protocols-and-Plugins
1621 * ##Plugin Generic-sessions related
1623 * generic-sessions plugin provides a reusable, generic session and login /
1624 * register / forgot password framework including email verification.
1628 #define LWSGS_EMAIL_CONTENT_SIZE 16384
1629 /**< Maximum size of email we might send */
1631 /* SHA-1 binary and hexified versions */
1632 /** typedef struct lwsgw_hash_bin */
1633 typedef struct { unsigned char bin[20]; /**< binary representation of hash */} lwsgw_hash_bin;
1634 /** typedef struct lwsgw_hash */
1635 typedef struct { char id[41]; /**< ascii hex representation of hash */ } lwsgw_hash;
1637 /** enum lwsgs_auth_bits */
1638 enum lwsgs_auth_bits {
1639 LWSGS_AUTH_LOGGED_IN = 1, /**< user is logged in as somebody */
1640 LWSGS_AUTH_ADMIN = 2, /**< logged in as the admin user */
1641 LWSGS_AUTH_VERIFIED = 4, /**< user has verified his email */
1642 LWSGS_AUTH_FORGOT_FLOW = 8, /**< he just completed "forgot password" flow */
1645 /** struct lws_session_info - information about user session status */
1646 struct lws_session_info {
1647 char username[32]; /**< username logged in as, or empty string */
1648 char email[100]; /**< email address associated with login, or empty string */
1649 char ip[72]; /**< ip address session was started from */
1650 unsigned int mask; /**< access rights mask associated with session
1651 * see enum lwsgs_auth_bits */
1652 char session[42]; /**< session id string, usable as opaque uid when not logged in */
1655 /** enum lws_gs_event */
1657 LWSGSE_CREATED, /**< a new user was created */
1658 LWSGSE_DELETED /**< an existing user was deleted */
1661 /** struct lws_gs_event_args */
1662 struct lws_gs_event_args {
1663 enum lws_gs_event event; /**< which event happened */
1664 const char *username; /**< which username the event happened to */
1665 const char *email; /**< the email address of that user */
1671 /*! \defgroup context-and-vhost
1674 * ##Context and Vhost releated functions
1676 * LWS requires that there is one context, in which you may define multiple
1677 * vhosts. Each vhost is a virtual host, with either its own listen port
1678 * or sharing an existing one. Each vhost has its own SSL context that can
1679 * be set up individually or left disabled.
1681 * If you don't care about multiple "site" support, you can ignore it and
1682 * lws will create a single default vhost at context creation time.
1687 * NOTE: These public enums are part of the abi. If you want to add one,
1688 * add it at where specified so existing users are unaffected.
1691 /** enum lws_context_options - context and vhost options */
1692 enum lws_context_options {
1693 LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT = (1 << 1) |
1695 /**< (VH) Don't allow the connection unless the client has a
1696 * client cert that we recognize; provides
1697 * LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT */
1698 LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME = (1 << 2),
1699 /**< (CTX) Don't try to get the server's hostname */
1700 LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT = (1 << 3) |
1702 /**< (VH) Allow non-SSL (plaintext) connections on the same
1703 * port as SSL is listening... undermines the security of SSL;
1704 * provides LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT */
1705 LWS_SERVER_OPTION_LIBEV = (1 << 4),
1706 /**< (CTX) Use libev event loop */
1707 LWS_SERVER_OPTION_DISABLE_IPV6 = (1 << 5),
1708 /**< (VH) Disable IPV6 support */
1709 LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS = (1 << 6),
1710 /**< (VH) Don't load OS CA certs, you will need to load your
1712 LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED = (1 << 7),
1713 /**< (VH) Accept connections with no valid Cert (eg, selfsigned) */
1714 LWS_SERVER_OPTION_VALIDATE_UTF8 = (1 << 8),
1715 /**< (VH) Check UT-8 correctness */
1716 LWS_SERVER_OPTION_SSL_ECDH = (1 << 9) |
1718 /**< (VH) initialize ECDH ciphers */
1719 LWS_SERVER_OPTION_LIBUV = (1 << 10),
1720 /**< (CTX) Use libuv event loop */
1721 LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS = (1 << 11) |
1723 /**< (VH) Use http redirect to force http to https
1724 * (deprecated: use mount redirection) */
1725 LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT = (1 << 12),
1726 /**< (CTX) Initialize the SSL library at all */
1727 LWS_SERVER_OPTION_EXPLICIT_VHOSTS = (1 << 13),
1728 /**< (CTX) Only create the context when calling context
1729 * create api, implies user code will create its own vhosts */
1730 LWS_SERVER_OPTION_UNIX_SOCK = (1 << 14),
1731 /**< (VH) Use Unix socket */
1732 LWS_SERVER_OPTION_STS = (1 << 15),
1733 /**< (VH) Send Strict Transport Security header, making
1734 * clients subsequently go to https even if user asked for http */
1735 LWS_SERVER_OPTION_IPV6_V6ONLY_MODIFY = (1 << 16),
1736 /**< (VH) Enable LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE to take effect */
1737 LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE = (1 << 17),
1738 /**< (VH) if set, only ipv6 allowed on the vhost */
1739 LWS_SERVER_OPTION_UV_NO_SIGSEGV_SIGFPE_SPIN = (1 << 18),
1740 /**< (CTX) Libuv only: Do not spin on SIGSEGV / SIGFPE. A segfault
1741 * normally makes the lib spin so you can attach a debugger to it
1742 * even if it happened without a debugger in place. You can disable
1743 * that by giving this option.
1745 LWS_SERVER_OPTION_JUST_USE_RAW_ORIGIN = (1 << 19),
1746 /**< For backwards-compatibility reasons, by default
1747 * lws prepends "http://" to the origin you give in the client
1748 * connection info struct. If you give this flag when you create
1749 * the context, only the string you give in the client connect
1750 * info for .origin (if any) will be used directly.
1752 LWS_SERVER_OPTION_FALLBACK_TO_RAW = (1 << 20),
1753 /**< (VH) if invalid http is coming in the first line, */
1754 LWS_SERVER_OPTION_LIBEVENT = (1 << 21),
1755 /**< (CTX) Use libevent event loop */
1756 LWS_SERVER_OPTION_ONLY_RAW = (1 << 22),
1757 /**< (VH) All connections to this vhost / port are RAW as soon as
1758 * the connection is accepted, no HTTP is going to be coming.
1761 /****** add new things just above ---^ ******/
1764 #define lws_check_opt(c, f) (((c) & (f)) == (f))
1766 struct lws_plat_file_ops;
1768 /** struct lws_context_creation_info - parameters to create context and /or vhost with
1770 * This is also used to create vhosts.... if LWS_SERVER_OPTION_EXPLICIT_VHOSTS
1771 * is not given, then for backwards compatibility one vhost is created at
1772 * context-creation time using the info from this struct.
1774 * If LWS_SERVER_OPTION_EXPLICIT_VHOSTS is given, then no vhosts are created
1775 * at the same time as the context, they are expected to be created afterwards.
1777 struct lws_context_creation_info {
1779 /**< VHOST: Port to listen on. Use CONTEXT_PORT_NO_LISTEN to suppress
1780 * listening for a client. Use CONTEXT_PORT_NO_LISTEN_SERVER if you are
1781 * writing a server but you are using \ref sock-adopt instead of the
1782 * built-in listener */
1784 /**< VHOST: NULL to bind the listen socket to all interfaces, or the
1785 * interface name, eg, "eth2"
1786 * If options specifies LWS_SERVER_OPTION_UNIX_SOCK, this member is
1787 * the pathname of a UNIX domain socket. you can use the UNIX domain
1788 * sockets in abstract namespace, by prepending an at symbol to the
1790 const struct lws_protocols *protocols;
1791 /**< VHOST: Array of structures listing supported protocols and a protocol-
1792 * specific callback for each one. The list is ended with an
1793 * entry that has a NULL callback pointer. */
1794 const struct lws_extension *extensions;
1795 /**< VHOST: NULL or array of lws_extension structs listing the
1796 * extensions this context supports. */
1797 const struct lws_token_limits *token_limits;
1798 /**< CONTEXT: NULL or struct lws_token_limits pointer which is initialized
1799 * with a token length limit for each possible WSI_TOKEN_ */
1800 const char *ssl_private_key_password;
1801 /**< VHOST: NULL or the passphrase needed for the private key */
1802 const char *ssl_cert_filepath;
1803 /**< VHOST: If libwebsockets was compiled to use ssl, and you want
1804 * to listen using SSL, set to the filepath to fetch the
1805 * server cert from, otherwise NULL for unencrypted */
1806 const char *ssl_private_key_filepath;
1807 /**< VHOST: filepath to private key if wanting SSL mode;
1808 * if this is set to NULL but sll_cert_filepath is set, the
1809 * OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY callback is called
1810 * to allow setting of the private key directly via openSSL
1812 const char *ssl_ca_filepath;
1813 /**< VHOST: CA certificate filepath or NULL */
1814 const char *ssl_cipher_list;
1815 /**< VHOST: List of valid ciphers to use (eg,
1816 * "RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL"
1817 * or you can leave it as NULL to get "DEFAULT" */
1818 const char *http_proxy_address;
1819 /**< VHOST: If non-NULL, attempts to proxy via the given address.
1820 * If proxy auth is required, use format "username:password\@server:port" */
1821 unsigned int http_proxy_port;
1822 /**< VHOST: If http_proxy_address was non-NULL, uses this port */
1824 /**< CONTEXT: group id to change to after setting listen socket, or -1. */
1826 /**< CONTEXT: user id to change to after setting listen socket, or -1. */
1827 unsigned int options;
1828 /**< VHOST + CONTEXT: 0, or LWS_SERVER_OPTION_... bitfields */
1830 /**< CONTEXT: optional user pointer that can be recovered via the context
1831 * pointer using lws_context_user */
1833 /**< CONTEXT: 0 for no TCP keepalive, otherwise apply this keepalive
1834 * timeout to all libwebsocket sockets, client or server */
1836 /**< CONTEXT: if ka_time was nonzero, after the timeout expires how many
1837 * times to try to get a response from the peer before giving up
1838 * and killing the connection */
1840 /**< CONTEXT: if ka_time was nonzero, how long to wait before each ka_probes
1842 #ifdef LWS_OPENSSL_SUPPORT
1843 SSL_CTX *provided_client_ssl_ctx;
1844 /**< CONTEXT: If non-null, swap out libwebsockets ssl
1845 * implementation for the one provided by provided_ssl_ctx.
1846 * Libwebsockets no longer is responsible for freeing the context
1847 * if this option is selected. */
1848 #else /* maintain structure layout either way */
1849 void *provided_client_ssl_ctx; /**< dummy if ssl disabled */
1852 short max_http_header_data;
1853 /**< CONTEXT: The max amount of header payload that can be handled
1854 * in an http request (unrecognized header payload is dropped) */
1855 short max_http_header_pool;
1856 /**< CONTEXT: The max number of connections with http headers that
1857 * can be processed simultaneously (the corresponding memory is
1858 * allocated for the lifetime of the context). If the pool is
1859 * busy new incoming connections must wait for accept until one
1862 unsigned int count_threads;
1863 /**< CONTEXT: how many contexts to create in an array, 0 = 1 */
1864 unsigned int fd_limit_per_thread;
1865 /**< CONTEXT: nonzero means restrict each service thread to this
1866 * many fds, 0 means the default which is divide the process fd
1867 * limit by the number of threads. */
1868 unsigned int timeout_secs;
1869 /**< VHOST: various processes involving network roundtrips in the
1870 * library are protected from hanging forever by timeouts. If
1871 * nonzero, this member lets you set the timeout used in seconds.
1872 * Otherwise a default timeout is used. */
1873 const char *ecdh_curve;
1874 /**< VHOST: if NULL, defaults to initializing server with "prime256v1" */
1875 const char *vhost_name;
1876 /**< VHOST: name of vhost, must match external DNS name used to
1877 * access the site, like "warmcat.com" as it's used to match
1878 * Host: header and / or SNI name for SSL. */
1879 const char * const *plugin_dirs;
1880 /**< CONTEXT: NULL, or NULL-terminated array of directories to
1881 * scan for lws protocol plugins at context creation time */
1882 const struct lws_protocol_vhost_options *pvo;
1883 /**< VHOST: pointer to optional linked list of per-vhost
1884 * options made accessible to protocols */
1885 int keepalive_timeout;
1886 /**< VHOST: (default = 0 = 60s) seconds to allow remote
1887 * client to hold on to an idle HTTP/1.1 connection */
1888 const char *log_filepath;
1889 /**< VHOST: filepath to append logs to... this is opened before
1890 * any dropping of initial privileges */
1891 const struct lws_http_mount *mounts;
1892 /**< VHOST: optional linked list of mounts for this vhost */
1893 const char *server_string;
1894 /**< CONTEXT: string used in HTTP headers to identify server
1895 * software, if NULL, "libwebsockets". */
1896 unsigned int pt_serv_buf_size;
1897 /**< CONTEXT: 0 = default of 4096. This buffer is used by
1898 * various service related features including file serving, it
1899 * defines the max chunk of file that can be sent at once.
1900 * At the risk of lws having to buffer failed large sends, it
1901 * can be increased to, eg, 128KiB to improve throughput. */
1902 unsigned int max_http_header_data2;
1903 /**< CONTEXT: if max_http_header_data is 0 and this
1904 * is nonzero, this will be used in place of the default. It's
1905 * like this for compatibility with the original short version,
1906 * this is unsigned int length. */
1907 long ssl_options_set;
1908 /**< VHOST: Any bits set here will be set as SSL options */
1909 long ssl_options_clear;
1910 /**< VHOST: Any bits set here will be cleared as SSL options */
1911 unsigned short ws_ping_pong_interval;
1912 /**< CONTEXT: 0 for none, else interval in seconds between sending
1913 * PINGs on idle websocket connections. When the PING is sent,
1914 * the PONG must come within the normal timeout_secs timeout period
1915 * or the connection will be dropped.
1916 * Any RX or TX traffic on the connection restarts the interval timer,
1917 * so a connection which always sends or receives something at intervals
1918 * less than the interval given here will never send PINGs / expect
1919 * PONGs. Conversely as soon as the ws connection is established, an
1920 * idle connection will do the PING / PONG roundtrip as soon as
1921 * ws_ping_pong_interval seconds has passed without traffic
1923 const struct lws_protocol_vhost_options *headers;
1924 /**< VHOST: pointer to optional linked list of per-vhost
1925 * canned headers that are added to server responses */
1927 const struct lws_protocol_vhost_options *reject_service_keywords;
1928 /**< CONTEXT: Optional list of keywords and rejection codes + text.
1930 * The keywords are checked for existing in the user agent string.
1932 * Eg, "badrobot" "404 Not Found"
1934 void *external_baggage_free_on_destroy;
1935 /**< CONTEXT: NULL, or pointer to something externally malloc'd, that
1936 * should be freed when the context is destroyed. This allows you to
1937 * automatically sync the freeing action to the context destruction
1938 * action, so there is no need for an external free() if the context
1939 * succeeded to create.
1942 #ifdef LWS_OPENSSL_SUPPORT
1943 /**< CONTEXT: NULL or struct lws_token_limits pointer which is initialized
1944 * with a token length limit for each possible WSI_TOKEN_ */
1945 const char *client_ssl_private_key_password;
1946 /**< VHOST: NULL or the passphrase needed for the private key */
1947 const char *client_ssl_cert_filepath;
1948 /**< VHOST: If libwebsockets was compiled to use ssl, and you want
1949 * to listen using SSL, set to the filepath to fetch the
1950 * server cert from, otherwise NULL for unencrypted */
1951 const char *client_ssl_private_key_filepath;
1952 /**< VHOST: filepath to private key if wanting SSL mode;
1953 * if this is set to NULL but sll_cert_filepath is set, the
1954 * OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY callback is called
1955 * to allow setting of the private key directly via openSSL
1957 const char *client_ssl_ca_filepath;
1958 /**< VHOST: CA certificate filepath or NULL */
1959 const char *client_ssl_cipher_list;
1960 /**< VHOST: List of valid ciphers to use (eg,
1961 * "RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL"
1962 * or you can leave it as NULL to get "DEFAULT" */
1965 const struct lws_plat_file_ops *fops;
1966 /**< CONTEXT: NULL, or pointer to an array of fops structs, terminated
1967 * by a sentinel with NULL .open.
1969 * If NULL, lws provides just the platform file operations struct for
1970 * backwards compatibility.
1972 int simultaneous_ssl_restriction;
1973 /**< CONTEXT: 0 (no limit) or limit of simultaneous SSL sessions possible.*/
1974 const char *socks_proxy_address;
1975 /**< VHOST: If non-NULL, attempts to proxy via the given address.
1976 * If proxy auth is required, use format "username:password\@server:port" */
1977 unsigned int socks_proxy_port;
1978 /**< VHOST: If socks_proxy_address was non-NULL, uses this port */
1980 /* Add new things just above here ---^
1981 * This is part of the ABI, don't needlessly break compatibility
1983 * The below is to ensure later library versions with new
1984 * members added above will see 0 (default) even if the app
1985 * was not built against the newer headers.
1988 void *_unused[8]; /**< dummy */
1992 * lws_create_context() - Create the websocket handler
1993 * \param info: pointer to struct with parameters
1995 * This function creates the listening socket (if serving) and takes care
1996 * of all initialization in one step.
1998 * If option LWS_SERVER_OPTION_EXPLICIT_VHOSTS is given, no vhost is
1999 * created; you're expected to create your own vhosts afterwards using
2000 * lws_create_vhost(). Otherwise a vhost named "default" is also created
2001 * using the information in the vhost-related members, for compatibility.
2003 * After initialization, it returns a struct lws_context * that
2004 * represents this server. After calling, user code needs to take care
2005 * of calling lws_service() with the context pointer to get the
2006 * server's sockets serviced. This must be done in the same process
2007 * context as the initialization call.
2009 * The protocol callback functions are called for a handful of events
2010 * including http requests coming in, websocket connections becoming
2011 * established, and data arriving; it's also called periodically to allow
2012 * async transmission.
2014 * HTTP requests are sent always to the FIRST protocol in protocol, since
2015 * at that time websocket protocol has not been negotiated. Other
2016 * protocols after the first one never see any HTTP callback activity.
2018 * The server created is a simple http server by default; part of the
2019 * websocket standard is upgrading this http connection to a websocket one.
2021 * This allows the same server to provide files like scripts and favicon /
2022 * images or whatever over http and dynamic data over websockets all in
2023 * one place; they're all handled in the user callback.
2025 LWS_VISIBLE LWS_EXTERN struct lws_context *
2026 lws_create_context(struct lws_context_creation_info *info);
2029 * lws_context_destroy() - Destroy the websocket context
2030 * \param context: Websocket context
2032 * This function closes any active connections and then frees the
2033 * context. After calling this, any further use of the context is
2036 LWS_VISIBLE LWS_EXTERN void
2037 lws_context_destroy(struct lws_context *context);
2039 LWS_VISIBLE LWS_EXTERN void
2040 lws_context_destroy2(struct lws_context *context);
2042 typedef int (*lws_reload_func)(void);
2045 * lws_context_deprecate() - Deprecate the websocket context
2046 * \param context: Websocket context
2048 * This function is used on an existing context before superceding it
2049 * with a new context.
2051 * It closes any listen sockets in the context, so new connections are
2054 * And it marks the context to be deleted when the number of active
2055 * connections into it falls to zero.
2057 * Otherwise if you attach the deprecated context to the replacement
2058 * context when it has been created using lws_context_attach_deprecated()
2059 * both any deprecated and the new context will service their connections.
2061 * This is aimed at allowing seamless configuration reloads.
2063 * The callback cb will be called after the listen sockets are actually
2064 * closed and may be reopened. In the callback the new context should be
2065 * configured and created. (With libuv, socket close happens async after
2066 * more loop events).
2068 LWS_VISIBLE LWS_EXTERN void
2069 lws_context_deprecate(struct lws_context *context, lws_reload_func cb);
2071 LWS_VISIBLE LWS_EXTERN int
2072 lws_context_is_deprecated(struct lws_context *context);
2075 * lws_set_proxy() - Setups proxy to lws_context.
2076 * \param vhost: pointer to struct lws_vhost you want set proxy for
2077 * \param proxy: pointer to c string containing proxy in format address:port
2079 * Returns 0 if proxy string was parsed and proxy was setup.
2080 * Returns -1 if proxy is NULL or has incorrect format.
2082 * This is only required if your OS does not provide the http_proxy
2083 * environment variable (eg, OSX)
2085 * IMPORTANT! You should call this function right after creation of the
2086 * lws_context and before call to connect. If you call this
2087 * function after connect behavior is undefined.
2088 * This function will override proxy settings made on lws_context
2089 * creation with genenv() call.
2091 LWS_VISIBLE LWS_EXTERN int
2092 lws_set_proxy(struct lws_vhost *vhost, const char *proxy);
2095 * lws_set_socks() - Setup socks to lws_context.
2096 * \param vhost: pointer to struct lws_vhost you want set socks for
2097 * \param socks: pointer to c string containing socks in format address:port
2099 * Returns 0 if socks string was parsed and socks was setup.
2100 * Returns -1 if socks is NULL or has incorrect format.
2102 * This is only required if your OS does not provide the socks_proxy
2103 * environment variable (eg, OSX)
2105 * IMPORTANT! You should call this function right after creation of the
2106 * lws_context and before call to connect. If you call this
2107 * function after connect behavior is undefined.
2108 * This function will override proxy settings made on lws_context
2109 * creation with genenv() call.
2111 LWS_VISIBLE LWS_EXTERN int
2112 lws_set_socks(struct lws_vhost *vhost, const char *socks);
2117 * lws_create_vhost() - Create a vhost (virtual server context)
2118 * \param context: pointer to result of lws_create_context()
2119 * \param info: pointer to struct with parameters
2121 * This function creates a virtual server (vhost) using the vhost-related
2122 * members of the info struct. You can create many vhosts inside one context
2123 * if you created the context with the option LWS_SERVER_OPTION_EXPLICIT_VHOSTS
2125 LWS_EXTERN LWS_VISIBLE struct lws_vhost *
2126 lws_create_vhost(struct lws_context *context,
2127 struct lws_context_creation_info *info);
2130 * lwsws_get_config_globals() - Parse a JSON server config file
2131 * \param info: pointer to struct with parameters
2132 * \param d: filepath of the config file
2133 * \param config_strings: storage for the config strings extracted from JSON,
2134 * the pointer is incremented as strings are stored
2135 * \param len: pointer to the remaining length left in config_strings
2136 * the value is decremented as strings are stored
2138 * This function prepares a n lws_context_creation_info struct with global
2139 * settings from a file d.
2141 * Requires CMake option LWS_WITH_LEJP_CONF to have been enabled
2143 LWS_VISIBLE LWS_EXTERN int
2144 lwsws_get_config_globals(struct lws_context_creation_info *info, const char *d,
2145 char **config_strings, int *len);
2148 * lwsws_get_config_vhosts() - Create vhosts from a JSON server config file
2149 * \param context: pointer to result of lws_create_context()
2150 * \param info: pointer to struct with parameters
2151 * \param d: filepath of the config file
2152 * \param config_strings: storage for the config strings extracted from JSON,
2153 * the pointer is incremented as strings are stored
2154 * \param len: pointer to the remaining length left in config_strings
2155 * the value is decremented as strings are stored
2157 * This function creates vhosts into a context according to the settings in
2158 *JSON files found in directory d.
2160 * Requires CMake option LWS_WITH_LEJP_CONF to have been enabled
2162 LWS_VISIBLE LWS_EXTERN int
2163 lwsws_get_config_vhosts(struct lws_context *context,
2164 struct lws_context_creation_info *info, const char *d,
2165 char **config_strings, int *len);
2167 /** lws_vhost_get() - \deprecated deprecated: use lws_get_vhost() */
2168 LWS_VISIBLE LWS_EXTERN struct lws_vhost *
2169 lws_vhost_get(struct lws *wsi) LWS_WARN_DEPRECATED;
2172 * lws_get_vhost() - return the vhost a wsi belongs to
2174 * \param wsi: which connection
2176 LWS_VISIBLE LWS_EXTERN struct lws_vhost *
2177 lws_get_vhost(struct lws *wsi);
2180 * lws_json_dump_vhost() - describe vhost state and stats in JSON
2182 * \param vh: the vhost
2183 * \param buf: buffer to fill with JSON
2184 * \param len: max length of buf
2186 LWS_VISIBLE LWS_EXTERN int
2187 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len);
2190 * lws_json_dump_context() - describe context state and stats in JSON
2192 * \param context: the context
2193 * \param buf: buffer to fill with JSON
2194 * \param len: max length of buf
2196 LWS_VISIBLE LWS_EXTERN int
2197 lws_json_dump_context(const struct lws_context *context, char *buf, int len,
2201 * lws_context_user() - get the user data associated with the context
2202 * \param context: Websocket context
2204 * This returns the optional user allocation that can be attached to
2205 * the context the sockets live in at context_create time. It's a way
2206 * to let all sockets serviced in the same context share data without
2207 * using globals statics in the user code.
2209 LWS_VISIBLE LWS_EXTERN void *
2210 lws_context_user(struct lws_context *context);
2212 /*! \defgroup vhost-mounts Vhost mounts and options
2213 * \ingroup context-and-vhost-creation
2215 * ##Vhost mounts and options
2218 /** struct lws_protocol_vhost_options - linked list of per-vhost protocol
2219 * name=value options
2221 * This provides a general way to attach a linked-list of name=value pairs,
2222 * which can also have an optional child link-list using the options member.
2224 struct lws_protocol_vhost_options {
2225 const struct lws_protocol_vhost_options *next; /**< linked list */
2226 const struct lws_protocol_vhost_options *options; /**< child linked-list of more options for this node */
2227 const char *name; /**< name of name=value pair */
2228 const char *value; /**< value of name=value pair */
2231 /** enum lws_mount_protocols
2232 * This specifies the mount protocol for a mountpoint, whether it is to be
2233 * served from a filesystem, or it is a cgi etc.
2235 enum lws_mount_protocols {
2236 LWSMPRO_HTTP = 0, /**< not supported yet */
2237 LWSMPRO_HTTPS = 1, /**< not supported yet */
2238 LWSMPRO_FILE = 2, /**< serve from filesystem directory */
2239 LWSMPRO_CGI = 3, /**< pass to CGI to handle */
2240 LWSMPRO_REDIR_HTTP = 4, /**< redirect to http:// url */
2241 LWSMPRO_REDIR_HTTPS = 5, /**< redirect to https:// url */
2242 LWSMPRO_CALLBACK = 6, /**< hand by named protocol's callback */
2245 /** struct lws_http_mount
2247 * arguments for mounting something in a vhost's url namespace
2249 struct lws_http_mount {
2250 const struct lws_http_mount *mount_next;
2251 /**< pointer to next struct lws_http_mount */
2252 const char *mountpoint;
2253 /**< mountpoint in http pathspace, eg, "/" */
2255 /**< path to be mounted, eg, "/var/www/warmcat.com" */
2257 /**< default target, eg, "index.html" */
2258 const char *protocol;
2259 /**<"protocol-name" to handle mount */
2261 const struct lws_protocol_vhost_options *cgienv;
2262 /**< optional linked-list of cgi options. These are created
2263 * as environment variables for the cgi process
2265 const struct lws_protocol_vhost_options *extra_mimetypes;
2266 /**< optional linked-list of mimetype mappings */
2267 const struct lws_protocol_vhost_options *interpret;
2268 /**< optional linked-list of files to be interpreted */
2271 /**< seconds cgi is allowed to live, if cgi://mount type */
2273 /**< max-age for reuse of client cache of files, seconds */
2274 unsigned int auth_mask;
2275 /**< bits set here must be set for authorized client session */
2277 unsigned int cache_reusable:1; /**< set if client cache may reuse this */
2278 unsigned int cache_revalidate:1; /**< set if client cache should revalidate on use */
2279 unsigned int cache_intermediaries:1; /**< set if intermediaries are allowed to cache */
2281 unsigned char origin_protocol; /**< one of enum lws_mount_protocols */
2282 unsigned char mountpoint_len; /**< length of mountpoint string */
2284 const char *basic_auth_login_file;
2285 /**<NULL, or filepath to use to check basic auth logins against */
2287 /* Add new things just above here ---^
2288 * This is part of the ABI, don't needlessly break compatibility
2290 * The below is to ensure later library versions with new
2291 * members added above will see 0 (default) even if the app
2292 * was not built against the newer headers.
2295 void *_unused[2]; /**< dummy */
2300 /*! \defgroup client
2303 * ##Client releated functions
2307 /** enum lws_client_connect_ssl_connection_flags - flags that may be used
2308 * with struct lws_client_connect_info ssl_connection member to control if
2309 * and how SSL checks apply to the client connection being created
2312 enum lws_client_connect_ssl_connection_flags {
2313 LCCSCF_USE_SSL = (1 << 0),
2314 LCCSCF_ALLOW_SELFSIGNED = (1 << 1),
2315 LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK = (1 << 2),
2316 LCCSCF_ALLOW_EXPIRED = (1 << 3)
2319 /** struct lws_client_connect_info - parameters to connect with when using
2320 * lws_client_connect_via_info() */
2322 struct lws_client_connect_info {
2323 struct lws_context *context;
2324 /**< lws context to create connection in */
2325 const char *address;
2326 /**< remote address to connect to */
2328 /**< remote port to connect to */
2330 /**< nonzero for ssl */
2334 /**< content of host header */
2336 /**< content of origin header */
2337 const char *protocol;
2338 /**< list of ws protocols we could accept */
2339 int ietf_version_or_minus_one;
2340 /**< deprecated: currently leave at 0 or -1 */
2342 /**< if non-NULL, use this as wsi user_data instead of malloc it */
2343 const void *client_exts;
2344 /**< UNUSED... provide in info.extensions at context creation time */
2346 /**< if non-NULL, do this http method instead of ws[s] upgrade.
2347 * use "GET" to be a simple http client connection */
2348 struct lws *parent_wsi;
2349 /**< if another wsi is responsible for this connection, give it here.
2350 * this is used to make sure if the parent closes so do any
2351 * child connections first. */
2352 const char *uri_replace_from;
2353 /**< if non-NULL, when this string is found in URIs in
2354 * text/html content-encoding, it's replaced with uri_replace_to */
2355 const char *uri_replace_to;
2356 /**< see uri_replace_from */
2357 struct lws_vhost *vhost;
2358 /**< vhost to bind to (used to determine related SSL_CTX) */
2360 /**< if not NULL, store the new wsi here early in the connection
2361 * process. Although we return the new wsi, the call to create the
2362 * client connection does progress the connection somewhat and may
2363 * meet an error that will result in the connection being scrubbed and
2364 * NULL returned. While the wsi exists though, he may process a
2365 * callback like CLIENT_CONNECTION_ERROR with his wsi: this gives the
2366 * user callback a way to identify which wsi it is that faced the error
2367 * even before the new wsi is returned and even if ultimately no wsi
2371 /* Add new things just above here ---^
2372 * This is part of the ABI, don't needlessly break compatibility
2374 * The below is to ensure later library versions with new
2375 * members added above will see 0 (default) even if the app
2376 * was not built against the newer headers.
2379 void *_unused[4]; /**< dummy */
2383 * lws_client_connect_via_info() - Connect to another websocket server
2384 * \param ccinfo: pointer to lws_client_connect_info struct
2386 * This function creates a connection to a remote server using the
2387 * information provided in ccinfo.
2389 LWS_VISIBLE LWS_EXTERN struct lws *
2390 lws_client_connect_via_info(struct lws_client_connect_info * ccinfo);
2393 * lws_client_connect() - Connect to another websocket server
2394 * \deprecated DEPRECATED use lws_client_connect_via_info
2395 * \param clients: Websocket context
2396 * \param address: Remote server address, eg, "myserver.com"
2397 * \param port: Port to connect to on the remote server, eg, 80
2398 * \param ssl_connection: 0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
2400 * \param path: Websocket path on server
2401 * \param host: Hostname on server
2402 * \param origin: Socket origin name
2403 * \param protocol: Comma-separated list of protocols being asked for from
2404 * the server, or just one. The server will pick the one it
2405 * likes best. If you don't want to specify a protocol, which is
2406 * legal, use NULL here.
2407 * \param ietf_version_or_minus_one: -1 to ask to connect using the default, latest
2408 * protocol supported, or the specific protocol ordinal
2410 * This function creates a connection to a remote server
2412 /* deprecated, use lws_client_connect_via_info() */
2413 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
2414 lws_client_connect(struct lws_context *clients, const char *address,
2415 int port, int ssl_connection, const char *path,
2416 const char *host, const char *origin, const char *protocol,
2417 int ietf_version_or_minus_one) LWS_WARN_DEPRECATED;
2418 /* deprecated, use lws_client_connect_via_info() */
2420 * lws_client_connect_extended() - Connect to another websocket server
2421 * \deprecated DEPRECATED use lws_client_connect_via_info
2422 * \param clients: Websocket context
2423 * \param address: Remote server address, eg, "myserver.com"
2424 * \param port: Port to connect to on the remote server, eg, 80
2425 * \param ssl_connection: 0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
2427 * \param path: Websocket path on server
2428 * \param host: Hostname on server
2429 * \param origin: Socket origin name
2430 * \param protocol: Comma-separated list of protocols being asked for from
2431 * the server, or just one. The server will pick the one it
2433 * \param ietf_version_or_minus_one: -1 to ask to connect using the default, latest
2434 * protocol supported, or the specific protocol ordinal
2435 * \param userdata: Pre-allocated user data
2437 * This function creates a connection to a remote server
2439 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
2440 lws_client_connect_extended(struct lws_context *clients, const char *address,
2441 int port, int ssl_connection, const char *path,
2442 const char *host, const char *origin,
2443 const char *protocol, int ietf_version_or_minus_one,
2444 void *userdata) LWS_WARN_DEPRECATED;
2447 * lws_init_vhost_client_ssl() - also enable client SSL on an existing vhost
2449 * \param info: client ssl related info
2450 * \param vhost: which vhost to initialize client ssl operations on
2452 * You only need to call this if you plan on using SSL client connections on
2453 * the vhost. For non-SSL client connections, it's not necessary to call this.
2455 * The following members of info are used during the call
2457 * - options must have LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT set,
2458 * otherwise the call does nothing
2459 * - provided_client_ssl_ctx must be NULL to get a generated client
2460 * ssl context, otherwise you can pass a prepared one in by setting it
2461 * - ssl_cipher_list may be NULL or set to the client valid cipher list
2462 * - ssl_ca_filepath may be NULL or client cert filepath
2463 * - ssl_cert_filepath may be NULL or client cert filepath
2464 * - ssl_private_key_filepath may be NULL or client cert private key
2466 * You must create your vhost explicitly if you want to use this, so you have
2467 * a pointer to the vhost. Create the context first with the option flag
2468 * LWS_SERVER_OPTION_EXPLICIT_VHOSTS and then call lws_create_vhost() with
2469 * the same info struct.
2471 LWS_VISIBLE LWS_EXTERN int
2472 lws_init_vhost_client_ssl(const struct lws_context_creation_info *info,
2473 struct lws_vhost *vhost);
2475 * lws_http_client_read() - consume waiting received http client data
2477 * \param wsi: client connection
2478 * \param buf: pointer to buffer pointer - fill with pointer to your buffer
2479 * \param len: pointer to chunk length - fill with max length of buffer
2481 * This is called when the user code is notified client http data has arrived.
2482 * The user code may choose to delay calling it to consume the data, for example
2483 * waiting until an onward connection is writeable.
2485 * For non-chunked connections, up to len bytes of buf are filled with the
2486 * received content. len is set to the actual amount filled before return.
2488 * For chunked connections, the linear buffer content contains the chunking
2489 * headers and it cannot be passed in one lump. Instead, this function will
2490 * call back LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ with in pointing to the
2491 * chunk start and len set to the chunk length. There will be as many calls
2492 * as there are chunks or partial chunks in the buffer.
2494 LWS_VISIBLE LWS_EXTERN int
2495 lws_http_client_read(struct lws *wsi, char **buf, int *len);
2498 * lws_http_client_http_response() - get last HTTP response code
2500 * \param wsi: client connection
2502 * Returns the last server response code, eg, 200 for client http connections.
2504 LWS_VISIBLE LWS_EXTERN unsigned int
2505 lws_http_client_http_response(struct lws *wsi);
2507 LWS_VISIBLE LWS_EXTERN void
2508 lws_client_http_body_pending(struct lws *wsi, int something_left_to_send);
2511 * lws_client_http_body_pending() - control if client connection neeeds to send body
2513 * \param wsi: client connection
2514 * \param something_left_to_send: nonzero if need to send more body, 0 (default)
2515 * if nothing more to send
2517 * If you will send payload data with your HTTP client connection, eg, for POST,
2518 * when you set the related http headers in
2519 * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER callback you should also call
2520 * this API with something_left_to_send nonzero, and call
2521 * lws_callback_on_writable(wsi);
2523 * After sending the headers, lws will call your callback with
2524 * LWS_CALLBACK_CLIENT_HTTP_WRITEABLE reason when writable. You can send the
2525 * next part of the http body payload, calling lws_callback_on_writable(wsi);
2526 * if there is more to come, or lws_client_http_body_pending(wsi, 0); to
2527 * let lws know the last part is sent and the connection can move on.
2532 /** \defgroup service Built-in service loop entry
2534 * ##Built-in service loop entry
2536 * If you're not using libev / libuv, these apis are needed to enter the poll()
2537 * wait in lws and service any connections with pending events.
2542 * lws_service() - Service any pending websocket activity
2543 * \param context: Websocket context
2544 * \param timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
2545 * service otherwise block and service immediately, returning
2546 * after the timeout if nothing needed service.
2548 * This function deals with any pending websocket traffic, for three
2549 * kinds of event. It handles these events on both server and client
2550 * types of connection the same.
2552 * 1) Accept new connections to our context's server
2554 * 2) Call the receive callback for incoming frame data received by
2555 * server or client connections.
2557 * You need to call this service function periodically to all the above
2558 * functions to happen; if your application is single-threaded you can
2559 * just call it in your main event loop.
2561 * Alternatively you can fork a new process that asynchronously handles
2562 * calling this service in a loop. In that case you are happy if this
2563 * call blocks your thread until it needs to take care of something and
2564 * would call it with a large nonzero timeout. Your loop then takes no
2565 * CPU while there is nothing happening.
2567 * If you are calling it in a single-threaded app, you don't want it to
2568 * wait around blocking other things in your loop from happening, so you
2569 * would call it with a timeout_ms of 0, so it returns immediately if
2570 * nothing is pending, or as soon as it services whatever was pending.
2572 LWS_VISIBLE LWS_EXTERN int
2573 lws_service(struct lws_context *context, int timeout_ms);
2576 * lws_service() - Service any pending websocket activity
2578 * \param context: Websocket context
2579 * \param timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
2580 * service otherwise block and service immediately, returning
2581 * after the timeout if nothing needed service.
2583 * Same as lws_service(), but for a specific thread service index. Only needed
2584 * if you are spawning multiple service threads.
2586 LWS_VISIBLE LWS_EXTERN int
2587 lws_service_tsi(struct lws_context *context, int timeout_ms, int tsi);
2590 * lws_cancel_service_pt() - Cancel servicing of pending socket activity
2592 * \param wsi: Cancel service on the thread this wsi is serviced by
2594 * This function lets a call to lws_service() waiting for a timeout
2595 * immediately return.
2597 * It works by creating a phony event and then swallowing it silently.
2599 * The reason it may be needed is when waiting in poll(), changes to
2600 * the event masks are ignored by the OS until poll() is reentered. This
2601 * lets you halt the poll() wait and make the reentry happen immediately
2602 * instead of having the wait out the rest of the poll timeout.
2604 LWS_VISIBLE LWS_EXTERN void
2605 lws_cancel_service_pt(struct lws *wsi);
2608 * lws_cancel_service() - Cancel wait for new pending socket activity
2609 * \param context: Websocket context
2611 * This function let a call to lws_service() waiting for a timeout
2612 * immediately return.
2614 * What it basically does is provide a fake event that will be swallowed,
2615 * so the wait in poll() is ended. That's useful because poll() doesn't
2616 * attend to changes in POLLIN/OUT/ERR until it re-enters the wait.
2618 LWS_VISIBLE LWS_EXTERN void
2619 lws_cancel_service(struct lws_context *context);
2622 * lws_service_fd() - Service polled socket with something waiting
2623 * \param context: Websocket context
2624 * \param pollfd: The pollfd entry describing the socket fd and which events
2625 * happened, or NULL to tell lws to do only timeout servicing.
2627 * This function takes a pollfd that has POLLIN or POLLOUT activity and
2628 * services it according to the state of the associated
2631 * The one call deals with all "service" that might happen on a socket
2632 * including listen accepts, http files as well as websocket protocol.
2634 * If a pollfd says it has something, you can just pass it to
2635 * lws_service_fd() whether it is a socket handled by lws or not.
2636 * If it sees it is a lws socket, the traffic will be handled and
2637 * pollfd->revents will be zeroed now.
2639 * If the socket is foreign to lws, it leaves revents alone. So you can
2640 * see if you should service yourself by checking the pollfd revents
2641 * after letting lws try to service it.
2643 * You should also call this with pollfd = NULL to just allow the
2644 * once-per-second global timeout checks; if less than a second since the last
2645 * check it returns immediately then.
2647 LWS_VISIBLE LWS_EXTERN int
2648 lws_service_fd(struct lws_context *context, struct lws_pollfd *pollfd);
2651 * lws_service_fd_tsi() - Service polled socket in specific service thread
2652 * \param context: Websocket context
2653 * \param pollfd: The pollfd entry describing the socket fd and which events
2655 * \param tsi: thread service index
2657 * Same as lws_service_fd() but used with multiple service threads
2659 LWS_VISIBLE LWS_EXTERN int
2660 lws_service_fd_tsi(struct lws_context *context, struct lws_pollfd *pollfd,
2664 * lws_service_adjust_timeout() - Check for any connection needing forced service
2665 * \param context: Websocket context
2666 * \param timeout_ms: The original poll timeout value. You can just set this
2667 * to 1 if you don't really have a poll timeout.
2668 * \param tsi: thread service index
2670 * Under some conditions connections may need service even though there is no
2671 * pending network action on them, this is "forced service". For default
2672 * poll() and libuv / libev, the library takes care of calling this and
2673 * dealing with it for you. But for external poll() integration, you need
2674 * access to the apis.
2676 * If anybody needs "forced service", returned timeout is zero. In that case,
2677 * you can call lws_service_tsi() with a timeout of -1 to only service
2678 * guys who need forced service.
2680 LWS_VISIBLE LWS_EXTERN int
2681 lws_service_adjust_timeout(struct lws_context *context, int timeout_ms, int tsi);
2683 /* Backwards compatibility */
2684 #define lws_plat_service_tsi lws_service_tsi
2688 /*! \defgroup http HTTP
2690 Modules related to handling HTTP
2694 /*! \defgroup httpft HTTP File transfer
2697 APIs for sending local files in response to HTTP requests
2702 * lws_get_mimetype() - Determine mimetype to use from filename
2704 * \param file: filename
2705 * \param m: NULL, or mount context
2707 * This uses a canned list of known filetypes first, if no match and m is
2708 * non-NULL, then tries a list of per-mount file suffix to mimtype mappings.
2710 * Returns either NULL or a pointer to the mimetype matching the file.
2712 LWS_VISIBLE LWS_EXTERN const char *
2713 lws_get_mimetype(const char *file, const struct lws_http_mount *m);
2716 * lws_serve_http_file() - Send a file back to the client using http
2717 * \param wsi: Websocket instance (available from user callback)
2718 * \param file: The file to issue over http
2719 * \param content_type: The http content type, eg, text/html
2720 * \param other_headers: NULL or pointer to header string
2721 * \param other_headers_len: length of the other headers if non-NULL
2723 * This function is intended to be called from the callback in response
2724 * to http requests from the client. It allows the callback to issue
2725 * local files down the http link in a single step.
2727 * Returning <0 indicates error and the wsi should be closed. Returning
2728 * >0 indicates the file was completely sent and
2729 * lws_http_transaction_completed() called on the wsi (and close if != 0)
2730 * ==0 indicates the file transfer is started and needs more service later,
2731 * the wsi should be left alone.
2733 LWS_VISIBLE LWS_EXTERN int
2734 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
2735 const char *other_headers, int other_headers_len);
2737 LWS_VISIBLE LWS_EXTERN int
2738 lws_serve_http_file_fragment(struct lws *wsi);
2741 /*! \defgroup html-chunked-substitution HTML Chunked Substitution
2744 * ##HTML chunked Substitution
2746 * APIs for receiving chunks of text, replacing a set of variable names via
2747 * a callback, and then prepending and appending HTML chunked encoding
2753 HTTP_STATUS_OK = 200,
2754 HTTP_STATUS_NO_CONTENT = 204,
2755 HTTP_STATUS_PARTIAL_CONTENT = 206,
2757 HTTP_STATUS_MOVED_PERMANENTLY = 301,
2758 HTTP_STATUS_FOUND = 302,
2759 HTTP_STATUS_SEE_OTHER = 303,
2760 HTTP_STATUS_NOT_MODIFIED = 304,
2762 HTTP_STATUS_BAD_REQUEST = 400,
2763 HTTP_STATUS_UNAUTHORIZED,
2764 HTTP_STATUS_PAYMENT_REQUIRED,
2765 HTTP_STATUS_FORBIDDEN,
2766 HTTP_STATUS_NOT_FOUND,
2767 HTTP_STATUS_METHOD_NOT_ALLOWED,
2768 HTTP_STATUS_NOT_ACCEPTABLE,
2769 HTTP_STATUS_PROXY_AUTH_REQUIRED,
2770 HTTP_STATUS_REQUEST_TIMEOUT,
2771 HTTP_STATUS_CONFLICT,
2773 HTTP_STATUS_LENGTH_REQUIRED,
2774 HTTP_STATUS_PRECONDITION_FAILED,
2775 HTTP_STATUS_REQ_ENTITY_TOO_LARGE,
2776 HTTP_STATUS_REQ_URI_TOO_LONG,
2777 HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE,
2778 HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE,
2779 HTTP_STATUS_EXPECTATION_FAILED,
2781 HTTP_STATUS_INTERNAL_SERVER_ERROR = 500,
2782 HTTP_STATUS_NOT_IMPLEMENTED,
2783 HTTP_STATUS_BAD_GATEWAY,
2784 HTTP_STATUS_SERVICE_UNAVAILABLE,
2785 HTTP_STATUS_GATEWAY_TIMEOUT,
2786 HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED,
2789 struct lws_process_html_args {
2790 char *p; /**< pointer to the buffer containing the data */
2791 int len; /**< length of the original data at p */
2792 int max_len; /**< maximum length we can grow the data to */
2793 int final; /**< set if this is the last chunk of the file */
2796 typedef const char *(*lws_process_html_state_cb)(void *data, int index);
2798 struct lws_process_html_state {
2799 char *start; /**< pointer to start of match */
2800 char swallow[16]; /**< matched character buffer */
2801 int pos; /**< position in match */
2802 void *data; /**< opaque pointer */
2803 const char * const *vars; /**< list of variable names */
2804 int count_vars; /**< count of variable names */
2806 lws_process_html_state_cb replace; /**< called on match to perform substitution */
2809 /*! lws_chunked_html_process() - generic chunked substitution
2810 * \param args: buffer to process using chunked encoding
2811 * \param s: current processing state
2813 LWS_VISIBLE LWS_EXTERN int
2814 lws_chunked_html_process(struct lws_process_html_args *args,
2815 struct lws_process_html_state *s);
2818 /** \defgroup HTTP-headers-read HTTP headers: read
2821 * ##HTTP header releated functions
2823 * In lws the client http headers are temporarily stored in a pool, only for the
2824 * duration of the http part of the handshake. It's because in most cases,
2825 * the header content is ignored for the whole rest of the connection lifetime
2826 * and would then just be taking up space needlessly.
2828 * During LWS_CALLBACK_HTTP when the URI path is delivered is the last time
2829 * the http headers are still allocated, you can use these apis then to
2830 * look at and copy out interesting header content (cookies, etc)
2832 * Notice that the header total length reported does not include a terminating
2833 * '\0', however you must allocate for it when using the _copy apis. So the
2834 * length reported for a header containing "123" is 3, but you must provide
2835 * a buffer of length 4 so that "123\0" may be copied into it, or the copy
2836 * will fail with a nonzero return code.
2838 * In the special case of URL arguments, like ?x=1&y=2, the arguments are
2839 * stored in a token named for the method, eg, WSI_TOKEN_GET_URI if it
2840 * was a GET or WSI_TOKEN_POST_URI if POST. You can check the total
2841 * length to confirm the method.
2843 * For URL arguments, each argument is stored urldecoded in a "fragment", so
2844 * you can use the fragment-aware api lws_hdr_copy_fragment() to access each
2845 * argument in turn: the fragments contain urldecoded strings like x=1 or y=2.
2847 * As a convenience, lws has an api that will find the fragment with a
2848 * given name= part, lws_get_urlarg_by_name().
2852 /** struct lws_tokens
2853 * you need these to look at headers that have been parsed if using the
2854 * LWS_CALLBACK_FILTER_CONNECTION callback. If a header from the enum
2855 * list below is absent, .token = NULL and token_len = 0. Otherwise .token
2856 * points to .token_len chars containing that header content.
2859 char *token; /**< pointer to start of the token */
2860 int token_len; /**< length of the token's value */
2863 /* enum lws_token_indexes
2864 * these have to be kept in sync with lextable.h / minilex.c
2866 * NOTE: These public enums are part of the abi. If you want to add one,
2867 * add it at where specified so existing users are unaffected.
2869 enum lws_token_indexes {
2870 WSI_TOKEN_GET_URI = 0,
2871 WSI_TOKEN_POST_URI = 1,
2872 WSI_TOKEN_OPTIONS_URI = 2,
2874 WSI_TOKEN_CONNECTION = 4,
2875 WSI_TOKEN_UPGRADE = 5,
2876 WSI_TOKEN_ORIGIN = 6,
2877 WSI_TOKEN_DRAFT = 7,
2878 WSI_TOKEN_CHALLENGE = 8,
2879 WSI_TOKEN_EXTENSIONS = 9,
2880 WSI_TOKEN_KEY1 = 10,
2881 WSI_TOKEN_KEY2 = 11,
2882 WSI_TOKEN_PROTOCOL = 12,
2883 WSI_TOKEN_ACCEPT = 13,
2884 WSI_TOKEN_NONCE = 14,
2885 WSI_TOKEN_HTTP = 15,
2886 WSI_TOKEN_HTTP2_SETTINGS = 16,
2887 WSI_TOKEN_HTTP_ACCEPT = 17,
2888 WSI_TOKEN_HTTP_AC_REQUEST_HEADERS = 18,
2889 WSI_TOKEN_HTTP_IF_MODIFIED_SINCE = 19,
2890 WSI_TOKEN_HTTP_IF_NONE_MATCH = 20,
2891 WSI_TOKEN_HTTP_ACCEPT_ENCODING = 21,
2892 WSI_TOKEN_HTTP_ACCEPT_LANGUAGE = 22,
2893 WSI_TOKEN_HTTP_PRAGMA = 23,
2894 WSI_TOKEN_HTTP_CACHE_CONTROL = 24,
2895 WSI_TOKEN_HTTP_AUTHORIZATION = 25,
2896 WSI_TOKEN_HTTP_COOKIE = 26,
2897 WSI_TOKEN_HTTP_CONTENT_LENGTH = 27,
2898 WSI_TOKEN_HTTP_CONTENT_TYPE = 28,
2899 WSI_TOKEN_HTTP_DATE = 29,
2900 WSI_TOKEN_HTTP_RANGE = 30,
2901 WSI_TOKEN_HTTP_REFERER = 31,
2903 WSI_TOKEN_VERSION = 33,
2904 WSI_TOKEN_SWORIGIN = 34,
2906 WSI_TOKEN_HTTP_COLON_AUTHORITY = 35,
2907 WSI_TOKEN_HTTP_COLON_METHOD = 36,
2908 WSI_TOKEN_HTTP_COLON_PATH = 37,
2909 WSI_TOKEN_HTTP_COLON_SCHEME = 38,
2910 WSI_TOKEN_HTTP_COLON_STATUS = 39,
2912 WSI_TOKEN_HTTP_ACCEPT_CHARSET = 40,
2913 WSI_TOKEN_HTTP_ACCEPT_RANGES = 41,
2914 WSI_TOKEN_HTTP_ACCESS_CONTROL_ALLOW_ORIGIN = 42,
2915 WSI_TOKEN_HTTP_AGE = 43,
2916 WSI_TOKEN_HTTP_ALLOW = 44,
2917 WSI_TOKEN_HTTP_CONTENT_DISPOSITION = 45,
2918 WSI_TOKEN_HTTP_CONTENT_ENCODING = 46,
2919 WSI_TOKEN_HTTP_CONTENT_LANGUAGE = 47,
2920 WSI_TOKEN_HTTP_CONTENT_LOCATION = 48,
2921 WSI_TOKEN_HTTP_CONTENT_RANGE = 49,
2922 WSI_TOKEN_HTTP_ETAG = 50,
2923 WSI_TOKEN_HTTP_EXPECT = 51,
2924 WSI_TOKEN_HTTP_EXPIRES = 52,
2925 WSI_TOKEN_HTTP_FROM = 53,
2926 WSI_TOKEN_HTTP_IF_MATCH = 54,
2927 WSI_TOKEN_HTTP_IF_RANGE = 55,
2928 WSI_TOKEN_HTTP_IF_UNMODIFIED_SINCE = 56,
2929 WSI_TOKEN_HTTP_LAST_MODIFIED = 57,
2930 WSI_TOKEN_HTTP_LINK = 58,
2931 WSI_TOKEN_HTTP_LOCATION = 59,
2932 WSI_TOKEN_HTTP_MAX_FORWARDS = 60,
2933 WSI_TOKEN_HTTP_PROXY_AUTHENTICATE = 61,
2934 WSI_TOKEN_HTTP_PROXY_AUTHORIZATION = 62,
2935 WSI_TOKEN_HTTP_REFRESH = 63,
2936 WSI_TOKEN_HTTP_RETRY_AFTER = 64,
2937 WSI_TOKEN_HTTP_SERVER = 65,
2938 WSI_TOKEN_HTTP_SET_COOKIE = 66,
2939 WSI_TOKEN_HTTP_STRICT_TRANSPORT_SECURITY = 67,
2940 WSI_TOKEN_HTTP_TRANSFER_ENCODING = 68,
2941 WSI_TOKEN_HTTP_USER_AGENT = 69,
2942 WSI_TOKEN_HTTP_VARY = 70,
2943 WSI_TOKEN_HTTP_VIA = 71,
2944 WSI_TOKEN_HTTP_WWW_AUTHENTICATE = 72,
2946 WSI_TOKEN_PATCH_URI = 73,
2947 WSI_TOKEN_PUT_URI = 74,
2948 WSI_TOKEN_DELETE_URI = 75,
2950 WSI_TOKEN_HTTP_URI_ARGS = 76,
2951 WSI_TOKEN_PROXY = 77,
2952 WSI_TOKEN_HTTP_X_REAL_IP = 78,
2953 WSI_TOKEN_HTTP1_0 = 79,
2954 WSI_TOKEN_X_FORWARDED_FOR = 80,
2955 WSI_TOKEN_CONNECT = 81,
2956 /****** add new things just above ---^ ******/
2958 /* use token storage to stash these internally, not for
2961 _WSI_TOKEN_CLIENT_SENT_PROTOCOLS,
2962 _WSI_TOKEN_CLIENT_PEER_ADDRESS,
2963 _WSI_TOKEN_CLIENT_URI,
2964 _WSI_TOKEN_CLIENT_HOST,
2965 _WSI_TOKEN_CLIENT_ORIGIN,
2966 _WSI_TOKEN_CLIENT_METHOD,
2968 /* always last real token index*/
2971 /* parser state additions, no storage associated */
2972 WSI_TOKEN_NAME_PART,
2974 WSI_TOKEN_SKIPPING_SAW_CR,
2975 WSI_PARSING_COMPLETE,
2976 WSI_INIT_TOKEN_MUXURL,
2979 struct lws_token_limits {
2980 unsigned short token_limit[WSI_TOKEN_COUNT]; /**< max chars for this token */
2984 * lws_token_to_string() - returns a textual representation of a hdr token index
2986 * \param: token index
2988 LWS_VISIBLE LWS_EXTERN const unsigned char *
2989 lws_token_to_string(enum lws_token_indexes token);
2993 * lws_hdr_total_length: report length of all fragments of a header totalled up
2994 * The returned length does not include the space for a
2997 * \param wsi: websocket connection
2998 * \param h: which header index we are interested in
3000 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3001 lws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h);
3004 * lws_hdr_fragment_length: report length of a single fragment of a header
3005 * The returned length does not include the space for a
3008 * \param wsi: websocket connection
3009 * \param h: which header index we are interested in
3010 * \param frag_idx: which fragment of h we want to get the length of
3012 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3013 lws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx);
3016 * lws_hdr_copy() - copy a single fragment of the given header to a buffer
3017 * The buffer length len must include space for an additional
3018 * terminating '\0', or it will fail returning -1.
3020 * \param wsi: websocket connection
3021 * \param dest: destination buffer
3022 * \param len: length of destination buffer
3023 * \param h: which header index we are interested in
3025 * copies the whole, aggregated header, even if it was delivered in
3026 * several actual headers piece by piece
3028 LWS_VISIBLE LWS_EXTERN int
3029 lws_hdr_copy(struct lws *wsi, char *dest, int len, enum lws_token_indexes h);
3032 * lws_hdr_copy_fragment() - copy a single fragment of the given header to a buffer
3033 * The buffer length len must include space for an additional
3034 * terminating '\0', or it will fail returning -1.
3035 * If the requested fragment index is not present, it fails
3038 * \param wsi: websocket connection
3039 * \param dest: destination buffer
3040 * \param len: length of destination buffer
3041 * \param h: which header index we are interested in
3042 * \param frag_idx: which fragment of h we want to copy
3044 * Normally this is only useful
3045 * to parse URI arguments like ?x=1&y=2, token index WSI_TOKEN_HTTP_URI_ARGS
3046 * fragment 0 will contain "x=1" and fragment 1 "y=2"
3048 LWS_VISIBLE LWS_EXTERN int
3049 lws_hdr_copy_fragment(struct lws *wsi, char *dest, int len,
3050 enum lws_token_indexes h, int frag_idx);
3053 * lws_get_urlarg_by_name() - return pointer to arg value if present
3054 * \param wsi: the connection to check
3055 * \param name: the arg name, like "token="
3056 * \param buf: the buffer to receive the urlarg (including the name= part)
3057 * \param len: the length of the buffer to receive the urlarg
3059 * Returns NULL if not found or a pointer inside buf to just after the
3062 LWS_VISIBLE LWS_EXTERN const char *
3063 lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len);
3066 /*! \defgroup HTTP-headers-create HTTP headers: create
3068 * ## HTTP headers: Create
3070 * These apis allow you to create HTTP response headers in a way compatible with
3071 * both HTTP/1.x and HTTP/2.
3073 * They each append to a buffer taking care about the buffer end, which is
3074 * passed in as a pointer. When data is written to the buffer, the current
3075 * position p is updated accordingly.
3077 * All of these apis are LWS_WARN_UNUSED_RESULT as they can run out of space
3078 * and fail with nonzero return.
3082 #define LWSAHH_CODE_MASK ((1 << 16) - 1)
3083 #define LWSAHH_FLAG_NO_SERVER_NAME (1 << 30)
3086 * lws_add_http_header_status() - add the HTTP response status code
3088 * \param wsi: the connection to check
3089 * \param code: an HTTP code like 200, 404 etc (see enum http_status)
3090 * \param p: pointer to current position in buffer pointer
3091 * \param end: pointer to end of buffer
3093 * Adds the initial response code, so should be called first.
3095 * Code may additionally take OR'd flags:
3097 * LWSAHH_FLAG_NO_SERVER_NAME: don't apply server name header this time
3099 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3100 lws_add_http_header_status(struct lws *wsi,
3101 unsigned int code, unsigned char **p,
3102 unsigned char *end);
3104 * lws_add_http_header_by_name() - append named header and value
3106 * \param wsi: the connection to check
3107 * \param name: the hdr name, like "my-header"
3108 * \param value: the value after the = for this header
3109 * \param length: the length of the value
3110 * \param p: pointer to current position in buffer pointer
3111 * \param end: pointer to end of buffer
3113 * Appends name: value to the headers
3115 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3116 lws_add_http_header_by_name(struct lws *wsi, const unsigned char *name,
3117 const unsigned char *value, int length,
3118 unsigned char **p, unsigned char *end);
3120 * lws_add_http_header_by_token() - append given header and value
3122 * \param wsi: the connection to check
3123 * \param token: the token index for the hdr
3124 * \param value: the value after the = for this header
3125 * \param length: the length of the value
3126 * \param p: pointer to current position in buffer pointer
3127 * \param end: pointer to end of buffer
3129 * Appends name=value to the headers, but is able to take advantage of better
3130 * HTTP/2 coding mechanisms where possible.
3132 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3133 lws_add_http_header_by_token(struct lws *wsi, enum lws_token_indexes token,
3134 const unsigned char *value, int length,
3135 unsigned char **p, unsigned char *end);
3137 * lws_add_http_header_content_length() - append content-length helper
3139 * \param wsi: the connection to check
3140 * \param content_length: the content length to use
3141 * \param p: pointer to current position in buffer pointer
3142 * \param end: pointer to end of buffer
3144 * Appends content-length: content_length to the headers
3146 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3147 lws_add_http_header_content_length(struct lws *wsi,
3148 unsigned long content_length,
3149 unsigned char **p, unsigned char *end);
3151 * lws_finalize_http_header() - terminate header block
3153 * \param wsi: the connection to check
3154 * \param p: pointer to current position in buffer pointer
3155 * \param end: pointer to end of buffer
3157 * Indicates no more headers will be added
3159 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3160 lws_finalize_http_header(struct lws *wsi, unsigned char **p,
3161 unsigned char *end);
3164 /** \defgroup form-parsing Form Parsing
3166 * ##POSTed form parsing functions
3168 * These lws_spa (stateful post arguments) apis let you parse and urldecode
3169 * POSTed form arguments, both using simple urlencoded and multipart transfer
3172 * It's capable of handling file uploads as well a named input parsing,
3173 * and the apis are the same for both form upload styles.
3175 * You feed it a list of parameter names and it creates pointers to the
3176 * urldecoded arguments: file upload parameters pass the file data in chunks to
3177 * a user-supplied callback as they come.
3179 * Since it's stateful, it handles the incoming data needing more than one
3180 * POST_BODY callback and has no limit on uploaded file size.
3184 /** enum lws_spa_fileupload_states */
3185 enum lws_spa_fileupload_states {
3187 /**< a chunk of file content has arrived */
3188 LWS_UFS_FINAL_CONTENT,
3189 /**< the last chunk (possibly zero length) of file content has arrived */
3191 /**< a new file is starting to arrive */
3195 * lws_spa_fileupload_cb() - callback to receive file upload data
3197 * \param data: opt_data pointer set in lws_spa_create
3198 * \param name: name of the form field being uploaded
3199 * \param filename: original filename from client
3200 * \param buf: start of data to receive
3201 * \param len: length of data to receive
3202 * \param state: information about how this call relates to file
3204 * Notice name and filename shouldn't be trusted, as they are passed from
3205 * HTTP provided by the client.
3207 typedef int (*lws_spa_fileupload_cb)(void *data, const char *name,
3208 const char *filename, char *buf, int len,
3209 enum lws_spa_fileupload_states state);
3211 /** struct lws_spa - opaque urldecode parser capable of handling multipart
3212 * and file uploads */
3216 * lws_spa_create() - create urldecode parser
3218 * \param wsi: lws connection (used to find Content Type)
3219 * \param param_names: array of form parameter names, like "username"
3220 * \param count_params: count of param_names
3221 * \param max_storage: total amount of form parameter values we can store
3222 * \param opt_cb: NULL, or callback to receive file upload data.
3223 * \param opt_data: NULL, or user pointer provided to opt_cb.
3225 * Creates a urldecode parser and initializes it.
3227 * opt_cb can be NULL if you just want normal name=value parsing, however
3228 * if one or more entries in your form are bulk data (file transfer), you
3229 * can provide this callback and filter on the name callback parameter to
3230 * treat that urldecoded data separately. The callback should return -1
3231 * in case of fatal error, and 0 if OK.
3233 LWS_VISIBLE LWS_EXTERN struct lws_spa *
3234 lws_spa_create(struct lws *wsi, const char * const *param_names,
3235 int count_params, int max_storage, lws_spa_fileupload_cb opt_cb,
3239 * lws_spa_process() - parses a chunk of input data
3241 * \param spa: the parser object previously created
3242 * \param in: incoming, urlencoded data
3243 * \param len: count of bytes valid at \param in
3245 LWS_VISIBLE LWS_EXTERN int
3246 lws_spa_process(struct lws_spa *spa, const char *in, int len);
3249 * lws_spa_finalize() - indicate incoming data completed
3251 * \param spa: the parser object previously created
3253 LWS_VISIBLE LWS_EXTERN int
3254 lws_spa_finalize(struct lws_spa *spa);
3257 * lws_spa_get_length() - return length of parameter value
3259 * \param spa: the parser object previously created
3260 * \param n: parameter ordinal to return length of value for
3262 LWS_VISIBLE LWS_EXTERN int
3263 lws_spa_get_length(struct lws_spa *spa, int n);
3266 * lws_spa_get_string() - return pointer to parameter value
3267 * \param spa: the parser object previously created
3268 * \param n: parameter ordinal to return pointer to value for
3270 LWS_VISIBLE LWS_EXTERN const char *
3271 lws_spa_get_string(struct lws_spa *spa, int n);
3274 * lws_spa_destroy() - destroy parser object
3276 * \param spa: the parser object previously created
3278 LWS_VISIBLE LWS_EXTERN int
3279 lws_spa_destroy(struct lws_spa *spa);
3282 /*! \defgroup urlendec Urlencode and Urldecode
3285 * ##HTML chunked Substitution
3287 * APIs for receiving chunks of text, replacing a set of variable names via
3288 * a callback, and then prepending and appending HTML chunked encoding
3294 * lws_urlencode() - like strncpy but with urlencoding
3296 * \param escaped: output buffer
3297 * \param string: input buffer ('/0' terminated)
3298 * \param len: output buffer max length
3300 * Because urlencoding expands the output string, it's not
3301 * possible to do it in-place, ie, with escaped == string
3303 LWS_VISIBLE LWS_EXTERN const char *
3304 lws_urlencode(char *escaped, const char *string, int len);
3309 * This simple urldecode only operates until the first '\0' and requires the
3310 * data to exist all at once
3313 * lws_urldecode() - like strncpy but with urldecoding
3315 * \param string: output buffer
3316 * \param escaped: input buffer ('\0' terminated)
3317 * \param len: output buffer max length
3319 * This is only useful for '\0' terminated strings
3321 * Since urldecoding only shrinks the output string, it is possible to
3322 * do it in-place, ie, string == escaped
3324 LWS_VISIBLE LWS_EXTERN int
3325 lws_urldecode(char *string, const char *escaped, int len);
3328 * lws_return_http_status() - Return simple http status
3329 * \param wsi: Websocket instance (available from user callback)
3330 * \param code: Status index, eg, 404
3331 * \param html_body: User-readable HTML description < 1KB, or NULL
3333 * Helper to report HTTP errors back to the client cleanly and
3336 LWS_VISIBLE LWS_EXTERN int
3337 lws_return_http_status(struct lws *wsi, unsigned int code,
3338 const char *html_body);
3341 * lws_http_redirect() - write http redirect into buffer
3343 * \param wsi: websocket connection
3344 * \param code: HTTP response code (eg, 301)
3345 * \param loc: where to redirect to
3346 * \param len: length of loc
3347 * \param p: pointer current position in buffer (updated as we write)
3348 * \param end: pointer to end of buffer
3350 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3351 lws_http_redirect(struct lws *wsi, int code, const unsigned char *loc, int len,
3352 unsigned char **p, unsigned char *end);
3355 * lws_http_transaction_completed() - wait for new http transaction or close
3356 * \param wsi: websocket connection
3358 * Returns 1 if the HTTP connection must close now
3359 * Returns 0 and resets connection to wait for new HTTP header /
3360 * transaction if possible
3362 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3363 lws_http_transaction_completed(struct lws *wsi);
3366 /*! \defgroup pur Sanitize / purify SQL and JSON helpers
3368 * ##Sanitize / purify SQL and JSON helpers
3370 * APIs for escaping untrusted JSON and SQL safely before use
3375 * lws_sql_purify() - like strncpy but with escaping for sql quotes
3377 * \param escaped: output buffer
3378 * \param string: input buffer ('/0' terminated)
3379 * \param len: output buffer max length
3381 * Because escaping expands the output string, it's not
3382 * possible to do it in-place, ie, with escaped == string
3384 LWS_VISIBLE LWS_EXTERN const char *
3385 lws_sql_purify(char *escaped, const char *string, int len);
3388 * lws_json_purify() - like strncpy but with escaping for json chars
3390 * \param escaped: output buffer
3391 * \param string: input buffer ('/0' terminated)
3392 * \param len: output buffer max length
3394 * Because escaping expands the output string, it's not
3395 * possible to do it in-place, ie, with escaped == string
3397 LWS_VISIBLE LWS_EXTERN const char *
3398 lws_json_purify(char *escaped, const char *string, int len);
3401 /*! \defgroup ev libev helpers
3405 * APIs specific to libev event loop itegration
3409 #ifdef LWS_USE_LIBEV
3410 typedef void (lws_ev_signal_cb_t)(EV_P_ struct ev_signal *w, int revents);
3412 LWS_VISIBLE LWS_EXTERN int
3413 lws_ev_sigint_cfg(struct lws_context *context, int use_ev_sigint,
3414 lws_ev_signal_cb_t *cb);
3416 LWS_VISIBLE LWS_EXTERN int
3417 lws_ev_initloop(struct lws_context *context, struct ev_loop *loop, int tsi);
3419 LWS_VISIBLE LWS_EXTERN void
3420 lws_ev_sigint_cb(struct ev_loop *loop, struct ev_signal *watcher, int revents);
3421 #endif /* LWS_USE_LIBEV */
3425 /*! \defgroup uv libuv helpers
3429 * APIs specific to libuv event loop itegration
3432 #ifdef LWS_USE_LIBUV
3433 LWS_VISIBLE LWS_EXTERN int
3434 lws_uv_sigint_cfg(struct lws_context *context, int use_uv_sigint,
3437 LWS_VISIBLE LWS_EXTERN void
3438 lws_libuv_run(const struct lws_context *context, int tsi);
3440 LWS_VISIBLE LWS_EXTERN void
3441 lws_libuv_stop(struct lws_context *context);
3443 LWS_VISIBLE LWS_EXTERN void
3444 lws_libuv_stop_without_kill(const struct lws_context *context, int tsi);
3446 LWS_VISIBLE LWS_EXTERN int
3447 lws_uv_initloop(struct lws_context *context, uv_loop_t *loop, int tsi);
3449 LWS_VISIBLE LWS_EXTERN uv_loop_t *
3450 lws_uv_getloop(struct lws_context *context, int tsi);
3452 LWS_VISIBLE LWS_EXTERN void
3453 lws_uv_sigint_cb(uv_signal_t *watcher, int signum);
3454 #endif /* LWS_USE_LIBUV */
3457 /*! \defgroup event libevent helpers
3459 * ##libevent helpers
3461 * APIs specific to libevent event loop itegration
3465 #ifdef LWS_USE_LIBEVENT
3466 typedef void (lws_event_signal_cb_t) (evutil_socket_t sock_fd, short revents,
3469 LWS_VISIBLE LWS_EXTERN int
3470 lws_event_sigint_cfg(struct lws_context *context, int use_event_sigint,
3471 lws_event_signal_cb_t cb);
3473 LWS_VISIBLE LWS_EXTERN int
3474 lws_event_initloop(struct lws_context *context, struct event_base *loop,
3477 LWS_VISIBLE LWS_EXTERN void
3478 lws_event_sigint_cb(evutil_socket_t sock_fd, short revents,
3480 #endif /* LWS_USE_LIBEVENT */
3484 /*! \defgroup timeout Connection timeouts
3486 APIs related to setting connection timeouts
3491 * NOTE: These public enums are part of the abi. If you want to add one,
3492 * add it at where specified so existing users are unaffected.
3494 enum pending_timeout {
3495 NO_PENDING_TIMEOUT = 0,
3496 PENDING_TIMEOUT_AWAITING_PROXY_RESPONSE = 1,
3497 PENDING_TIMEOUT_AWAITING_CONNECT_RESPONSE = 2,
3498 PENDING_TIMEOUT_ESTABLISH_WITH_SERVER = 3,
3499 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE = 4,
3500 PENDING_TIMEOUT_AWAITING_PING = 5,
3501 PENDING_TIMEOUT_CLOSE_ACK = 6,
3502 PENDING_TIMEOUT_AWAITING_EXTENSION_CONNECT_RESPONSE = 7,
3503 PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE = 8,
3504 PENDING_TIMEOUT_SSL_ACCEPT = 9,
3505 PENDING_TIMEOUT_HTTP_CONTENT = 10,
3506 PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND = 11,
3507 PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE = 12,
3508 PENDING_TIMEOUT_SHUTDOWN_FLUSH = 13,
3509 PENDING_TIMEOUT_CGI = 14,
3510 PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE = 15,
3511 PENDING_TIMEOUT_WS_PONG_CHECK_SEND_PING = 16,
3512 PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG = 17,
3513 PENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD = 18,
3514 PENDING_TIMEOUT_AWAITING_SOCKS_GREETING_REPLY = 19,
3515 PENDING_TIMEOUT_AWAITING_SOCKS_CONNECT_REPLY = 20,
3516 PENDING_TIMEOUT_AWAITING_SOCKS_AUTH_REPLY = 21,
3518 /****** add new things just above ---^ ******/
3522 * lws_set_timeout() - marks the wsi as subject to a timeout
3524 * You will not need this unless you are doing something special
3526 * \param wsi: Websocket connection instance
3527 * \param reason: timeout reason
3528 * \param secs: how many seconds
3530 LWS_VISIBLE LWS_EXTERN void
3531 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs);
3534 /*! \defgroup sending-data Sending data
3536 APIs related to writing data on a connection
3539 #if !defined(LWS_SIZEOFPTR)
3540 #define LWS_SIZEOFPTR (sizeof (void *))
3542 #if !defined(u_int64_t)
3543 #define u_int64_t unsigned long long
3546 #if defined(__x86_64__)
3547 #define _LWS_PAD_SIZE 16 /* Intel recommended for best performance */
3549 #define _LWS_PAD_SIZE LWS_SIZEOFPTR /* Size of a pointer on the target arch */
3551 #define _LWS_PAD(n) (((n) % _LWS_PAD_SIZE) ? \
3552 ((n) + (_LWS_PAD_SIZE - ((n) % _LWS_PAD_SIZE))) : (n))
3553 #define LWS_PRE _LWS_PAD(4 + 10)
3554 /* used prior to 1.7 and retained for backward compatibility */
3555 #define LWS_SEND_BUFFER_PRE_PADDING LWS_PRE
3556 #define LWS_SEND_BUFFER_POST_PADDING 0
3559 * NOTE: These public enums are part of the abi. If you want to add one,
3560 * add it at where specified so existing users are unaffected.
3562 enum lws_write_protocol {
3564 /**< Send a ws TEXT message,the pointer must have LWS_PRE valid
3565 * memory behind it. The receiver expects only valid utf-8 in the
3567 LWS_WRITE_BINARY = 1,
3568 /**< Send a ws BINARY message, the pointer must have LWS_PRE valid
3569 * memory behind it. Any sequence of bytes is valid */
3570 LWS_WRITE_CONTINUATION = 2,
3571 /**< Continue a previous ws message, the pointer must have LWS_PRE valid
3572 * memory behind it */
3574 /**< Send HTTP content */
3576 /* LWS_WRITE_CLOSE is handled by lws_close_reason() */
3580 /* Same as write_http but we know this write ends the transaction */
3581 LWS_WRITE_HTTP_FINAL = 7,
3585 LWS_WRITE_HTTP_HEADERS = 8,
3586 /**< Send http headers (http2 encodes this payload and LWS_WRITE_HTTP
3587 * payload differently, http 1.x links also handle this correctly. so
3588 * to be compatible with both in the future,header response part should
3589 * be sent using this regardless of http version expected)
3592 /****** add new things just above ---^ ******/
3596 LWS_WRITE_NO_FIN = 0x40,
3597 /**< This part of the message is not the end of the message */
3599 LWS_WRITE_CLIENT_IGNORE_XOR_MASK = 0x80
3600 /**< client packet payload goes out on wire unmunged
3601 * only useful for security tests since normal servers cannot
3602 * decode the content if used */
3607 * lws_write() - Apply protocol then write data to client
3608 * \param wsi: Websocket instance (available from user callback)
3609 * \param buf: The data to send. For data being sent on a websocket
3610 * connection (ie, not default http), this buffer MUST have
3611 * LWS_PRE bytes valid BEFORE the pointer.
3612 * This is so the protocol header data can be added in-situ.
3613 * \param len: Count of the data bytes in the payload starting from buf
3614 * \param protocol: Use LWS_WRITE_HTTP to reply to an http connection, and one
3615 * of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
3616 * data on a websockets connection. Remember to allow the extra
3617 * bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
3620 * This function provides the way to issue data back to the client
3621 * for both http and websocket protocols.
3625 * When sending with websocket protocol
3629 * LWS_WRITE_CONTINUATION,
3633 * the send buffer has to have LWS_PRE bytes valid BEFORE
3634 * the buffer pointer you pass to lws_write().
3636 * This allows us to add protocol info before and after the data, and send as
3637 * one packet on the network without payload copying, for maximum efficiency.
3639 * So for example you need this kind of code to use lws_write with a
3642 * char buf[LWS_PRE + 128];
3644 * // fill your part of the buffer... for example here it's all zeros
3645 * memset(&buf[LWS_PRE], 0, 128);
3647 * lws_write(wsi, &buf[LWS_PRE], 128, LWS_WRITE_TEXT);
3649 * When sending HTTP, with
3652 * LWS_WRITE_HTTP_HEADERS
3653 * LWS_WRITE_HTTP_FINAL
3655 * there is no protocol data prepended, and don't need to take care about the
3656 * LWS_PRE bytes valid before the buffer pointer.
3658 * LWS_PRE is at least the frame nonce + 2 header + 8 length
3659 * LWS_SEND_BUFFER_POST_PADDING is deprecated, it's now 0 and can be left off.
3660 * The example apps no longer use it.
3662 * Pad LWS_PRE to the CPU word size, so that word references
3663 * to the address immediately after the padding won't cause an unaligned access
3664 * error. Sometimes for performance reasons the recommended padding is even
3665 * larger than sizeof(void *).
3667 * In the case of sending using websocket protocol, be sure to allocate
3668 * valid storage before and after buf as explained above. This scheme
3669 * allows maximum efficiency of sending data and protocol in a single
3670 * packet while not burdening the user code with any protocol knowledge.
3672 * Return may be -1 for a fatal error needing connection close, or the
3673 * number of bytes sent.
3678 * The OS may not accept everything you asked to write on the connection.
3680 * Posix defines POLLOUT indication from poll() to show that the connection
3681 * will accept more write data, but it doesn't specifiy how much. It may just
3682 * accept one byte of whatever you wanted to send.
3684 * LWS will buffer the remainder automatically, and send it out autonomously.
3686 * During that time, WRITABLE callbacks will be suppressed.
3688 * This is to handle corner cases where unexpectedly the OS refuses what we
3689 * usually expect it to accept. You should try to send in chunks that are
3690 * almost always accepted in order to avoid the inefficiency of the buffering.
3692 LWS_VISIBLE LWS_EXTERN int
3693 lws_write(struct lws *wsi, unsigned char *buf, size_t len,
3694 enum lws_write_protocol protocol);
3696 /* helper for case where buffer may be const */
3697 #define lws_write_http(wsi, buf, len) \
3698 lws_write(wsi, (unsigned char *)(buf), len, LWS_WRITE_HTTP)
3701 /** \defgroup callback-when-writeable Callback when writeable
3703 * ##Callback When Writeable
3705 * lws can only write data on a connection when it is able to accept more
3706 * data without blocking.
3708 * So a basic requirement is we should only use the lws_write() apis when the
3709 * connection we want to write on says that he can accept more data.
3711 * When lws cannot complete your send at the time, it will buffer the data
3712 * and send it in the background, suppressing any further WRITEABLE callbacks
3713 * on that connection until it completes. So it is important to write new
3714 * things in a new writeable callback.
3716 * These apis reflect the various ways we can indicate we would like to be
3717 * called back when one or more connections is writeable.
3722 * lws_callback_on_writable() - Request a callback when this socket
3723 * becomes able to be written to without
3726 * \param wsi: Websocket connection instance to get callback for
3728 * - Which: only this wsi
3729 * - When: when the individual connection becomes writeable
3730 * - What: LWS_CALLBACK_*_WRITEABLE
3732 LWS_VISIBLE LWS_EXTERN int
3733 lws_callback_on_writable(struct lws *wsi);
3736 * lws_callback_on_writable_all_protocol() - Request a callback for all
3737 * connections on same vhost using the given protocol when it
3738 * becomes possible to write to each socket without
3741 * \param context: lws_context
3742 * \param protocol: Protocol whose connections will get callbacks
3744 * - Which: connections using this protocol on ANY VHOST
3745 * - When: when the individual connection becomes writeable
3746 * - What: LWS_CALLBACK_*_WRITEABLE
3748 LWS_VISIBLE LWS_EXTERN int
3749 lws_callback_on_writable_all_protocol(const struct lws_context *context,
3750 const struct lws_protocols *protocol);
3753 * lws_callback_on_writable_all_protocol_vhost() - Request a callback for
3754 * all connections using the given protocol when it
3755 * becomes possible to write to each socket without
3758 * \param vhost: Only consider connections on this lws_vhost
3759 * \param protocol: Protocol whose connections will get callbacks
3761 * - Which: connections using this protocol on GIVEN VHOST ONLY
3762 * - When: when the individual connection becomes writeable
3763 * - What: LWS_CALLBACK_*_WRITEABLE
3765 LWS_VISIBLE LWS_EXTERN int
3766 lws_callback_on_writable_all_protocol_vhost(const struct lws_vhost *vhost,
3767 const struct lws_protocols *protocol);
3770 * lws_callback_all_protocol() - Callback all connections using
3771 * the given protocol with the given reason
3773 * \param context: lws_context
3774 * \param protocol: Protocol whose connections will get callbacks
3775 * \param reason: Callback reason index
3777 * - Which: connections using this protocol on ALL VHOSTS
3778 * - When: before returning
3781 * This isn't normally what you want... normally any update of connection-
3782 * specific information can wait until a network-related callback like rx,
3783 * writable, or close.
3785 LWS_VISIBLE LWS_EXTERN int
3786 lws_callback_all_protocol(struct lws_context *context,
3787 const struct lws_protocols *protocol, int reason);
3790 * lws_callback_all_protocol_vhost() - Callback all connections using
3791 * the given protocol with the given reason
3793 * \param vh: Vhost whose connections will get callbacks
3794 * \param protocol: Which protocol to match
3795 * \param reason: Callback reason index
3797 * - Which: connections using this protocol on GIVEN VHOST ONLY
3801 LWS_VISIBLE LWS_EXTERN int
3802 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
3803 const struct lws_protocols *protocol, int reason);
3806 * lws_callback_vhost_protocols() - Callback all protocols enabled on a vhost
3807 * with the given reason
3809 * \param wsi: wsi whose vhost will get callbacks
3810 * \param reason: Callback reason index
3811 * \param in: in argument to callback
3812 * \param len: len argument to callback
3814 * - Which: connections using this protocol on same VHOST as wsi ONLY
3818 LWS_VISIBLE LWS_EXTERN int
3819 lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len);
3821 LWS_VISIBLE LWS_EXTERN int
3822 lws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason,
3823 void *user, void *in, size_t len);
3826 * lws_get_socket_fd() - returns the socket file descriptor
3828 * You will not need this unless you are doing something special
3830 * \param wsi: Websocket connection instance
3832 LWS_VISIBLE LWS_EXTERN int
3833 lws_get_socket_fd(struct lws *wsi);
3836 * lws_get_peer_write_allowance() - get the amount of data writeable to peer
3839 * \param wsi: Websocket connection instance
3841 * if the protocol does not have any guidance, returns -1. Currently only
3842 * http2 connections get send window information from this API. But your code
3843 * should use it so it can work properly with any protocol.
3845 * If nonzero return is the amount of payload data the peer or intermediary has
3846 * reported it has buffer space for. That has NO relationship with the amount
3847 * of buffer space your OS can accept on this connection for a write action.
3849 * This number represents the maximum you could send to the peer or intermediary
3850 * on this connection right now without the protocol complaining.
3852 * lws manages accounting for send window updates and payload writes
3853 * automatically, so this number reflects the situation at the peer or
3854 * intermediary dynamically.
3856 LWS_VISIBLE LWS_EXTERN size_t
3857 lws_get_peer_write_allowance(struct lws *wsi);
3861 * lws_rx_flow_control() - Enable and disable socket servicing for
3864 * If the output side of a server process becomes choked, this allows flow
3865 * control for the input side.
3867 * \param wsi: Websocket connection instance to get callback for
3868 * \param enable: 0 = disable read servicing for this connection, 1 = enable
3870 LWS_VISIBLE LWS_EXTERN int
3871 lws_rx_flow_control(struct lws *wsi, int enable);
3874 * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
3876 * When the user server code realizes it can accept more input, it can
3877 * call this to have the RX flow restriction removed from all connections using
3878 * the given protocol.
3879 * \param context: lws_context
3880 * \param protocol: all connections using this protocol will be allowed to receive
3882 LWS_VISIBLE LWS_EXTERN void
3883 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
3884 const struct lws_protocols *protocol);
3887 * lws_remaining_packet_payload() - Bytes to come before "overall"
3888 * rx packet is complete
3889 * \param wsi: Websocket instance (available from user callback)
3891 * This function is intended to be called from the callback if the
3892 * user code is interested in "complete packets" from the client.
3893 * libwebsockets just passes through payload as it comes and issues a buffer
3894 * additionally when it hits a built-in limit. The LWS_CALLBACK_RECEIVE
3895 * callback handler can use this API to find out if the buffer it has just
3896 * been given is the last piece of a "complete packet" from the client --
3897 * when that is the case lws_remaining_packet_payload() will return
3900 * Many protocols won't care becuse their packets are always small.
3902 LWS_VISIBLE LWS_EXTERN size_t
3903 lws_remaining_packet_payload(struct lws *wsi);
3906 /** \defgroup sock-adopt Socket adoption helpers
3907 * ##Socket adoption helpers
3909 * When integrating with an external app with its own event loop, these can
3910 * be used to accept connections from someone else's listening socket.
3912 * When using lws own event loop, these are not needed.
3917 * lws_adopt_socket() - adopt foreign socket as if listen socket accepted it
3918 * for the default vhost of context.
3919 * \param context: lws context
3920 * \param accept_fd: fd of already-accepted socket to adopt
3922 * Either returns new wsi bound to accept_fd, or closes accept_fd and
3923 * returns NULL, having cleaned up any new wsi pieces.
3925 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
3926 * to ws or just serve http.
3928 LWS_VISIBLE LWS_EXTERN struct lws *
3929 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd);
3931 * lws_adopt_socket_vhost() - adopt foreign socket as if listen socket accepted it
3933 * \param vhost: lws vhost
3934 * \param accept_fd: fd of already-accepted socket to adopt
3936 * Either returns new wsi bound to accept_fd, or closes accept_fd and
3937 * returns NULL, having cleaned up any new wsi pieces.
3939 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
3940 * to ws or just serve http.
3942 LWS_VISIBLE LWS_EXTERN struct lws *
3943 lws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd);
3946 LWS_ADOPT_RAW_FILE_DESC = 0, /* convenience constant */
3947 LWS_ADOPT_HTTP = 1, /* flag: absent implies RAW */
3948 LWS_ADOPT_SOCKET = 2, /* flag: absent implies file descr */
3949 LWS_ADOPT_ALLOW_SSL = 4 /* flag: if set requires LWS_ADOPT_SOCKET */
3950 } lws_adoption_type;
3953 lws_sockfd_type sockfd;
3954 lws_filefd_type filefd;
3955 } lws_sock_file_fd_type;
3958 * lws_adopt_descriptor_vhost() - adopt foreign socket or file descriptor
3959 * if socket descriptor, should already have been accepted from listen socket
3961 * \param vhost: lws vhost
3962 * \param type: OR-ed combinations of lws_adoption_type flags
3963 * \param fd: union with either .sockfd or .filefd set
3964 * \param vh_prot_name: NULL or vh protocol name to bind raw connection to
3965 * \param parent: NULL or struct lws to attach new_wsi to as a child
3967 * Either returns new wsi bound to accept_fd, or closes accept_fd and
3968 * returns NULL, having cleaned up any new wsi pieces.
3970 * If LWS_ADOPT_SOCKET is set, LWS adopts the socket in http serving mode, it's
3971 * ready to accept an upgrade to ws or just serve http.
3973 * parent may be NULL, if given it should be an existing wsi that will become the
3974 * parent of the new wsi created by this call.
3976 LWS_VISIBLE struct lws *
3977 lws_adopt_descriptor_vhost(struct lws_vhost *vh, lws_adoption_type type,
3978 lws_sock_file_fd_type fd, const char *vh_prot_name,
3979 struct lws *parent);
3982 * lws_adopt_socket_readbuf() - adopt foreign socket and first rx as if listen socket accepted it
3983 * for the default vhost of context.
3984 * \param context: lws context
3985 * \param accept_fd: fd of already-accepted socket to adopt
3986 * \param readbuf: NULL or pointer to data that must be drained before reading from
3988 * \param len: The length of the data held at \param readbuf
3990 * Either returns new wsi bound to accept_fd, or closes accept_fd and
3991 * returns NULL, having cleaned up any new wsi pieces.
3993 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
3994 * to ws or just serve http.
3996 * If your external code did not already read from the socket, you can use
3997 * lws_adopt_socket() instead.
3999 * This api is guaranteed to use the data at \param readbuf first, before reading from
4002 * readbuf is limited to the size of the ah rx buf, currently 2048 bytes.
4004 LWS_VISIBLE LWS_EXTERN struct lws *
4005 lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
4006 const char *readbuf, size_t len);
4008 * lws_adopt_socket_vhost_readbuf() - adopt foreign socket and first rx as if listen socket
4009 * accepted it for vhost.
4010 * \param vhost: lws vhost
4011 * \param accept_fd: fd of already-accepted socket to adopt
4012 * \param readbuf: NULL or pointer to data that must be drained before reading from
4014 * \param len: The length of the data held at \param readbuf
4016 * Either returns new wsi bound to accept_fd, or closes accept_fd and
4017 * returns NULL, having cleaned up any new wsi pieces.
4019 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
4020 * to ws or just serve http.
4022 * If your external code did not already read from the socket, you can use
4023 * lws_adopt_socket() instead.
4025 * This api is guaranteed to use the data at \param readbuf first, before reading from
4028 * readbuf is limited to the size of the ah rx buf, currently 2048 bytes.
4030 LWS_VISIBLE LWS_EXTERN struct lws *
4031 lws_adopt_socket_vhost_readbuf(struct lws_vhost *vhost, lws_sockfd_type accept_fd,
4032 const char *readbuf, size_t len);
4035 /** \defgroup net Network related helper APIs
4036 * ##Network related helper APIs
4038 * These wrap miscellaneous useful network-related functions
4043 * lws_canonical_hostname() - returns this host's hostname
4045 * This is typically used by client code to fill in the host parameter
4046 * when making a client connection. You can only call it after the context
4049 * \param context: Websocket context
4051 LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
4052 lws_canonical_hostname(struct lws_context *context);
4055 * lws_get_peer_addresses() - Get client address information
4056 * \param wsi: Local struct lws associated with
4057 * \param fd: Connection socket descriptor
4058 * \param name: Buffer to take client address name
4059 * \param name_len: Length of client address name buffer
4060 * \param rip: Buffer to take client address IP dotted quad
4061 * \param rip_len: Length of client address IP buffer
4063 * This function fills in name and rip with the name and IP of
4064 * the client connected with socket descriptor fd. Names may be
4065 * truncated if there is not enough room. If either cannot be
4066 * determined, they will be returned as valid zero-length strings.
4068 LWS_VISIBLE LWS_EXTERN void
4069 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
4070 int name_len, char *rip, int rip_len);
4073 * lws_get_peer_simple() - Get client address information without RDNS
4075 * \param wsi: Local struct lws associated with
4076 * \param name: Buffer to take client address name
4077 * \param namelen: Length of client address name buffer
4079 * This provides a 123.123.123.123 type IP address in name from the
4080 * peer that has connected to wsi
4082 LWS_VISIBLE LWS_EXTERN const char *
4083 lws_get_peer_simple(struct lws *wsi, char *name, int namelen);
4084 #if !defined(LWS_WITH_ESP8266) && !defined(LWS_WITH_ESP32)
4086 * lws_interface_to_sa() - Convert interface name or IP to sockaddr struct
4088 * \param ipv6: Allow IPV6 addresses
4089 * \param ifname: Interface name or IP
4090 * \param addr: struct sockaddr_in * to be written
4091 * \param addrlen: Length of addr
4093 * This converts a textual network interface name to a sockaddr usable by
4094 * other network functions
4096 LWS_VISIBLE LWS_EXTERN int
4097 lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr,
4102 /** \defgroup misc Miscellaneous APIs
4103 * ##Miscellaneous APIs
4105 * Various APIs outside of other categories
4110 * lws_snprintf(): snprintf that truncates the returned length too
4112 * \param str: destination buffer
4113 * \param size: bytes left in destination buffer
4114 * \param format: format string
4115 * \param ...: args for format
4117 * This lets you correctly truncate buffers by concatenating lengths, if you
4118 * reach the limit the reported length doesn't exceed the limit.
4120 LWS_VISIBLE LWS_EXTERN int
4121 lws_snprintf(char *str, size_t size, const char *format, ...) LWS_FORMAT(3);
4124 * lws_get_random(): fill a buffer with platform random data
4126 * \param context: the lws context
4127 * \param buf: buffer to fill
4128 * \param len: how much to fill
4130 * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
4131 * it's interested to see if the frame it's dealing with was sent in binary
4134 LWS_VISIBLE LWS_EXTERN int
4135 lws_get_random(struct lws_context *context, void *buf, int len);
4137 * lws_daemonize(): make current process run in the background
4139 * \param _lock_path: the filepath to write the lock file
4141 * Spawn lws as a background process, taking care of various things
4143 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4144 lws_daemonize(const char *_lock_path);
4146 * lws_get_library_version(): return string describing the version of lws
4148 * On unix, also includes the git describe
4150 LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
4151 lws_get_library_version(void);
4154 * lws_wsi_user() - get the user data associated with the connection
4155 * \param wsi: lws connection
4157 * Not normally needed since it's passed into the callback
4159 LWS_VISIBLE LWS_EXTERN void *
4160 lws_wsi_user(struct lws *wsi);
4163 * lws_wsi_set_user() - set the user data associated with the client connection
4164 * \param wsi: lws connection
4165 * \param user: user data
4167 * By default lws allocates this and it's not legal to externally set it
4168 * yourself. However client connections may have it set externally when the
4169 * connection is created... if so, this api can be used to modify it at
4170 * runtime additionally.
4172 LWS_VISIBLE LWS_EXTERN void
4173 lws_set_wsi_user(struct lws *wsi, void *user);
4176 * lws_parse_uri: cut up prot:/ads:port/path into pieces
4177 * Notice it does so by dropping '\0' into input string
4178 * and the leading / on the path is consequently lost
4180 * \param p: incoming uri string.. will get written to
4181 * \param prot: result pointer for protocol part (https://)
4182 * \param ads: result pointer for address part
4183 * \param port: result pointer for port part
4184 * \param path: result pointer for path part
4186 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4187 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
4191 * lws_now_secs(): return seconds since 1970-1-1
4193 LWS_VISIBLE LWS_EXTERN unsigned long
4197 * lws_get_context - Allow geting lws_context from a Websocket connection
4200 * With this function, users can access context in the callback function.
4201 * Otherwise users may have to declare context as a global variable.
4203 * \param wsi: Websocket connection instance
4205 LWS_VISIBLE LWS_EXTERN struct lws_context * LWS_WARN_UNUSED_RESULT
4206 lws_get_context(const struct lws *wsi);
4209 * lws_get_count_threads(): how many service threads the context uses
4211 * \param context: the lws context
4213 * By default this is always 1, if you asked for more than lws can handle it
4214 * will clip the number of threads. So you can use this to find out how many
4215 * threads are actually in use.
4217 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4218 lws_get_count_threads(struct lws_context *context);
4221 * lws_get_parent() - get parent wsi or NULL
4222 * \param wsi: lws connection
4224 * Specialized wsi like cgi stdin/out/err are associated to a parent wsi,
4225 * this allows you to get their parent.
4227 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
4228 lws_get_parent(const struct lws *wsi);
4231 * lws_get_child() - get child wsi or NULL
4232 * \param wsi: lws connection
4234 * Allows you to find a related wsi from the parent wsi.
4236 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
4237 lws_get_child(const struct lws *wsi);
4241 * \deprecated DEPRECATED Note: this is not normally needed as a user api.
4242 * It's provided in case it is
4243 * useful when integrating with other app poll loop service code.
4245 LWS_VISIBLE LWS_EXTERN int
4246 lws_read(struct lws *wsi, unsigned char *buf, size_t len);
4249 * lws_set_allocator() - custom allocator support
4253 * Allows you to replace the allocator (and deallocator) used by lws
4255 LWS_VISIBLE LWS_EXTERN void
4256 lws_set_allocator(void *(*realloc)(void *ptr, size_t size));
4259 /** \defgroup wsstatus Websocket status APIs
4260 * ##Websocket connection status APIs
4262 * These provide information about ws connection or message status
4266 * lws_send_pipe_choked() - tests if socket is writable or not
4267 * \param wsi: lws connection
4269 * Allows you to check if you can write more on the socket
4271 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4272 lws_send_pipe_choked(struct lws *wsi);
4275 * lws_is_final_fragment() - tests if last part of ws message
4276 * \param wsi: lws connection
4278 LWS_VISIBLE LWS_EXTERN int
4279 lws_is_final_fragment(struct lws *wsi);
4282 * lws_get_reserved_bits() - access reserved bits of ws frame
4283 * \param wsi: lws connection
4285 LWS_VISIBLE LWS_EXTERN unsigned char
4286 lws_get_reserved_bits(struct lws *wsi);
4289 * lws_partial_buffered() - find out if lws buffered the last write
4290 * \param wsi: websocket connection to check
4292 * Returns 1 if you cannot use lws_write because the last
4293 * write on this connection is still buffered, and can't be cleared without
4294 * returning to the service loop and waiting for the connection to be
4297 * If you will try to do >1 lws_write call inside a single
4298 * WRITEABLE callback, you must check this after every write and bail if
4299 * set, ask for a new writeable callback and continue writing from there.
4301 * This is never set at the start of a writeable callback, but any write
4304 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4305 lws_partial_buffered(struct lws *wsi);
4308 * lws_frame_is_binary(): true if the current frame was sent in binary mode
4310 * \param wsi: the connection we are inquiring about
4312 * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
4313 * it's interested to see if the frame it's dealing with was sent in binary
4316 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4317 lws_frame_is_binary(struct lws *wsi);
4320 * lws_is_ssl() - Find out if connection is using SSL
4321 * \param wsi: websocket connection to check
4323 * Returns 0 if the connection is not using SSL, 1 if using SSL and
4324 * using verified cert, and 2 if using SSL but the cert was not
4325 * checked (appears for client wsi told to skip check on connection)
4327 LWS_VISIBLE LWS_EXTERN int
4328 lws_is_ssl(struct lws *wsi);
4330 * lws_is_cgi() - find out if this wsi is running a cgi process
4331 * \param wsi: lws connection
4333 LWS_VISIBLE LWS_EXTERN int
4334 lws_is_cgi(struct lws *wsi);
4336 #ifdef LWS_OPENSSL_SUPPORT
4338 * lws_get_ssl() - Return wsi's SSL context structure
4339 * \param wsi: websocket connection
4341 * Returns pointer to the SSL library's context structure
4343 LWS_VISIBLE LWS_EXTERN SSL*
4344 lws_get_ssl(struct lws *wsi);
4349 /** \defgroup sha SHA and B64 helpers
4350 * ##SHA and B64 helpers
4352 * These provide SHA-1 and B64 helper apis
4355 #ifdef LWS_SHA1_USE_OPENSSL_NAME
4356 #define lws_SHA1 SHA1
4359 * lws_SHA1(): make a SHA-1 digest of a buffer
4361 * \param d: incoming buffer
4362 * \param n: length of incoming buffer
4363 * \param md: buffer for message digest (must be >= 20 bytes)
4365 * Reduces any size buffer into a 20-byte SHA-1 hash.
4367 LWS_VISIBLE LWS_EXTERN unsigned char *
4368 lws_SHA1(const unsigned char *d, size_t n, unsigned char *md);
4371 * lws_b64_encode_string(): encode a string into base 64
4373 * \param in: incoming buffer
4374 * \param in_len: length of incoming buffer
4375 * \param out: result buffer
4376 * \param out_size: length of result buffer
4378 * Encodes a string using b64
4380 LWS_VISIBLE LWS_EXTERN int
4381 lws_b64_encode_string(const char *in, int in_len, char *out, int out_size);
4383 * lws_b64_decode_string(): decode a string from base 64
4385 * \param in: incoming buffer
4386 * \param out: result buffer
4387 * \param out_size: length of result buffer
4389 * Decodes a string using b64
4391 LWS_VISIBLE LWS_EXTERN int
4392 lws_b64_decode_string(const char *in, char *out, int out_size);
4396 /*! \defgroup cgi cgi handling
4400 * These functions allow low-level control over stdin/out/err of the cgi.
4402 * However for most cases, binding the cgi to http in and out, the default
4403 * lws implementation already does the right thing.
4406 enum lws_enum_stdinouterr {
4412 enum lws_cgi_hdr_state {
4424 struct lws_cgi_args {
4425 struct lws **stdwsi; /**< get fd with lws_get_socket_fd() */
4426 enum lws_enum_stdinouterr ch; /**< channel index */
4427 unsigned char *data; /**< for messages with payload */
4428 enum lws_cgi_hdr_state hdr_state; /**< track where we are in cgi headers */
4429 int len; /**< length */
4434 * lws_cgi: spawn network-connected cgi process
4436 * \param wsi: connection to own the process
4437 * \param exec_array: array of "exec-name" "arg1" ... "argn" NULL
4438 * \param script_uri_path_len: how many chars on the left of the uri are the path to the cgi
4439 * \param timeout_secs: seconds script should be allowed to run
4440 * \param mp_cgienv: pvo list with per-vhost cgi options to put in env
4442 LWS_VISIBLE LWS_EXTERN int
4443 lws_cgi(struct lws *wsi, const char * const *exec_array,
4444 int script_uri_path_len, int timeout_secs,
4445 const struct lws_protocol_vhost_options *mp_cgienv);
4448 * lws_cgi_write_split_stdout_headers: write cgi output accounting for header part
4450 * \param wsi: connection to own the process
4452 LWS_VISIBLE LWS_EXTERN int
4453 lws_cgi_write_split_stdout_headers(struct lws *wsi);
4456 * lws_cgi_kill: terminate cgi process associated with wsi
4458 * \param wsi: connection to own the process
4460 LWS_VISIBLE LWS_EXTERN int
4461 lws_cgi_kill(struct lws *wsi);
4466 /*! \defgroup fops file operation wrapping
4468 * ##File operation wrapping
4470 * Use these helper functions if you want to access a file from the perspective
4471 * of a specific wsi, which is usually the case. If you just want contextless
4472 * file access, use the fops callbacks directly with NULL wsi instead of these
4475 * If so, then it calls the platform handler or user overrides where present
4476 * (as defined in info->fops)
4478 * The advantage from all this is user code can be portable for file operations
4479 * without having to deal with differences between platforms.
4483 /** struct lws_plat_file_ops - Platform-specific file operations
4485 * These provide platform-agnostic ways to deal with filesystem access in the
4486 * library and in the user code.
4489 #if defined(LWS_WITH_ESP32)
4490 /* sdk preprocessor defs? compiler issue? gets confused with member names */
4491 #define LWS_FOP_OPEN _open
4492 #define LWS_FOP_CLOSE _close
4493 #define LWS_FOP_SEEK_CUR _seek_cur
4494 #define LWS_FOP_READ _read
4495 #define LWS_FOP_WRITE _write
4497 #define LWS_FOP_OPEN open
4498 #define LWS_FOP_CLOSE close
4499 #define LWS_FOP_SEEK_CUR seek_cur
4500 #define LWS_FOP_READ read
4501 #define LWS_FOP_WRITE write
4504 #define LWS_FOP_FLAGS_MASK ((1 << 23) - 1)
4505 #define LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP (1 << 24)
4506 #define LWS_FOP_FLAG_COMPR_IS_GZIP (1 << 25)
4507 #define LWS_FOP_FLAG_MOD_TIME_VALID (1 << 26)
4508 #define LWS_FOP_FLAG_VIRTUAL (1 << 27)
4510 struct lws_plat_file_ops;
4512 #if (defined(WIN32) || defined(_WIN32)) && !defined(__MINGW32__)
4514 #if !defined(ssize_t)
4515 typedef SSIZE_T ssize_t;
4519 #if defined(LWS_HAVE_STDINT_H)
4522 #if defined(WIN32) || defined(_WIN32)
4524 typedef unsigned __int32 uint32_t;
4525 typedef unsigned __int16 uint16_t;
4526 typedef unsigned __int8 uint8_t;
4528 typedef unsigned int uint32_t;
4529 typedef unsigned short uint16_t;
4530 typedef unsigned char uint8_t;
4534 typedef size_t lws_filepos_t;
4535 typedef ssize_t lws_fileofs_t;
4536 typedef uint32_t lws_fop_flags_t;
4540 /**< real file descriptor related to the file... */
4541 const struct lws_plat_file_ops *fops;
4542 /**< fops that apply to this fop_fd */
4543 void *filesystem_priv;
4544 /**< ignored by lws; owned by the fops handlers */
4546 /**< generic "position in file" */
4548 /**< generic "length of file" */
4549 lws_fop_flags_t flags;
4550 /**< copy of the returned flags */
4552 /**< optional "modification time of file", only valid if .open()
4553 * set the LWS_FOP_FLAG_MOD_TIME_VALID flag */
4555 typedef struct lws_fop_fd *lws_fop_fd_t;
4557 struct lws_fops_index {
4558 const char *sig; /* NULL or vfs signature, eg, ".zip/" */
4559 uint8_t len; /* length of above string */
4562 struct lws_plat_file_ops {
4563 lws_fop_fd_t (*LWS_FOP_OPEN)(const struct lws_plat_file_ops *fops,
4564 const char *filename, const char *vpath,
4565 lws_fop_flags_t *flags);
4566 /**< Open file (always binary access if plat supports it)
4567 * vpath may be NULL, or if the fops understands it, the point at which
4568 * the filename's virtual part starts.
4569 * *flags & LWS_FOP_FLAGS_MASK should be set to O_RDONLY or O_RDWR.
4570 * If the file may be gzip-compressed,
4571 * LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP is set. If it actually is
4572 * gzip-compressed, then the open handler should OR
4573 * LWS_FOP_FLAG_COMPR_IS_GZIP on to *flags before returning.
4575 int (*LWS_FOP_CLOSE)(lws_fop_fd_t *fop_fd);
4576 /**< close file AND set the pointer to NULL */
4577 lws_fileofs_t (*LWS_FOP_SEEK_CUR)(lws_fop_fd_t fop_fd,
4578 lws_fileofs_t offset_from_cur_pos);
4579 /**< seek from current position */
4580 int (*LWS_FOP_READ)(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4581 uint8_t *buf, lws_filepos_t len);
4582 /**< Read from file, on exit *amount is set to amount actually read */
4583 int (*LWS_FOP_WRITE)(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4584 uint8_t *buf, lws_filepos_t len);
4585 /**< Write to file, on exit *amount is set to amount actually written */
4587 struct lws_fops_index fi[3];
4588 /**< vfs path signatures implying use of this fops */
4590 const struct lws_plat_file_ops *next;
4591 /**< NULL or next fops in list */
4593 /* Add new things just above here ---^
4594 * This is part of the ABI, don't needlessly break compatibility */
4598 * lws_get_fops() - get current file ops
4600 * \param context: context
4602 LWS_VISIBLE LWS_EXTERN struct lws_plat_file_ops * LWS_WARN_UNUSED_RESULT
4603 lws_get_fops(struct lws_context *context);
4604 LWS_VISIBLE LWS_EXTERN void
4605 lws_set_fops(struct lws_context *context, const struct lws_plat_file_ops *fops);
4607 * lws_vfs_tell() - get current file position
4609 * \param fop_fd: fop_fd we are asking about
4611 LWS_VISIBLE LWS_EXTERN lws_filepos_t LWS_WARN_UNUSED_RESULT
4612 lws_vfs_tell(lws_fop_fd_t fop_fd);
4614 * lws_vfs_get_length() - get current file total length in bytes
4616 * \param fop_fd: fop_fd we are asking about
4618 LWS_VISIBLE LWS_EXTERN lws_filepos_t LWS_WARN_UNUSED_RESULT
4619 lws_vfs_get_length(lws_fop_fd_t fop_fd);
4621 * lws_vfs_get_mod_time() - get time file last modified
4623 * \param fop_fd: fop_fd we are asking about
4625 LWS_VISIBLE LWS_EXTERN uint32_t LWS_WARN_UNUSED_RESULT
4626 lws_vfs_get_mod_time(lws_fop_fd_t fop_fd);
4628 * lws_vfs_file_seek_set() - seek relative to start of file
4630 * \param fop_fd: fop_fd we are seeking in
4631 * \param offset: offset from start of file
4633 LWS_VISIBLE LWS_EXTERN lws_fileofs_t
4634 lws_vfs_file_seek_set(lws_fop_fd_t fop_fd, lws_fileofs_t offset);
4636 * lws_vfs_file_seek_end() - seek relative to end of file
4638 * \param fop_fd: fop_fd we are seeking in
4639 * \param offset: offset from start of file
4641 LWS_VISIBLE LWS_EXTERN lws_fileofs_t
4642 lws_vfs_file_seek_end(lws_fop_fd_t fop_fd, lws_fileofs_t offset);
4644 extern struct lws_plat_file_ops fops_zip;
4647 * lws_plat_file_open() - open vfs filepath
4649 * \param fops: file ops struct that applies to this descriptor
4650 * \param vfs_path: filename to open
4651 * \param flags: pointer to open flags
4653 * The vfs_path is scanned for known fops signatures, and the open directed
4654 * to any matching fops open.
4656 * User code should use this api to perform vfs opens.
4658 * returns semi-opaque handle
4660 LWS_VISIBLE LWS_EXTERN lws_fop_fd_t LWS_WARN_UNUSED_RESULT
4661 lws_vfs_file_open(const struct lws_plat_file_ops *fops, const char *vfs_path,
4662 lws_fop_flags_t *flags);
4665 * lws_plat_file_close() - close file
4667 * \param fop_fd: file handle to close
4669 static LWS_INLINE int
4670 lws_vfs_file_close(lws_fop_fd_t *fop_fd)
4672 return (*fop_fd)->fops->LWS_FOP_CLOSE(fop_fd);
4676 * lws_plat_file_seek_cur() - close file
4679 * \param fop_fd: file handle
4680 * \param offset: position to seek to
4682 static LWS_INLINE lws_fileofs_t
4683 lws_vfs_file_seek_cur(lws_fop_fd_t fop_fd, lws_fileofs_t offset)
4685 return fop_fd->fops->LWS_FOP_SEEK_CUR(fop_fd, offset);
4688 * lws_plat_file_read() - read from file
4690 * \param fop_fd: file handle
4691 * \param amount: how much to read (rewritten by call)
4692 * \param buf: buffer to write to
4693 * \param len: max length
4695 static LWS_INLINE int LWS_WARN_UNUSED_RESULT
4696 lws_vfs_file_read(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4697 uint8_t *buf, lws_filepos_t len)
4699 return fop_fd->fops->LWS_FOP_READ(fop_fd, amount, buf, len);
4702 * lws_plat_file_write() - write from file
4704 * \param fop_fd: file handle
4705 * \param amount: how much to write (rewritten by call)
4706 * \param buf: buffer to read from
4707 * \param len: max length
4709 static LWS_INLINE int LWS_WARN_UNUSED_RESULT
4710 lws_vfs_file_write(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4711 uint8_t *buf, lws_filepos_t len)
4713 return fop_fd->fops->LWS_FOP_WRITE(fop_fd, amount, buf, len);
4716 /* these are the platform file operations implementations... they can
4717 * be called directly and used in fops arrays
4720 LWS_VISIBLE LWS_EXTERN lws_fop_fd_t
4721 _lws_plat_file_open(const struct lws_plat_file_ops *fops, const char *filename,
4722 const char *vpath, lws_fop_flags_t *flags);
4723 LWS_VISIBLE LWS_EXTERN int
4724 _lws_plat_file_close(lws_fop_fd_t *fop_fd);
4725 LWS_VISIBLE LWS_EXTERN lws_fileofs_t
4726 _lws_plat_file_seek_cur(lws_fop_fd_t fop_fd, lws_fileofs_t offset);
4727 LWS_VISIBLE LWS_EXTERN int
4728 _lws_plat_file_read(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4729 uint8_t *buf, lws_filepos_t len);
4730 LWS_VISIBLE LWS_EXTERN int
4731 _lws_plat_file_write(lws_fop_fd_t fop_fd, lws_filepos_t *amount,
4732 uint8_t *buf, lws_filepos_t len);
4734 LWS_VISIBLE LWS_EXTERN int
4735 lws_alloc_vfs_file(struct lws_context *context, const char *filename, uint8_t **buf,
4736 lws_filepos_t *amount);
4741 * ##SMTP related functions
4743 * These apis let you communicate with a local SMTP server to send email from
4744 * lws. It handles all the SMTP sequencing and protocol actions.
4746 * Your system should have postfix, sendmail or another MTA listening on port
4747 * 25 and able to send email using the "mail" commandline app. Usually distro
4748 * MTAs are configured for this by default.
4750 * It runs via its own libuv events if initialized (which requires giving it
4751 * a libuv loop to attach to).
4753 * It operates using three callbacks, on_next() queries if there is a new email
4754 * to send, on_get_body() asks for the body of the email, and on_sent() is
4755 * called after the email is successfully sent.
4759 * - create an lws_email struct
4761 * - initialize data, loop, the email_* strings, max_content_size and
4764 * - call lws_email_init()
4766 * When you have at least one email to send, call lws_email_check() to
4767 * schedule starting to send it.
4770 #ifdef LWS_WITH_SMTP
4772 /** enum lwsgs_smtp_states - where we are in SMTP protocol sequence */
4773 enum lwsgs_smtp_states {
4774 LGSSMTP_IDLE, /**< awaiting new email */
4775 LGSSMTP_CONNECTING, /**< opening tcp connection to MTA */
4776 LGSSMTP_CONNECTED, /**< tcp connection to MTA is connected */
4777 LGSSMTP_SENT_HELO, /**< sent the HELO */
4778 LGSSMTP_SENT_FROM, /**< sent FROM */
4779 LGSSMTP_SENT_TO, /**< sent TO */
4780 LGSSMTP_SENT_DATA, /**< sent DATA request */
4781 LGSSMTP_SENT_BODY, /**< sent the email body */
4782 LGSSMTP_SENT_QUIT, /**< sent the session quit */
4785 /** struct lws_email - abstract context for performing SMTP operations */
4788 /**< opaque pointer set by user code and available to the callbacks */
4790 /**< the libuv loop we will work on */
4792 char email_smtp_ip[32]; /**< Fill before init, eg, "127.0.0.1" */
4793 char email_helo[32]; /**< Fill before init, eg, "myserver.com" */
4794 char email_from[100]; /**< Fill before init or on_next */
4795 char email_to[100]; /**< Fill before init or on_next */
4797 unsigned int max_content_size;
4798 /**< largest possible email body size */
4800 /* Fill all the callbacks before init */
4802 int (*on_next)(struct lws_email *email);
4803 /**< (Fill in before calling lws_email_init)
4804 * called when idle, 0 = another email to send, nonzero is idle.
4805 * If you return 0, all of the email_* char arrays must be set
4806 * to something useful. */
4807 int (*on_sent)(struct lws_email *email);
4808 /**< (Fill in before calling lws_email_init)
4809 * called when transfer of the email to the SMTP server was
4810 * successful, your callback would remove the current email
4812 int (*on_get_body)(struct lws_email *email, char *buf, int len);
4813 /**< (Fill in before calling lws_email_init)
4814 * called when the body part of the queued email is about to be
4815 * sent to the SMTP server. */
4818 /* private things */
4819 uv_timer_t timeout_email; /**< private */
4820 enum lwsgs_smtp_states estate; /**< private */
4821 uv_connect_t email_connect_req; /**< private */
4822 uv_tcp_t email_client; /**< private */
4823 time_t email_connect_started; /**< private */
4824 char email_buf[256]; /**< private */
4825 char *content; /**< private */
4829 * lws_email_init() - Initialize a struct lws_email
4831 * \param email: struct lws_email to init
4832 * \param loop: libuv loop to use
4833 * \param max_content: max email content size
4835 * Prepares a struct lws_email for use ending SMTP
4837 LWS_VISIBLE LWS_EXTERN int
4838 lws_email_init(struct lws_email *email, uv_loop_t *loop, int max_content);
4841 * lws_email_check() - Request check for new email
4843 * \param email: struct lws_email context to check
4845 * Schedules a check for new emails in 1s... call this when you have queued an
4848 LWS_VISIBLE LWS_EXTERN void
4849 lws_email_check(struct lws_email *email);
4851 * lws_email_destroy() - stop using the struct lws_email
4853 * \param email: the struct lws_email context
4855 * Stop sending email using email and free allocations
4857 LWS_VISIBLE LWS_EXTERN void
4858 lws_email_destroy(struct lws_email *email);
4864 * Stats are all uint64_t numbers that start at 0.
4865 * Index names here have the convention
4869 * _MS_ millisecond count
4873 LWSSTATS_C_CONNECTIONS, /**< count incoming connections */
4874 LWSSTATS_C_API_CLOSE, /**< count calls to close api */
4875 LWSSTATS_C_API_READ, /**< count calls to read from socket api */
4876 LWSSTATS_C_API_LWS_WRITE, /**< count calls to lws_write API */
4877 LWSSTATS_C_API_WRITE, /**< count calls to write API */
4878 LWSSTATS_C_WRITE_PARTIALS, /**< count of partial writes */
4879 LWSSTATS_C_WRITEABLE_CB_REQ, /**< count of writable callback requests */
4880 LWSSTATS_C_WRITEABLE_CB_EFF_REQ, /**< count of effective writable callback requests */
4881 LWSSTATS_C_WRITEABLE_CB, /**< count of writable callbacks */
4882 LWSSTATS_C_SSL_CONNECTIONS_FAILED, /**< count of failed SSL connections */
4883 LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED, /**< count of accepted SSL connections */
4884 LWSSTATS_C_SSL_CONNS_HAD_RX, /**< count of accepted SSL conns that have had some RX */
4885 LWSSTATS_C_TIMEOUTS, /**< count of timed-out connections */
4886 LWSSTATS_C_SERVICE_ENTRY, /**< count of entries to lws service loop */
4887 LWSSTATS_B_READ, /**< aggregate bytes read */
4888 LWSSTATS_B_WRITE, /**< aggregate bytes written */
4889 LWSSTATS_B_PARTIALS_ACCEPTED_PARTS, /**< aggreate of size of accepted write data from new partials */
4890 LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY, /**< aggregate delay in accepting connection */
4891 LWSSTATS_MS_WRITABLE_DELAY, /**< aggregate delay between asking for writable and getting cb */
4892 LWSSTATS_MS_WORST_WRITABLE_DELAY, /**< single worst delay between asking for writable and getting cb */
4893 LWSSTATS_MS_SSL_RX_DELAY, /**< aggregate delay between ssl accept complete and first RX */
4895 /* Add new things just above here ---^
4896 * This is part of the ABI, don't needlessly break compatibility */
4900 #if defined(LWS_WITH_STATS)
4902 LWS_VISIBLE LWS_EXTERN uint64_t
4903 lws_stats_get(struct lws_context *context, int index);
4904 LWS_VISIBLE LWS_EXTERN void
4905 lws_stats_log_dump(struct lws_context *context);
4907 static LWS_INLINE uint64_t
4908 lws_stats_get(struct lws_context *context, int index) { return 0; }
4909 static LWS_INLINE void
4910 lws_stats_log_dump(struct lws_context *context) { }