file_ops: use wrappers for names
[platform/upstream/libwebsockets.git] / lib / libwebsockets.h
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2016 Andy Green <andy@warmcat.com>
5  *
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.
10  *
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.
15  *
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,
19  *  MA  02110-1301  USA
20  */
21
22 /** @file */
23
24 #ifndef LIBWEBSOCKET_H_3060898B846849FF9F88F5DB59B5950C
25 #define LIBWEBSOCKET_H_3060898B846849FF9F88F5DB59B5950C
26
27 #ifdef __cplusplus
28 #include <cstddef>
29 #include <cstdarg>
30 #ifdef MBED_OPERATORS
31 #include "mbed-drivers/mbed.h"
32 #include "sal-iface-eth/EthernetInterface.h"
33 #include "sockets/TCPListener.h"
34 #include "sal-stack-lwip/lwipv4_init.h"
35
36 namespace {
37 }
38 using namespace mbed::Sockets::v0;
39
40
41 struct sockaddr_in;
42 struct lws;
43
44 class lws_conn {
45         public:
46         lws_conn():
47                 ts(NULL),
48                 wsi(NULL),
49                 writeable(1),
50                 awaiting_on_writeable(0)
51         {
52         }
53
54 public:
55         void set_wsi(struct lws *_wsi) { wsi = _wsi; }
56         int actual_onRX(Socket *s);
57         void onRX(Socket *s);
58         void onError(Socket *s, socket_error_t err);
59         void onDisconnect(TCPStream *s);
60         void onSent(Socket *s, uint16_t len);
61         void serialized_writeable(struct lws *wsi);
62
63 public:
64         TCPStream *ts;
65
66 public:
67         struct lws *wsi;
68         char writeable;
69         char awaiting_on_writeable;
70 };
71
72 class lws_conn_listener : lws_conn {
73 public:
74         lws_conn_listener():
75                 srv(SOCKET_STACK_LWIP_IPV4)
76         {
77                 srv.setOnError(TCPStream::ErrorHandler_t(this,
78                                 &lws_conn_listener::onError));
79         }
80
81         void start(const uint16_t port); /**< start listening */
82
83 protected:
84         void onRX(Socket *s); /**< incoming data ready */
85         void onError(Socket *s, socket_error_t err); /**< if error occurs */
86         void onIncoming(TCPListener *s, void *impl); /**< new connection */
87         void onDisconnect(TCPStream *s); /**< disconnection */
88
89 public:
90         TCPListener srv;
91 };
92
93 #endif
94
95 extern "C" {
96 #else
97 #include <stdarg.h>
98 #endif
99
100 #if defined(MBED_OPERATORS) || defined(LWS_WITH_ESP8266)
101 struct sockaddr_in;
102 #define LWS_POSIX 0
103 #else
104 #define LWS_POSIX 1
105 #endif
106
107 #include "lws_config.h"
108
109 #if defined(WIN32) || defined(_WIN32)
110 #ifndef WIN32_LEAN_AND_MEAN
111 #define WIN32_LEAN_AND_MEAN
112 #endif
113
114 #include <winsock2.h>
115 #include <ws2tcpip.h>
116 #include <stddef.h>
117 #include <basetsd.h>
118 #ifndef _WIN32_WCE
119 #include <fcntl.h>
120 #else
121 #define _O_RDONLY       0x0000
122 #define O_RDONLY        _O_RDONLY
123 #endif
124
125 // Visual studio older than 2015 and WIN_CE has only _stricmp
126 #if (defined(_MSC_VER) && _MSC_VER < 1900) || defined(_WIN32_WCE)
127 #define strcasecmp _stricmp
128 #elif !defined(__MINGW32__)
129 #define strcasecmp stricmp
130 #endif
131 #define getdtablesize() 30000
132
133 #define LWS_INLINE __inline
134 #define LWS_VISIBLE
135 #define LWS_WARN_UNUSED_RESULT
136 #define LWS_WARN_DEPRECATED
137 #define LWS_FORMAT(string_index)
138
139 #ifdef LWS_DLL
140 #ifdef LWS_INTERNAL
141 #define LWS_EXTERN extern __declspec(dllexport)
142 #else
143 #define LWS_EXTERN extern __declspec(dllimport)
144 #endif
145 #else
146 #define LWS_EXTERN
147 #endif
148
149 #define LWS_INVALID_FILE INVALID_HANDLE_VALUE
150 #define LWS_O_RDONLY _O_RDONLY
151
152 #if !defined(__MINGW32__) && (!defined(_MSC_VER) || _MSC_VER < 1900) /* Visual Studio 2015 already defines this in <stdio.h> */
153 #define lws_snprintf _snprintf
154 #endif
155
156 #ifndef __func__
157 #define __func__ __FUNCTION__
158 #endif
159
160 #else /* NOT WIN32 */
161 #include <unistd.h>
162
163 #if defined(__NetBSD__) || defined(__FreeBSD__)
164 #include <netinet/in.h>
165 #endif
166
167 #define LWS_INLINE inline
168 #define LWS_O_RDONLY O_RDONLY
169
170 #if !defined(MBED_OPERATORS) && !defined(LWS_WITH_ESP8266) && !defined(OPTEE_TA)
171 #include <poll.h>
172 #include <netdb.h>
173 #define LWS_INVALID_FILE -1
174 #else
175 #define getdtablesize() (20)
176 #define LWS_INVALID_FILE NULL
177 #endif
178
179 #if defined(__GNUC__)
180
181 /* warn_unused_result attribute only supported by GCC 3.4 or later */
182 #if __GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
183 #define LWS_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
184 #else
185 #define LWS_WARN_UNUSED_RESULT
186 #endif
187
188 #define LWS_VISIBLE __attribute__((visibility("default")))
189 #define LWS_WARN_DEPRECATED __attribute__ ((deprecated))
190 #define LWS_FORMAT(string_index) __attribute__ ((format(printf, string_index, string_index+1)))
191 #else
192 #define LWS_VISIBLE
193 #define LWS_WARN_UNUSED_RESULT
194 #define LWS_WARN_DEPRECATED
195 #define LWS_FORMAT(string_index)
196 #endif
197
198 #if defined(__ANDROID__)
199 #include <unistd.h>
200 #define getdtablesize() sysconf(_SC_OPEN_MAX)
201 #endif
202
203 #endif
204
205 #ifdef LWS_USE_LIBEV
206 #include <ev.h>
207 #endif /* LWS_USE_LIBEV */
208 #ifdef LWS_USE_LIBUV
209 #include <uv.h>
210 #ifdef LWS_HAVE_UV_VERSION_H
211 #include <uv-version.h>
212 #endif
213 #endif /* LWS_USE_LIBUV */
214
215 #ifndef LWS_EXTERN
216 #define LWS_EXTERN extern
217 #endif
218
219 #ifdef _WIN32
220 #define random rand
221 #else
222 #if !defined(OPTEE_TA)
223 #include <sys/time.h>
224 #include <unistd.h>
225 #endif
226 #endif
227
228 #ifdef LWS_OPENSSL_SUPPORT
229
230 #ifdef USE_WOLFSSL
231 #ifdef USE_OLD_CYASSL
232 #include <cyassl/openssl/ssl.h>
233 #include <cyassl/error-ssl.h>
234 #else
235 #include <wolfssl/openssl/ssl.h>
236 #include <wolfssl/error-ssl.h>
237 #endif /* not USE_OLD_CYASSL */
238 #else
239 #if defined(LWS_USE_POLARSSL)
240 #include <polarssl/ssl.h>
241 struct lws_polarssl_context {
242         x509_crt ca; /**< ca */
243         x509_crt certificate; /**< cert */
244         rsa_context key; /**< key */
245 };
246 typedef struct lws_polarssl_context SSL_CTX;
247 typedef ssl_context SSL;
248 #else
249 #if defined(LWS_USE_MBEDTLS)
250 #include <mbedtls/ssl.h>
251 #else
252 #include <openssl/ssl.h>
253 #include <openssl/err.h>
254 #endif /* not USE_MBEDTLS */
255 #endif /* not USE_POLARSSL */
256 #endif /* not USE_WOLFSSL */
257 #endif
258
259
260 #define CONTEXT_PORT_NO_LISTEN -1
261 #define CONTEXT_PORT_NO_LISTEN_SERVER -2
262
263 /** \defgroup log Logging
264  *
265  * ##Logging
266  *
267  * Lws provides flexible and filterable logging facilities, which can be
268  * used inside lws and in user code.
269  *
270  * Log categories may be individually filtered bitwise, and directed to built-in
271  * sinks for syslog-compatible logging, or a user-defined function.
272  */
273 ///@{
274
275 enum lws_log_levels {
276         LLL_ERR = 1 << 0,
277         LLL_WARN = 1 << 1,
278         LLL_NOTICE = 1 << 2,
279         LLL_INFO = 1 << 3,
280         LLL_DEBUG = 1 << 4,
281         LLL_PARSER = 1 << 5,
282         LLL_HEADER = 1 << 6,
283         LLL_EXT = 1 << 7,
284         LLL_CLIENT = 1 << 8,
285         LLL_LATENCY = 1 << 9,
286         LLL_USER = 1 << 10,
287
288         LLL_COUNT = 11 /* set to count of valid flags */
289 };
290
291 LWS_VISIBLE LWS_EXTERN void _lws_log(int filter, const char *format, ...) LWS_FORMAT(2);
292 LWS_VISIBLE LWS_EXTERN void _lws_logv(int filter, const char *format, va_list vl);
293 /**
294  * lwsl_timestamp: generate logging timestamp string
295  *
296  * \param level:        logging level
297  * \param p:            char * buffer to take timestamp
298  * \param len:  length of p
299  *
300  * returns length written in p
301  */
302 LWS_VISIBLE LWS_EXTERN int
303 lwsl_timestamp(int level, char *p, int len);
304
305 /* these guys are unconditionally included */
306
307 #define lwsl_err(...) _lws_log(LLL_ERR, __VA_ARGS__)
308 #define lwsl_user(...) _lws_log(LLL_USER, __VA_ARGS__)
309
310 #if !defined(LWS_WITH_NO_LOGS)
311 /* notice and warn are usually included by being compiled in */
312 #define lwsl_warn(...) _lws_log(LLL_WARN, __VA_ARGS__)
313 #define lwsl_notice(...) _lws_log(LLL_NOTICE, __VA_ARGS__)
314 #endif
315 /*
316  *  weaker logging can be deselected by telling CMake to build in RELEASE mode
317  *  that gets rid of the overhead of checking while keeping _warn and _err
318  *  active
319  */
320
321 #if defined(LWS_WITH_ESP8266)
322 #undef _DEBUG
323 #endif
324
325 #ifdef _DEBUG
326 #if defined(LWS_WITH_NO_LOGS)
327 /* notice, warn and log are always compiled in */
328 #define lwsl_warn(...) _lws_log(LLL_WARN, __VA_ARGS__)
329 #define lwsl_notice(...) _lws_log(LLL_NOTICE, __VA_ARGS__)
330 #endif
331 #define lwsl_info(...) _lws_log(LLL_INFO, __VA_ARGS__)
332 #define lwsl_debug(...) _lws_log(LLL_DEBUG, __VA_ARGS__)
333 #define lwsl_parser(...) _lws_log(LLL_PARSER, __VA_ARGS__)
334 #define lwsl_header(...)  _lws_log(LLL_HEADER, __VA_ARGS__)
335 #define lwsl_ext(...)  _lws_log(LLL_EXT, __VA_ARGS__)
336 #define lwsl_client(...) _lws_log(LLL_CLIENT, __VA_ARGS__)
337 #define lwsl_latency(...) _lws_log(LLL_LATENCY, __VA_ARGS__)
338 /**
339  * lwsl_hexdump() - helper to hexdump a buffer (DEBUG builds only)
340  *
341  * \param buf: buffer start to dump
342  * \param len: length of buffer to dump
343  */
344 LWS_VISIBLE LWS_EXTERN void lwsl_hexdump(void *buf, size_t len);
345
346 #else /* no debug */
347 #if defined(LWS_WITH_NO_LOGS)
348 #define lwsl_warn(...) do {} while(0)
349 #define lwsl_notice(...) do {} while(0)
350 #endif
351 #define lwsl_info(...) do {} while(0)
352 #define lwsl_debug(...) do {} while(0)
353 #define lwsl_parser(...) do {} while(0)
354 #define lwsl_header(...) do {} while(0)
355 #define lwsl_ext(...) do {} while(0)
356 #define lwsl_client(...) do {} while(0)
357 #define lwsl_latency(...) do {} while(0)
358 #define lwsl_hexdump(a, b)
359
360 #endif
361
362 /**
363  * lws_set_log_level() - Set the logging bitfield
364  * \param level:        OR together the LLL_ debug contexts you want output from
365  * \param log_emit_function:    NULL to leave it as it is, or a user-supplied
366  *                      function to perform log string emission instead of
367  *                      the default stderr one.
368  *
369  *      log level defaults to "err", "warn" and "notice" contexts enabled and
370  *      emission on stderr.
371  */
372 LWS_VISIBLE LWS_EXTERN void
373 lws_set_log_level(int level,
374                   void (*log_emit_function)(int level, const char *line));
375
376 /**
377  * lwsl_emit_syslog() - helper log emit function writes to system log
378  *
379  * \param level: one of LLL_ log level indexes
380  * \param line: log string
381  *
382  * You use this by passing the function pointer to lws_set_log_level(), to set
383  * it as the log emit function, it is not called directly.
384  */
385 LWS_VISIBLE LWS_EXTERN void
386 lwsl_emit_syslog(int level, const char *line);
387
388 /**
389  * lwsl_visible() - returns true if the log level should be printed
390  *
391  * \param level: one of LLL_ log level indexes
392  *
393  * This is useful if you have to do work to generate the log content, you
394  * can skip the work if the log level used to print it is not actually
395  * enabled at runtime.
396  */
397 LWS_VISIBLE LWS_EXTERN int
398 lwsl_visible(int level);
399
400 ///@}
401
402
403 #include <stddef.h>
404
405 #ifndef lws_container_of
406 #define lws_container_of(P,T,M) ((T *)((char *)(P) - offsetof(T, M)))
407 #endif
408
409
410 struct lws;
411 #ifndef ARRAY_SIZE
412 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
413 #endif
414
415 /* api change list for user code to test against */
416
417 #define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_ARG
418
419 /* the struct lws_protocols has the id field present */
420 #define LWS_FEATURE_PROTOCOLS_HAS_ID_FIELD
421
422 /* you can call lws_get_peer_write_allowance */
423 #define LWS_FEATURE_PROTOCOLS_HAS_PEER_WRITE_ALLOWANCE
424
425 /* extra parameter introduced in 917f43ab821 */
426 #define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_LEN
427
428 /* File operations stuff exists */
429 #define LWS_FEATURE_FOPS
430
431
432 #if defined(_WIN32)
433 typedef SOCKET lws_sockfd_type;
434 typedef HANDLE lws_filefd_type;
435 #define lws_sockfd_valid(sfd) (!!sfd)
436 struct lws_pollfd {
437         lws_sockfd_type fd; /**< file descriptor */
438         SHORT events; /**< which events to respond to */
439         SHORT revents; /**< which events happened */
440 };
441 #define LWS_POLLHUP (FD_CLOSE)
442 #define LWS_POLLIN (FD_READ | FD_ACCEPT)
443 #define LWS_POLLOUT (FD_WRITE)
444 #else
445
446 #if defined(MBED_OPERATORS)
447 /* it's a class lws_conn * */
448 typedef void * lws_sockfd_type;
449 typedef void * lws_filefd_type;
450 #define lws_sockfd_valid(sfd) (!!sfd)
451 struct pollfd {
452         lws_sockfd_type fd; /**< fd related to */
453         short events; /**< which POLL... events to respond to */
454         short revents; /**< which POLL... events occurred */
455 };
456 #define POLLIN          0x0001
457 #define POLLPRI         0x0002
458 #define POLLOUT         0x0004
459 #define POLLERR         0x0008
460 #define POLLHUP         0x0010
461 #define POLLNVAL        0x0020
462
463 struct lws;
464
465 void * mbed3_create_tcp_stream_socket(void);
466 void mbed3_delete_tcp_stream_socket(void *sockfd);
467 void mbed3_tcp_stream_bind(void *sock, int port, struct lws *);
468 void mbed3_tcp_stream_accept(void *sock, struct lws *);
469 #else
470 #if defined(LWS_WITH_ESP8266)
471
472 #include <user_interface.h>
473 #include <espconn.h>
474
475 typedef struct espconn * lws_sockfd_type;
476 typedef void * lws_filefd_type;
477 #define lws_sockfd_valid(sfd) (!!sfd)
478 struct pollfd {
479         lws_sockfd_type fd; /**< fd related to */
480         short events; /**< which POLL... events to respond to */
481         short revents; /**< which POLL... events occurred */
482 };
483 #define POLLIN          0x0001
484 #define POLLPRI         0x0002
485 #define POLLOUT         0x0004
486 #define POLLERR         0x0008
487 #define POLLHUP         0x0010
488 #define POLLNVAL        0x0020
489
490 struct lws_vhost;
491
492 lws_sockfd_type esp8266_create_tcp_listen_socket(struct lws_vhost *vh);
493 void esp8266_tcp_stream_accept(lws_sockfd_type fd, struct lws *wsi);
494
495 #include <os_type.h>
496 #include <osapi.h>
497 #include "ets_sys.h"
498
499 int ets_snprintf(char *str, size_t size, const char *format, ...) LWS_FORMAT(3);
500 #define snprintf  ets_snprintf
501
502 typedef os_timer_t uv_timer_t;
503 typedef void uv_cb_t(uv_timer_t *);
504
505 void os_timer_disarm(void *);
506 void os_timer_setfn(os_timer_t *, os_timer_func_t *, void *);
507
508 void ets_timer_arm_new(os_timer_t *, int, int, int);
509
510 //void os_timer_arm(os_timer_t *, int, int);
511
512 #define UV_VERSION_MAJOR 1
513
514 #define lws_uv_getloop(a, b) (NULL)
515
516 static inline void uv_timer_init(void *l, uv_timer_t *t)
517 {
518         (void)l;
519         memset(t, 0, sizeof(*t));
520         os_timer_disarm(t);
521 }
522
523 static inline void uv_timer_start(uv_timer_t *t, uv_cb_t *cb, int first, int rep)
524 {
525         os_timer_setfn(t, (os_timer_func_t *)cb, t);
526         /* ms, repeat */
527         os_timer_arm(t, first, !!rep);
528 }
529
530 static inline void uv_timer_stop(uv_timer_t *t)
531 {
532         os_timer_disarm(t);
533 }
534
535 #else
536 typedef int lws_sockfd_type;
537 typedef int lws_filefd_type;
538 #define lws_sockfd_valid(sfd) (sfd >= 0)
539 #endif
540 #endif
541
542 #define lws_pollfd pollfd
543 #define LWS_POLLHUP (POLLHUP|POLLERR)
544 #define LWS_POLLIN (POLLIN)
545 #define LWS_POLLOUT (POLLOUT)
546 #endif
547
548 /** struct lws_pollargs - argument structure for all external poll related calls
549  * passed in via 'in' */
550 struct lws_pollargs {
551         lws_sockfd_type fd;     /**< applicable socket descriptor */
552         int events;             /**< the new event mask */
553         int prev_events;        /**< the previous event mask */
554 };
555
556 struct lws_tokens;
557 struct lws_token_limits;
558
559 /*! \defgroup wsclose Websocket Close
560  *
561  * ##Websocket close frame control
562  *
563  * When we close a ws connection, we can send a reason code and a short
564  * UTF-8 description back with the close packet.
565  */
566 ///@{
567
568 /*
569  * NOTE: These public enums are part of the abi.  If you want to add one,
570  * add it at where specified so existing users are unaffected.
571  */
572 /** enum lws_close_status - RFC6455 close status codes */
573 enum lws_close_status {
574         LWS_CLOSE_STATUS_NOSTATUS                               =    0,
575         LWS_CLOSE_STATUS_NORMAL                                 = 1000,
576         /**< 1000 indicates a normal closure, meaning that the purpose for
577       which the connection was established has been fulfilled. */
578         LWS_CLOSE_STATUS_GOINGAWAY                              = 1001,
579         /**< 1001 indicates that an endpoint is "going away", such as a server
580       going down or a browser having navigated away from a page. */
581         LWS_CLOSE_STATUS_PROTOCOL_ERR                           = 1002,
582         /**< 1002 indicates that an endpoint is terminating the connection due
583       to a protocol error. */
584         LWS_CLOSE_STATUS_UNACCEPTABLE_OPCODE                    = 1003,
585         /**< 1003 indicates that an endpoint is terminating the connection
586       because it has received a type of data it cannot accept (e.g., an
587       endpoint that understands only text data MAY send this if it
588       receives a binary message). */
589         LWS_CLOSE_STATUS_RESERVED                               = 1004,
590         /**< Reserved.  The specific meaning might be defined in the future. */
591         LWS_CLOSE_STATUS_NO_STATUS                              = 1005,
592         /**< 1005 is a reserved value and MUST NOT be set as a status code in a
593       Close control frame by an endpoint.  It is designated for use in
594       applications expecting a status code to indicate that no status
595       code was actually present. */
596         LWS_CLOSE_STATUS_ABNORMAL_CLOSE                         = 1006,
597         /**< 1006 is a reserved value and MUST NOT be set as a status code in a
598       Close control frame by an endpoint.  It is designated for use in
599       applications expecting a status code to indicate that the
600       connection was closed abnormally, e.g., without sending or
601       receiving a Close control frame. */
602         LWS_CLOSE_STATUS_INVALID_PAYLOAD                        = 1007,
603         /**< 1007 indicates that an endpoint is terminating the connection
604       because it has received data within a message that was not
605       consistent with the type of the message (e.g., non-UTF-8 [RFC3629]
606       data within a text message). */
607         LWS_CLOSE_STATUS_POLICY_VIOLATION                       = 1008,
608         /**< 1008 indicates that an endpoint is terminating the connection
609       because it has received a message that violates its policy.  This
610       is a generic status code that can be returned when there is no
611       other more suitable status code (e.g., 1003 or 1009) or if there
612       is a need to hide specific details about the policy. */
613         LWS_CLOSE_STATUS_MESSAGE_TOO_LARGE                      = 1009,
614         /**< 1009 indicates that an endpoint is terminating the connection
615       because it has received a message that is too big for it to
616       process. */
617         LWS_CLOSE_STATUS_EXTENSION_REQUIRED                     = 1010,
618         /**< 1010 indicates that an endpoint (client) is terminating the
619       connection because it has expected the server to negotiate one or
620       more extension, but the server didn't return them in the response
621       message of the WebSocket handshake.  The list of extensions that
622       are needed SHOULD appear in the /reason/ part of the Close frame.
623       Note that this status code is not used by the server, because it
624       can fail the WebSocket handshake instead */
625         LWS_CLOSE_STATUS_UNEXPECTED_CONDITION                   = 1011,
626         /**< 1011 indicates that a server is terminating the connection because
627       it encountered an unexpected condition that prevented it from
628       fulfilling the request. */
629         LWS_CLOSE_STATUS_TLS_FAILURE                            = 1015,
630         /**< 1015 is a reserved value and MUST NOT be set as a status code in a
631       Close control frame by an endpoint.  It is designated for use in
632       applications expecting a status code to indicate that the
633       connection was closed due to a failure to perform a TLS handshake
634       (e.g., the server certificate can't be verified). */
635
636         /****** add new things just above ---^ ******/
637
638         LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY               = 9999,
639 };
640
641 /**
642  * lws_close_reason - Set reason and aux data to send with Close packet
643  *              If you are going to return nonzero from the callback
644  *              requesting the connection to close, you can optionally
645  *              call this to set the reason the peer will be told if
646  *              possible.
647  *
648  * \param wsi:  The websocket connection to set the close reason on
649  * \param status:       A valid close status from websocket standard
650  * \param buf:  NULL or buffer containing up to 124 bytes of auxiliary data
651  * \param len:  Length of data in \param buf to send
652  */
653 LWS_VISIBLE LWS_EXTERN void
654 lws_close_reason(struct lws *wsi, enum lws_close_status status,
655                  unsigned char *buf, size_t len);
656
657 ///@}
658
659 struct lws;
660 struct lws_context;
661 /* needed even with extensions disabled for create context */
662 struct lws_extension;
663
664 /*! \defgroup usercb User Callback
665  *
666  * ##User protocol callback
667  *
668  * The protocol callback is the primary way lws interacts with
669  * user code.  For one of a list of a few dozen reasons the callback gets
670  * called at some event to be handled.
671  *
672  * All of the events can be ignored, returning 0 is taken as "OK" and returning
673  * nonzero in most cases indicates that the connection should be closed.
674  */
675 ///@{
676
677
678 /*
679  * NOTE: These public enums are part of the abi.  If you want to add one,
680  * add it at where specified so existing users are unaffected.
681  */
682 /** enum lws_callback_reasons - reason you're getting a protocol callback */
683 enum lws_callback_reasons {
684         LWS_CALLBACK_ESTABLISHED                                =  0,
685         /**< (VH) after the server completes a handshake with an incoming
686          * client.  If you built the library with ssl support, in is a
687          * pointer to the ssl struct associated with the connection or NULL.*/
688         LWS_CALLBACK_CLIENT_CONNECTION_ERROR                    =  1,
689         /**< the request client connection has been unable to complete a
690          * handshake with the remote server.  If in is non-NULL, you can
691          * find an error string of length len where it points to
692          *
693          * Diagnostic strings that may be returned include
694          *
695          *      "getaddrinfo (ipv6) failed"
696          *      "unknown address family"
697          *      "getaddrinfo (ipv4) failed"
698          *      "set socket opts failed"
699          *      "insert wsi failed"
700          *      "lws_ssl_client_connect1 failed"
701          *      "lws_ssl_client_connect2 failed"
702          *      "Peer hung up"
703          *      "read failed"
704          *      "HS: URI missing"
705          *      "HS: Redirect code but no Location"
706          *      "HS: URI did not parse"
707          *      "HS: Redirect failed"
708          *      "HS: Server did not return 200"
709          *      "HS: OOM"
710          *      "HS: disallowed by client filter"
711          *      "HS: disallowed at ESTABLISHED"
712          *      "HS: ACCEPT missing"
713          *      "HS: ws upgrade response not 101"
714          *      "HS: UPGRADE missing"
715          *      "HS: Upgrade to something other than websocket"
716          *      "HS: CONNECTION missing"
717          *      "HS: UPGRADE malformed"
718          *      "HS: PROTOCOL malformed"
719          *      "HS: Cannot match protocol"
720          *      "HS: EXT: list too big"
721          *      "HS: EXT: failed setting defaults"
722          *      "HS: EXT: failed parsing defaults"
723          *      "HS: EXT: failed parsing options"
724          *      "HS: EXT: Rejects server options"
725          *      "HS: EXT: unknown ext"
726          *      "HS: Accept hash wrong"
727          *      "HS: Rejected by filter cb"
728          *      "HS: OOM"
729          *      "HS: SO_SNDBUF failed"
730          *      "HS: Rejected at CLIENT_ESTABLISHED"
731          */
732         LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH                =  2,
733         /**< this is the last chance for the client user code to examine the
734          * http headers and decide to reject the connection.  If the
735          * content in the headers is interesting to the
736          * client (url, etc) it needs to copy it out at
737          * this point since it will be destroyed before
738          * the CLIENT_ESTABLISHED call */
739         LWS_CALLBACK_CLIENT_ESTABLISHED                         =  3,
740         /**< after your client connection completed
741          * a handshake with the remote server */
742         LWS_CALLBACK_CLOSED                                     =  4,
743         /**< when the websocket session ends */
744         LWS_CALLBACK_CLOSED_HTTP                                =  5,
745         /**< when a HTTP (non-websocket) session ends */
746         LWS_CALLBACK_RECEIVE                                    =  6,
747         /**< data has appeared for this server endpoint from a
748          * remote client, it can be found at *in and is
749          * len bytes long */
750         LWS_CALLBACK_RECEIVE_PONG                               =  7,
751         /**< servers receive PONG packets with this callback reason */
752         LWS_CALLBACK_CLIENT_RECEIVE                             =  8,
753         /**< data has appeared from the server for the client connection, it
754          * can be found at *in and is len bytes long */
755         LWS_CALLBACK_CLIENT_RECEIVE_PONG                        =  9,
756         /**< clients receive PONG packets with this callback reason */
757         LWS_CALLBACK_CLIENT_WRITEABLE                           = 10,
758         /**<  If you call lws_callback_on_writable() on a connection, you will
759          * get one of these callbacks coming when the connection socket
760          * is able to accept another write packet without blocking.
761          * If it already was able to take another packet without blocking,
762          * you'll get this callback at the next call to the service loop
763          * function.  Notice that CLIENTs get LWS_CALLBACK_CLIENT_WRITEABLE
764          * and servers get LWS_CALLBACK_SERVER_WRITEABLE. */
765         LWS_CALLBACK_SERVER_WRITEABLE                           = 11,
766         /**< See LWS_CALLBACK_CLIENT_WRITEABLE */
767         LWS_CALLBACK_HTTP                                       = 12,
768         /**< an http request has come from a client that is not
769          * asking to upgrade the connection to a websocket
770          * one.  This is a chance to serve http content,
771          * for example, to send a script to the client
772          * which will then open the websockets connection.
773          * in points to the URI path requested and
774          * lws_serve_http_file() makes it very
775          * simple to send back a file to the client.
776          * Normally after sending the file you are done
777          * with the http connection, since the rest of the
778          * activity will come by websockets from the script
779          * that was delivered by http, so you will want to
780          * return 1; to close and free up the connection. */
781         LWS_CALLBACK_HTTP_BODY                                  = 13,
782         /**< the next len bytes data from the http
783          * request body HTTP connection is now available in in. */
784         LWS_CALLBACK_HTTP_BODY_COMPLETION                       = 14,
785         /**< the expected amount of http request body has been delivered */
786         LWS_CALLBACK_HTTP_FILE_COMPLETION                       = 15,
787         /**< a file requested to be sent down http link has completed. */
788         LWS_CALLBACK_HTTP_WRITEABLE                             = 16,
789         /**< you can write more down the http protocol link now. */
790         LWS_CALLBACK_FILTER_NETWORK_CONNECTION                  = 17,
791         /**< called when a client connects to
792          * the server at network level; the connection is accepted but then
793          * passed to this callback to decide whether to hang up immediately
794          * or not, based on the client IP.  in contains the connection
795          * socket's descriptor. Since the client connection information is
796          * not available yet, wsi still pointing to the main server socket.
797          * Return non-zero to terminate the connection before sending or
798          * receiving anything. Because this happens immediately after the
799          * network connection from the client, there's no websocket protocol
800          * selected yet so this callback is issued only to protocol 0. */
801         LWS_CALLBACK_FILTER_HTTP_CONNECTION                     = 18,
802         /**< called when the request has
803          * been received and parsed from the client, but the response is
804          * not sent yet.  Return non-zero to disallow the connection.
805          * user is a pointer to the connection user space allocation,
806          * in is the URI, eg, "/"
807          * In your handler you can use the public APIs
808          * lws_hdr_total_length() / lws_hdr_copy() to access all of the
809          * headers using the header enums lws_token_indexes from
810          * libwebsockets.h to check for and read the supported header
811          * presence and content before deciding to allow the http
812          * connection to proceed or to kill the connection. */
813         LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED             = 19,
814         /**< A new client just had
815          * been connected, accepted, and instantiated into the pool. This
816          * callback allows setting any relevant property to it. Because this
817          * happens immediately after the instantiation of a new client,
818          * there's no websocket protocol selected yet so this callback is
819          * issued only to protocol 0. Only wsi is defined, pointing to the
820          * new client, and the return value is ignored. */
821         LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION                 = 20,
822         /**< called when the handshake has
823          * been received and parsed from the client, but the response is
824          * not sent yet.  Return non-zero to disallow the connection.
825          * user is a pointer to the connection user space allocation,
826          * in is the requested protocol name
827          * In your handler you can use the public APIs
828          * lws_hdr_total_length() / lws_hdr_copy() to access all of the
829          * headers using the header enums lws_token_indexes from
830          * libwebsockets.h to check for and read the supported header
831          * presence and content before deciding to allow the handshake
832          * to proceed or to kill the connection. */
833         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS     = 21,
834         /**< if configured for
835          * including OpenSSL support, this callback allows your user code
836          * to perform extra SSL_CTX_load_verify_locations() or similar
837          * calls to direct OpenSSL where to find certificates the client
838          * can use to confirm the remote server identity.  user is the
839          * OpenSSL SSL_CTX* */
840         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS     = 22,
841         /**< if configured for
842          * including OpenSSL support, this callback allows your user code
843          * to load extra certifcates into the server which allow it to
844          * verify the validity of certificates returned by clients.  user
845          * is the server's OpenSSL SSL_CTX* */
846         LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION   = 23,
847         /**< if the libwebsockets vhost was created with the option
848          * LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT, then this
849          * callback is generated during OpenSSL verification of the cert
850          * sent from the client.  It is sent to protocol[0] callback as
851          * no protocol has been negotiated on the connection yet.
852          * Notice that the libwebsockets context and wsi are both NULL
853          * during this callback.  See
854          *  http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html
855          * to understand more detail about the OpenSSL callback that
856          * generates this libwebsockets callback and the meanings of the
857          * arguments passed.  In this callback, user is the x509_ctx,
858          * in is the ssl pointer and len is preverify_ok
859          * Notice that this callback maintains libwebsocket return
860          * conventions, return 0 to mean the cert is OK or 1 to fail it.
861          * This also means that if you don't handle this callback then
862          * the default callback action of returning 0 allows the client
863          * certificates. */
864         LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER             = 24,
865         /**< this callback happens
866          * when a client handshake is being compiled.  user is NULL,
867          * in is a char **, it's pointing to a char * which holds the
868          * next location in the header buffer where you can add
869          * headers, and len is the remaining space in the header buffer,
870          * which is typically some hundreds of bytes.  So, to add a canned
871          * cookie, your handler code might look similar to:
872          *
873          *      char **p = (char **)in;
874          *
875          *      if (len < 100)
876          *              return 1;
877          *
878          *      *p += sprintf(*p, "Cookie: a=b\x0d\x0a");
879          *
880          *      return 0;
881          *
882          * Notice if you add anything, you just have to take care about
883          * the CRLF on the line you added.  Obviously this callback is
884          * optional, if you don't handle it everything is fine.
885          *
886          * Notice the callback is coming to protocols[0] all the time,
887          * because there is no specific protocol negotiated yet. */
888         LWS_CALLBACK_CONFIRM_EXTENSION_OKAY                     = 25,
889         /**< When the server handshake code
890          * sees that it does support a requested extension, before
891          * accepting the extension by additing to the list sent back to
892          * the client it gives this callback just to check that it's okay
893          * to use that extension.  It calls back to the requested protocol
894          * and with in being the extension name, len is 0 and user is
895          * valid.  Note though at this time the ESTABLISHED callback hasn't
896          * happened yet so if you initialize user content there, user
897          * content during this callback might not be useful for anything.
898          * Notice this callback comes to protocols[0]. */
899         LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED         = 26,
900         /**< When a client
901          * connection is being prepared to start a handshake to a server,
902          * each supported extension is checked with protocols[0] callback
903          * with this reason, giving the user code a chance to suppress the
904          * claim to support that extension by returning non-zero.  If
905          * unhandled, by default 0 will be returned and the extension
906          * support included in the header to the server.  Notice this
907          * callback comes to protocols[0]. */
908         LWS_CALLBACK_PROTOCOL_INIT                              = 27,
909         /**< One-time call per protocol, per-vhost using it, so it can
910          * do initial setup / allocations etc */
911         LWS_CALLBACK_PROTOCOL_DESTROY                           = 28,
912         /**< One-time call per protocol, per-vhost using it, indicating
913          * this protocol won't get used at all after this callback, the
914          * vhost is getting destroyed.  Take the opportunity to
915          * deallocate everything that was allocated by the protocol. */
916         LWS_CALLBACK_WSI_CREATE                                 = 29,
917         /**< outermost (earliest) wsi create notification to protocols[0] */
918         LWS_CALLBACK_WSI_DESTROY                                = 30,
919         /**< outermost (latest) wsi destroy notification to protocols[0] */
920         LWS_CALLBACK_GET_THREAD_ID                              = 31,
921         /**< lws can accept callback when writable requests from other
922          * threads, if you implement this callback and return an opaque
923          * current thread ID integer. */
924
925         /* external poll() management support */
926         LWS_CALLBACK_ADD_POLL_FD                                = 32,
927         /**< lws normally deals with its poll() or other event loop
928          * internally, but in the case you are integrating with another
929          * server you will need to have lws sockets share a
930          * polling array with the other server.  This and the other
931          * POLL_FD related callbacks let you put your specialized
932          * poll array interface code in the callback for protocol 0, the
933          * first protocol you support, usually the HTTP protocol in the
934          * serving case.
935          * This callback happens when a socket needs to be
936          * added to the polling loop: in points to a struct
937          * lws_pollargs; the fd member of the struct is the file
938          * descriptor, and events contains the active events
939          *
940          * If you are using the internal lws polling / event loop
941          * you can just ignore these callbacks. */
942         LWS_CALLBACK_DEL_POLL_FD                                = 33,
943         /**< This callback happens when a socket descriptor
944          * needs to be removed from an external polling array.  in is
945          * again the struct lws_pollargs containing the fd member
946          * to be removed.  If you are using the internal polling
947          * loop, you can just ignore it. */
948         LWS_CALLBACK_CHANGE_MODE_POLL_FD                        = 34,
949         /**< This callback happens when lws wants to modify the events for
950          * a connection.
951          * in is the struct lws_pollargs with the fd to change.
952          * The new event mask is in events member and the old mask is in
953          * the prev_events member.
954          * If you are using the internal polling loop, you can just ignore
955          * it. */
956         LWS_CALLBACK_LOCK_POLL                                  = 35,
957         /**< These allow the external poll changes driven
958          * by lws to participate in an external thread locking
959          * scheme around the changes, so the whole thing is threadsafe.
960          * These are called around three activities in the library,
961          *      - inserting a new wsi in the wsi / fd table (len=1)
962          *      - deleting a wsi from the wsi / fd table (len=1)
963          *      - changing a wsi's POLLIN/OUT state (len=0)
964          * Locking and unlocking external synchronization objects when
965          * len == 1 allows external threads to be synchronized against
966          * wsi lifecycle changes if it acquires the same lock for the
967          * duration of wsi dereference from the other thread context. */
968         LWS_CALLBACK_UNLOCK_POLL                                = 36,
969         /**< See LWS_CALLBACK_LOCK_POLL, ignore if using lws internal poll */
970
971         LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY       = 37,
972         /**< if configured for including OpenSSL support but no private key
973          * file has been specified (ssl_private_key_filepath is NULL), this is
974          * called to allow the user to set the private key directly via
975          * libopenssl and perform further operations if required; this might be
976          * useful in situations where the private key is not directly accessible
977          * by the OS, for example if it is stored on a smartcard.
978          * user is the server's OpenSSL SSL_CTX* */
979         LWS_CALLBACK_WS_PEER_INITIATED_CLOSE                    = 38,
980         /**< The peer has sent an unsolicited Close WS packet.  in and
981          * len are the optional close code (first 2 bytes, network
982          * order) and the optional additional information which is not
983          * defined in the standard, and may be a string or non-human- readable data.
984          * If you return 0 lws will echo the close and then close the
985          * connection.  If you return nonzero lws will just close the
986          * connection. */
987
988         LWS_CALLBACK_WS_EXT_DEFAULTS                            = 39,
989         /**<  */
990
991         LWS_CALLBACK_CGI                                        = 40,
992         /**<  */
993         LWS_CALLBACK_CGI_TERMINATED                             = 41,
994         /**<  */
995         LWS_CALLBACK_CGI_STDIN_DATA                             = 42,
996         /**<  */
997         LWS_CALLBACK_CGI_STDIN_COMPLETED                        = 43,
998         /**<  */
999         LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP                    = 44,
1000         /**<  */
1001         LWS_CALLBACK_CLOSED_CLIENT_HTTP                         = 45,
1002         /**<  */
1003         LWS_CALLBACK_RECEIVE_CLIENT_HTTP                        = 46,
1004         /**<  */
1005         LWS_CALLBACK_COMPLETED_CLIENT_HTTP                      = 47,
1006         /**<  */
1007         LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ                   = 48,
1008         /**<  */
1009         LWS_CALLBACK_HTTP_BIND_PROTOCOL                         = 49,
1010         /**<  */
1011         LWS_CALLBACK_HTTP_DROP_PROTOCOL                         = 50,
1012         /**<  */
1013         LWS_CALLBACK_CHECK_ACCESS_RIGHTS                        = 51,
1014         /**<  */
1015         LWS_CALLBACK_PROCESS_HTML                               = 52,
1016         /**<  */
1017         LWS_CALLBACK_ADD_HEADERS                                = 53,
1018         /**<  */
1019         LWS_CALLBACK_SESSION_INFO                               = 54,
1020         /**<  */
1021
1022         LWS_CALLBACK_GS_EVENT                                   = 55,
1023         /**<  */
1024         LWS_CALLBACK_HTTP_PMO                                   = 56,
1025         /**< per-mount options for this connection, called before
1026          * the normal LWS_CALLBACK_HTTP when the mount has per-mount
1027          * options
1028          */
1029         LWS_CALLBACK_CLIENT_HTTP_WRITEABLE                      = 57,
1030         /**< when doing an HTTP type client connection, you can call
1031          * lws_client_http_body_pending(wsi, 1) from
1032          * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER to get these callbacks
1033          * sending the HTTP headers.
1034          *
1035          * From this callback, when you have sent everything, you should let
1036          * lws know by calling lws_client_http_body_pending(wsi, 0)
1037          */
1038         LWS_CALLBACK_OPENSSL_PERFORM_SERVER_CERT_VERIFICATION = 58,
1039         /**< Similar to LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION
1040          * this callback is called during OpenSSL verification of the cert
1041          * sent from the server to the client. It is sent to protocol[0]
1042          * callback as no protocol has been negotiated on the connection yet.
1043          * Notice that the wsi is set because lws_client_connect_via_info was
1044          * successful.
1045          *
1046          * See http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html
1047          * to understand more detail about the OpenSSL callback that
1048          * generates this libwebsockets callback and the meanings of the
1049          * arguments passed. In this callback, user is the x509_ctx,
1050          * in is the ssl pointer and len is preverify_ok.
1051          *
1052          * THIS IS NOT RECOMMENDED BUT if a cert validation error shall be
1053          * overruled and cert shall be accepted as ok,
1054          * X509_STORE_CTX_set_error((X509_STORE_CTX*)user, X509_V_OK); must be
1055          * called and return value must be 0 to mean the cert is OK;
1056          * returning 1 will fail the cert in any case.
1057          *
1058          * This also means that if you don't handle this callback then
1059          * the default callback action of returning 0 will not accept the
1060          * certificate in case of a validation error decided by the SSL lib.
1061          *
1062          * This is expected and secure behaviour when validating certificates.
1063          *
1064          * Note: LCCSCF_ALLOW_SELFSIGNED and
1065          * LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK still work without this
1066          * callback being implemented.
1067          */
1068
1069         /****** add new things just above ---^ ******/
1070
1071         LWS_CALLBACK_USER = 1000,
1072         /**<  user code can use any including / above without fear of clashes */
1073 };
1074
1075
1076
1077 /**
1078  * typedef lws_callback_function() - User server actions
1079  * \param wsi:  Opaque websocket instance pointer
1080  * \param reason:       The reason for the call
1081  * \param user: Pointer to per-session user data allocated by library
1082  * \param in:           Pointer used for some callback reasons
1083  * \param len:  Length set for some callback reasons
1084  *
1085  *      This callback is the way the user controls what is served.  All the
1086  *      protocol detail is hidden and handled by the library.
1087  *
1088  *      For each connection / session there is user data allocated that is
1089  *      pointed to by "user".  You set the size of this user data area when
1090  *      the library is initialized with lws_create_server.
1091  */
1092 typedef int
1093 lws_callback_function(struct lws *wsi, enum lws_callback_reasons reason,
1094                     void *user, void *in, size_t len);
1095 ///@}
1096
1097 /*! \defgroup extensions
1098  *
1099  * ##Extension releated functions
1100  *
1101  *  Ws defines optional extensions, lws provides the ability to implement these
1102  *  in user code if so desired.
1103  *
1104  *  We provide one extensions permessage-deflate.
1105  */
1106 ///@{
1107
1108 /*
1109  * NOTE: These public enums are part of the abi.  If you want to add one,
1110  * add it at where specified so existing users are unaffected.
1111  */
1112 enum lws_extension_callback_reasons {
1113         LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT             =  0,
1114         LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT             =  1,
1115         LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT              =  2,
1116         LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT              =  3,
1117         LWS_EXT_CB_CONSTRUCT                            =  4,
1118         LWS_EXT_CB_CLIENT_CONSTRUCT                     =  5,
1119         LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE             =  6,
1120         LWS_EXT_CB_CHECK_OK_TO_PROPOSE_EXTENSION        =  7,
1121         LWS_EXT_CB_DESTROY                              =  8,
1122         LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING              =  9,
1123         LWS_EXT_CB_ANY_WSI_ESTABLISHED                  = 10,
1124         LWS_EXT_CB_PACKET_RX_PREPARSE                   = 11,
1125         LWS_EXT_CB_PACKET_TX_PRESEND                    = 12,
1126         LWS_EXT_CB_PACKET_TX_DO_SEND                    = 13,
1127         LWS_EXT_CB_HANDSHAKE_REPLY_TX                   = 14,
1128         LWS_EXT_CB_FLUSH_PENDING_TX                     = 15,
1129         LWS_EXT_CB_EXTENDED_PAYLOAD_RX                  = 16,
1130         LWS_EXT_CB_CAN_PROXY_CLIENT_CONNECTION          = 17,
1131         LWS_EXT_CB_1HZ                                  = 18,
1132         LWS_EXT_CB_REQUEST_ON_WRITEABLE                 = 19,
1133         LWS_EXT_CB_IS_WRITEABLE                         = 20,
1134         LWS_EXT_CB_PAYLOAD_TX                           = 21,
1135         LWS_EXT_CB_PAYLOAD_RX                           = 22,
1136         LWS_EXT_CB_OPTION_DEFAULT                       = 23,
1137         LWS_EXT_CB_OPTION_SET                           = 24,
1138         LWS_EXT_CB_OPTION_CONFIRM                       = 25,
1139         LWS_EXT_CB_NAMED_OPTION_SET                     = 26,
1140
1141         /****** add new things just above ---^ ******/
1142 };
1143
1144 /** enum lws_ext_options_types */
1145 enum lws_ext_options_types {
1146         EXTARG_NONE, /**< does not take an argument */
1147         EXTARG_DEC,  /**< requires a decimal argument */
1148         EXTARG_OPT_DEC /**< may have an optional decimal argument */
1149
1150         /* Add new things just above here ---^
1151          * This is part of the ABI, don't needlessly break compatibility */
1152 };
1153
1154 /** struct lws_ext_options -    Option arguments to the extension.  These are
1155  *                              used in the negotiation at ws upgrade time.
1156  *                              The helper function lws_ext_parse_options()
1157  *                              uses these to generate callbacks */
1158 struct lws_ext_options {
1159         const char *name; /**< Option name, eg, "server_no_context_takeover" */
1160         enum lws_ext_options_types type; /**< What kind of args the option can take */
1161
1162         /* Add new things just above here ---^
1163          * This is part of the ABI, don't needlessly break compatibility */
1164 };
1165
1166 /** struct lws_ext_option_arg */
1167 struct lws_ext_option_arg {
1168         const char *option_name; /**< may be NULL, option_index used then */
1169         int option_index; /**< argument ordinal to use if option_name missing */
1170         const char *start; /**< value */
1171         int len; /**< length of value */
1172 };
1173
1174 /**
1175  * typedef lws_extension_callback_function() - Hooks to allow extensions to operate
1176  * \param context:      Websockets context
1177  * \param ext:  This extension
1178  * \param wsi:  Opaque websocket instance pointer
1179  * \param reason:       The reason for the call
1180  * \param user: Pointer to ptr to per-session user data allocated by library
1181  * \param in:           Pointer used for some callback reasons
1182  * \param len:  Length set for some callback reasons
1183  *
1184  *      Each extension that is active on a particular connection receives
1185  *      callbacks during the connection lifetime to allow the extension to
1186  *      operate on websocket data and manage itself.
1187  *
1188  *      Libwebsockets takes care of allocating and freeing "user" memory for
1189  *      each active extension on each connection.  That is what is pointed to
1190  *      by the user parameter.
1191  *
1192  *      LWS_EXT_CB_CONSTRUCT:  called when the server has decided to
1193  *              select this extension from the list provided by the client,
1194  *              just before the server will send back the handshake accepting
1195  *              the connection with this extension active.  This gives the
1196  *              extension a chance to initialize its connection context found
1197  *              in user.
1198  *
1199  *      LWS_EXT_CB_CLIENT_CONSTRUCT: same as LWS_EXT_CB_CONSTRUCT
1200  *              but called when client is instantiating this extension.  Some
1201  *              extensions will work the same on client and server side and then
1202  *              you can just merge handlers for both CONSTRUCTS.
1203  *
1204  *      LWS_EXT_CB_DESTROY:  called when the connection the extension was
1205  *              being used on is about to be closed and deallocated.  It's the
1206  *              last chance for the extension to deallocate anything it has
1207  *              allocated in the user data (pointed to by user) before the
1208  *              user data is deleted.  This same callback is used whether you
1209  *              are in client or server instantiation context.
1210  *
1211  *      LWS_EXT_CB_PACKET_RX_PREPARSE: when this extension was active on
1212  *              a connection, and a packet of data arrived at the connection,
1213  *              it is passed to this callback to give the extension a chance to
1214  *              change the data, eg, decompress it.  user is pointing to the
1215  *              extension's private connection context data, in is pointing
1216  *              to an lws_tokens struct, it consists of a char * pointer called
1217  *              token, and an int called token_len.  At entry, these are
1218  *              set to point to the received buffer and set to the content
1219  *              length.  If the extension will grow the content, it should use
1220  *              a new buffer allocated in its private user context data and
1221  *              set the pointed-to lws_tokens members to point to its buffer.
1222  *
1223  *      LWS_EXT_CB_PACKET_TX_PRESEND: this works the same way as
1224  *              LWS_EXT_CB_PACKET_RX_PREPARSE above, except it gives the
1225  *              extension a chance to change websocket data just before it will
1226  *              be sent out.  Using the same lws_token pointer scheme in in,
1227  *              the extension can change the buffer and the length to be
1228  *              transmitted how it likes.  Again if it wants to grow the
1229  *              buffer safely, it should copy the data into its own buffer and
1230  *              set the lws_tokens token pointer to it.
1231  *
1232  *      LWS_EXT_CB_ARGS_VALIDATE:
1233  */
1234 typedef int
1235 lws_extension_callback_function(struct lws_context *context,
1236                               const struct lws_extension *ext, struct lws *wsi,
1237                               enum lws_extension_callback_reasons reason,
1238                               void *user, void *in, size_t len);
1239
1240 /** struct lws_extension -      An extension we support */
1241 struct lws_extension {
1242         const char *name; /**< Formal extension name, eg, "permessage-deflate" */
1243         lws_extension_callback_function *callback; /**< Service callback */
1244         const char *client_offer; /**< String containing exts and options client offers */
1245
1246         /* Add new things just above here ---^
1247          * This is part of the ABI, don't needlessly break compatibility */
1248 };
1249
1250 /**
1251  * lws_set_extension_option(): set extension option if possible
1252  *
1253  * \param wsi:  websocket connection
1254  * \param ext_name:     name of ext, like "permessage-deflate"
1255  * \param opt_name:     name of option, like "rx_buf_size"
1256  * \param opt_val:      value to set option to
1257  */
1258 LWS_VISIBLE LWS_EXTERN int
1259 lws_set_extension_option(struct lws *wsi, const char *ext_name,
1260                          const char *opt_name, const char *opt_val);
1261
1262 #ifndef LWS_NO_EXTENSIONS
1263 /* lws_get_internal_extensions() - DEPRECATED
1264  *
1265  * \Deprecated There is no longer a set internal extensions table.  The table is provided
1266  * by user code along with application-specific settings.  See the test
1267  * client and server for how to do.
1268  */
1269 static LWS_INLINE LWS_WARN_DEPRECATED const struct lws_extension *
1270 lws_get_internal_extensions(void) { return NULL; }
1271
1272 /**
1273  * lws_ext_parse_options() - deal with parsing negotiated extension options
1274  *
1275  * \param ext: related extension struct
1276  * \param wsi:  websocket connection
1277  * \param ext_user: per-connection extension private data
1278  * \param opts: list of supported options
1279  * \param o: option string to parse
1280  * \param len: length
1281  */
1282 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
1283 lws_ext_parse_options(const struct lws_extension *ext, struct lws *wsi,
1284                        void *ext_user, const struct lws_ext_options *opts,
1285                        const char *o, int len);
1286 #endif
1287
1288 /** lws_extension_callback_pm_deflate() - extension for RFC7692
1289  *
1290  * \param context:      lws context
1291  * \param ext:  related lws_extension struct
1292  * \param wsi:  websocket connection
1293  * \param reason:       incoming callback reason
1294  * \param user: per-connection extension private data
1295  * \param in:   pointer parameter
1296  * \param len:  length parameter
1297  *
1298  * Built-in callback implementing RFC7692 permessage-deflate
1299  */
1300 LWS_EXTERN
1301 int lws_extension_callback_pm_deflate(
1302         struct lws_context *context, const struct lws_extension *ext,
1303         struct lws *wsi, enum lws_extension_callback_reasons reason,
1304         void *user, void *in, size_t len);
1305
1306 /*
1307  * The internal exts are part of the public abi
1308  * If we add more extensions, publish the callback here  ------v
1309  */
1310 ///@}
1311
1312 /*! \defgroup Protocols-and-Plugins Protocols and Plugins
1313  * \ingroup lwsapi
1314  *
1315  * ##Protocol and protocol plugin -related apis
1316  *
1317  * Protocols bind ws protocol names to a custom callback specific to that
1318  * protocol implementaion.
1319  *
1320  * A list of protocols can be passed in at context creation time, but it is
1321  * also legal to leave that NULL and add the protocols and their callback code
1322  * using plugins.
1323  *
1324  * Plugins are much preferable compared to cut and pasting code into an
1325  * application each time, since they can be used standalone.
1326  */
1327 ///@{
1328 /** struct lws_protocols -      List of protocols and handlers client or server
1329  *                                      supports. */
1330
1331 struct lws_protocols {
1332         const char *name;
1333         /**< Protocol name that must match the one given in the client
1334          * Javascript new WebSocket(url, 'protocol') name. */
1335         lws_callback_function *callback;
1336         /**< The service callback used for this protocol.  It allows the
1337          * service action for an entire protocol to be encapsulated in
1338          * the protocol-specific callback */
1339         size_t per_session_data_size;
1340         /**< Each new connection using this protocol gets
1341          * this much memory allocated on connection establishment and
1342          * freed on connection takedown.  A pointer to this per-connection
1343          * allocation is passed into the callback in the 'user' parameter */
1344         size_t rx_buffer_size;
1345         /**< lws allocates this much space for rx data and informs callback
1346          * when something came.  Due to rx flow control, the callback may not
1347          * be able to consume it all without having to return to the event
1348          * loop.  That is supported in lws.
1349          *
1350          * This also controls how much may be sent at once at the moment,
1351          * although this is likely to change.
1352          */
1353         unsigned int id;
1354         /**< ignored by lws, but useful to contain user information bound
1355          * to the selected protocol.  For example if this protocol was
1356          * called "myprotocol-v2", you might set id to 2, and the user
1357          * code that acts differently according to the version can do so by
1358          * switch (wsi->protocol->id), user code might use some bits as
1359          * capability flags based on selected protocol version, etc. */
1360         void *user; /**< ignored by lws, but user code can pass a pointer
1361                         here it can later access from the protocol callback */
1362
1363         /* Add new things just above here ---^
1364          * This is part of the ABI, don't needlessly break compatibility */
1365 };
1366
1367 struct lws_vhost;
1368
1369 /**
1370  * lws_vhost_name_to_protocol() - get vhost's protocol object from its name
1371  *
1372  * \param vh: vhost to search
1373  * \param name: protocol name
1374  *
1375  * Returns NULL or a pointer to the vhost's protocol of the requested name
1376  */
1377 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1378 lws_vhost_name_to_protocol(struct lws_vhost *vh, const char *name);
1379
1380 /**
1381  * lws_get_protocol() - Returns a protocol pointer from a websocket
1382  *                                connection.
1383  * \param wsi:  pointer to struct websocket you want to know the protocol of
1384  *
1385  *
1386  *      Some apis can act on all live connections of a given protocol,
1387  *      this is how you can get a pointer to the active protocol if needed.
1388  */
1389 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1390 lws_get_protocol(struct lws *wsi);
1391
1392 /** lws_protocol_get() -  deprecated: use lws_get_protocol */
1393 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
1394 lws_protocol_get(struct lws *wsi) LWS_WARN_DEPRECATED;
1395
1396 /**
1397  * lws_protocol_vh_priv_zalloc() - Allocate and zero down a protocol's per-vhost
1398  *                                 storage
1399  * \param vhost:        vhost the instance is related to
1400  * \param prot:         protocol the instance is related to
1401  * \param size:         bytes to allocate
1402  *
1403  * Protocols often find it useful to allocate a per-vhost struct, this is a
1404  * helper to be called in the per-vhost init LWS_CALLBACK_PROTOCOL_INIT
1405  */
1406 LWS_VISIBLE LWS_EXTERN void *
1407 lws_protocol_vh_priv_zalloc(struct lws_vhost *vhost, const struct lws_protocols *prot,
1408                             int size);
1409
1410 /**
1411  * lws_protocol_vh_priv_get() - retreive a protocol's per-vhost storage
1412  *
1413  * \param vhost:        vhost the instance is related to
1414  * \param prot:         protocol the instance is related to
1415  *
1416  * Recover a pointer to the allocated per-vhost storage for the protocol created
1417  * by lws_protocol_vh_priv_zalloc() earlier
1418  */
1419 LWS_VISIBLE LWS_EXTERN void *
1420 lws_protocol_vh_priv_get(struct lws_vhost *vhost, const struct lws_protocols *prot);
1421
1422 /**
1423  * lws_finalize_startup() - drop initial process privileges
1424  *
1425  * \param context:      lws context
1426  *
1427  * This is called after the end of the vhost protocol initializations, but
1428  * you may choose to call it earlier
1429  */
1430 LWS_VISIBLE LWS_EXTERN int
1431 lws_finalize_startup(struct lws_context *context);
1432
1433 #ifdef LWS_WITH_PLUGINS
1434
1435 /* PLUGINS implies LIBUV */
1436
1437 #define LWS_PLUGIN_API_MAGIC 180
1438
1439 /** struct lws_plugin_capability - how a plugin introduces itself to lws */
1440 struct lws_plugin_capability {
1441         unsigned int api_magic; /**< caller fills this in, plugin fills rest */
1442         const struct lws_protocols *protocols; /**< array of supported protocols provided by plugin */
1443         int count_protocols; /**< how many protocols */
1444         const struct lws_extension *extensions; /**< array of extensions provided by plugin */
1445         int count_extensions; /**< how many extensions */
1446 };
1447
1448 typedef int (*lws_plugin_init_func)(struct lws_context *,
1449                                     struct lws_plugin_capability *);
1450 typedef int (*lws_plugin_destroy_func)(struct lws_context *);
1451
1452 /** struct lws_plugin */
1453 struct lws_plugin {
1454         struct lws_plugin *list; /**< linked list */
1455 #if (UV_VERSION_MAJOR > 0)
1456         uv_lib_t lib; /**< shared library pointer */
1457 #else
1458         void *l; /**< so we can compile on ancient libuv */
1459 #endif
1460         char name[64]; /**< name of the plugin */
1461         struct lws_plugin_capability caps; /**< plugin capabilities */
1462 };
1463
1464 #endif
1465
1466 ///@}
1467
1468
1469 /*! \defgroup generic-sessions plugin: generic-sessions
1470  * \ingroup Protocols-and-Plugins
1471  *
1472  * ##Plugin Generic-sessions related
1473  *
1474  * generic-sessions plugin provides a reusable, generic session and login /
1475  * register / forgot password framework including email verification.
1476  */
1477 ///@{
1478
1479 #define LWSGS_EMAIL_CONTENT_SIZE 16384
1480 /**< Maximum size of email we might send */
1481
1482 /* SHA-1 binary and hexified versions */
1483 /** typedef struct lwsgw_hash_bin */
1484 typedef struct { unsigned char bin[20]; /**< binary representation of hash */} lwsgw_hash_bin;
1485 /** typedef struct lwsgw_hash */
1486 typedef struct { char id[41]; /**< ascii hex representation of hash */ } lwsgw_hash;
1487
1488 /** enum lwsgs_auth_bits */
1489 enum lwsgs_auth_bits {
1490         LWSGS_AUTH_LOGGED_IN = 1, /**< user is logged in as somebody */
1491         LWSGS_AUTH_ADMIN = 2,   /**< logged in as the admin user */
1492         LWSGS_AUTH_VERIFIED = 4,  /**< user has verified his email */
1493         LWSGS_AUTH_FORGOT_FLOW = 8,     /**< he just completed "forgot password" flow */
1494 };
1495
1496 /** struct lws_session_info - information about user session status */
1497 struct lws_session_info {
1498         char username[32]; /**< username logged in as, or empty string */
1499         char email[100]; /**< email address associated with login, or empty string */
1500         char ip[72]; /**< ip address session was started from */
1501         unsigned int mask; /**< access rights mask associated with session
1502                             * see enum lwsgs_auth_bits */
1503         char session[42]; /**< session id string, usable as opaque uid when not logged in */
1504 };
1505
1506 /** enum lws_gs_event */
1507 enum lws_gs_event {
1508         LWSGSE_CREATED, /**< a new user was created */
1509         LWSGSE_DELETED  /**< an existing user was deleted */
1510 };
1511
1512 /** struct lws_gs_event_args */
1513 struct lws_gs_event_args {
1514         enum lws_gs_event event; /**< which event happened */
1515         const char *username; /**< which username the event happened to */
1516         const char *email; /**< the email address of that user */
1517 };
1518
1519 ///@}
1520
1521
1522 /*! \defgroup context-and-vhost
1523  * \ingroup lwsapi
1524  *
1525  * ##Context and Vhost releated functions
1526  *
1527  *  LWS requires that there is one context, in which you may define multiple
1528  *  vhosts.  Each vhost is a virtual host, with either its own listen port
1529  *  or sharing an existing one.  Each vhost has its own SSL context that can
1530  *  be set up individually or left disabled.
1531  *
1532  *  If you don't care about multiple "site" support, you can ignore it and
1533  *  lws will create a single default vhost at context creation time.
1534  */
1535 ///@{
1536
1537 /*
1538  * NOTE: These public enums are part of the abi.  If you want to add one,
1539  * add it at where specified so existing users are unaffected.
1540  */
1541
1542 /** enum lws_context_options - context and vhost options */
1543 enum lws_context_options {
1544         LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT     = (1 << 1) |
1545                                                                   (1 << 12),
1546         /**< (VH) Don't allow the connection unless the client has a
1547          * client cert that we recognize; provides
1548          * LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT */
1549         LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME            = (1 << 2),
1550         /**< (CTX) Don't try to get the server's hostname */
1551         LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT             = (1 << 3) |
1552                                                                   (1 << 12),
1553         /**< (VH) Allow non-SSL (plaintext) connections on the same
1554          * port as SSL is listening... undermines the security of SSL;
1555          * provides  LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT */
1556         LWS_SERVER_OPTION_LIBEV                                 = (1 << 4),
1557         /**< (CTX) Use libev event loop */
1558         LWS_SERVER_OPTION_DISABLE_IPV6                          = (1 << 5),
1559         /**< (VH) Disable IPV6 support */
1560         LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS                   = (1 << 6),
1561         /**< (VH) Don't load OS CA certs, you will need to load your
1562          * own CA cert(s) */
1563         LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED                = (1 << 7),
1564         /**< (VH) Accept connections with no valid Cert (eg, selfsigned) */
1565         LWS_SERVER_OPTION_VALIDATE_UTF8                         = (1 << 8),
1566         /**< (VH) Check UT-8 correctness */
1567         LWS_SERVER_OPTION_SSL_ECDH                              = (1 << 9) |
1568                                                                   (1 << 12),
1569         /**< (VH)  initialize ECDH ciphers */
1570         LWS_SERVER_OPTION_LIBUV                                 = (1 << 10),
1571         /**< (CTX)  Use libuv event loop */
1572         LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS                = (1 << 11) |
1573                                                                   (1 << 12),
1574         /**< (VH) Use http redirect to force http to https
1575          * (deprecated: use mount redirection) */
1576         LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT                    = (1 << 12),
1577         /**< (CTX) Initialize the SSL library at all */
1578         LWS_SERVER_OPTION_EXPLICIT_VHOSTS                       = (1 << 13),
1579         /**< (CTX) Only create the context when calling context
1580          * create api, implies user code will create its own vhosts */
1581         LWS_SERVER_OPTION_UNIX_SOCK                             = (1 << 14),
1582         /**< (VH) Use Unix socket */
1583         LWS_SERVER_OPTION_STS                                   = (1 << 15),
1584         /**< (VH) Send Strict Transport Security header, making
1585          * clients subsequently go to https even if user asked for http */
1586         LWS_SERVER_OPTION_IPV6_V6ONLY_MODIFY                    = (1 << 16),
1587         /**< (VH) Enable LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE to take effect */
1588         LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE                     = (1 << 17),
1589         /**< (VH) if set, only ipv6 allowed on the vhost */
1590         LWS_SERVER_OPTION_UV_NO_SIGSEGV_SIGFPE_SPIN             = (1 << 18),
1591         /**< (CTX) Libuv only: Do not spin on SIGSEGV / SIGFPE.  A segfault
1592          * normally makes the lib spin so you can attach a debugger to it
1593          * even if it happened without a debugger in place.  You can disable
1594          * that by giving this option.
1595          */
1596         LWS_SERVER_OPTION_JUST_USE_RAW_ORIGIN                   = (1 << 19),
1597         /**< For backwards-compatibility reasons, by default
1598          * lws prepends "http://" to the origin you give in the client
1599          * connection info struct.  If you give this flag when you create
1600          * the context, only the string you give in the client connect
1601          * info for .origin (if any) will be used directly.
1602          */
1603
1604         /****** add new things just above ---^ ******/
1605 };
1606
1607 #define lws_check_opt(c, f) (((c) & (f)) == (f))
1608
1609 /** struct lws_context_creation_info - parameters to create context and /or vhost with
1610  *
1611  * This is also used to create vhosts.... if LWS_SERVER_OPTION_EXPLICIT_VHOSTS
1612  * is not given, then for backwards compatibility one vhost is created at
1613  * context-creation time using the info from this struct.
1614  *
1615  * If LWS_SERVER_OPTION_EXPLICIT_VHOSTS is given, then no vhosts are created
1616  * at the same time as the context, they are expected to be created afterwards.
1617  */
1618 struct lws_context_creation_info {
1619         int port;
1620         /**< VHOST: Port to listen on. Use CONTEXT_PORT_NO_LISTEN to suppress
1621          * listening for a client. Use CONTEXT_PORT_NO_LISTEN_SERVER if you are
1622          * writing a server but you are using \ref sock-adopt instead of the
1623          * built-in listener */
1624         const char *iface;
1625         /**< VHOST: NULL to bind the listen socket to all interfaces, or the
1626          * interface name, eg, "eth2"
1627          * If options specifies LWS_SERVER_OPTION_UNIX_SOCK, this member is
1628          * the pathname of a UNIX domain socket. you can use the UNIX domain
1629          * sockets in abstract namespace, by prepending an at symbol to the
1630          * socket name. */
1631         const struct lws_protocols *protocols;
1632         /**< VHOST: Array of structures listing supported protocols and a protocol-
1633          * specific callback for each one.  The list is ended with an
1634          * entry that has a NULL callback pointer. */
1635         const struct lws_extension *extensions;
1636         /**< VHOST: NULL or array of lws_extension structs listing the
1637          * extensions this context supports. */
1638         const struct lws_token_limits *token_limits;
1639         /**< CONTEXT: NULL or struct lws_token_limits pointer which is initialized
1640          * with a token length limit for each possible WSI_TOKEN_ */
1641         const char *ssl_private_key_password;
1642         /**< VHOST: NULL or the passphrase needed for the private key */
1643         const char *ssl_cert_filepath;
1644         /**< VHOST: If libwebsockets was compiled to use ssl, and you want
1645          * to listen using SSL, set to the filepath to fetch the
1646          * server cert from, otherwise NULL for unencrypted */
1647         const char *ssl_private_key_filepath;
1648         /**<  VHOST: filepath to private key if wanting SSL mode;
1649          * if this is set to NULL but sll_cert_filepath is set, the
1650          * OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY callback is called
1651          * to allow setting of the private key directly via openSSL
1652          * library calls */
1653         const char *ssl_ca_filepath;
1654         /**< VHOST: CA certificate filepath or NULL */
1655         const char *ssl_cipher_list;
1656         /**< VHOST: List of valid ciphers to use (eg,
1657          * "RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL"
1658          * or you can leave it as NULL to get "DEFAULT" */
1659         const char *http_proxy_address;
1660         /**< VHOST: If non-NULL, attempts to proxy via the given address.
1661          * If proxy auth is required, use format "username:password\@server:port" */
1662         unsigned int http_proxy_port;
1663         /**< VHOST: If http_proxy_address was non-NULL, uses this port */
1664         int gid;
1665         /**< CONTEXT: group id to change to after setting listen socket, or -1. */
1666         int uid;
1667         /**< CONTEXT: user id to change to after setting listen socket, or -1. */
1668         unsigned int options;
1669         /**< VHOST + CONTEXT: 0, or LWS_SERVER_OPTION_... bitfields */
1670         void *user;
1671         /**< CONTEXT: optional user pointer that can be recovered via the context
1672  *              pointer using lws_context_user */
1673         int ka_time;
1674         /**< CONTEXT: 0 for no TCP keepalive, otherwise apply this keepalive
1675          * timeout to all libwebsocket sockets, client or server */
1676         int ka_probes;
1677         /**< CONTEXT: if ka_time was nonzero, after the timeout expires how many
1678          * times to try to get a response from the peer before giving up
1679          * and killing the connection */
1680         int ka_interval;
1681         /**< CONTEXT: if ka_time was nonzero, how long to wait before each ka_probes
1682          * attempt */
1683 #ifdef LWS_OPENSSL_SUPPORT
1684         SSL_CTX *provided_client_ssl_ctx;
1685         /**< CONTEXT: If non-null, swap out libwebsockets ssl
1686  *              implementation for the one provided by provided_ssl_ctx.
1687  *              Libwebsockets no longer is responsible for freeing the context
1688  *              if this option is selected. */
1689 #else /* maintain structure layout either way */
1690         void *provided_client_ssl_ctx; /**< dummy if ssl disabled */
1691 #endif
1692
1693         short max_http_header_data;
1694         /**< CONTEXT: The max amount of header payload that can be handled
1695          * in an http request (unrecognized header payload is dropped) */
1696         short max_http_header_pool;
1697         /**< CONTEXT: The max number of connections with http headers that
1698          * can be processed simultaneously (the corresponding memory is
1699          * allocated for the lifetime of the context).  If the pool is
1700          * busy new incoming connections must wait for accept until one
1701          * becomes free. */
1702
1703         unsigned int count_threads;
1704         /**< CONTEXT: how many contexts to create in an array, 0 = 1 */
1705         unsigned int fd_limit_per_thread;
1706         /**< CONTEXT: nonzero means restrict each service thread to this
1707          * many fds, 0 means the default which is divide the process fd
1708          * limit by the number of threads. */
1709         unsigned int timeout_secs;
1710         /**< VHOST: various processes involving network roundtrips in the
1711          * library are protected from hanging forever by timeouts.  If
1712          * nonzero, this member lets you set the timeout used in seconds.
1713          * Otherwise a default timeout is used. */
1714         const char *ecdh_curve;
1715         /**< VHOST: if NULL, defaults to initializing server with "prime256v1" */
1716         const char *vhost_name;
1717         /**< VHOST: name of vhost, must match external DNS name used to
1718          * access the site, like "warmcat.com" as it's used to match
1719          * Host: header and / or SNI name for SSL. */
1720         const char * const *plugin_dirs;
1721         /**< CONTEXT: NULL, or NULL-terminated array of directories to
1722          * scan for lws protocol plugins at context creation time */
1723         const struct lws_protocol_vhost_options *pvo;
1724         /**< VHOST: pointer to optional linked list of per-vhost
1725          * options made accessible to protocols */
1726         int keepalive_timeout;
1727         /**< VHOST: (default = 0 = 60s) seconds to allow remote
1728          * client to hold on to an idle HTTP/1.1 connection */
1729         const char *log_filepath;
1730         /**< VHOST: filepath to append logs to... this is opened before
1731          *              any dropping of initial privileges */
1732         const struct lws_http_mount *mounts;
1733         /**< VHOST: optional linked list of mounts for this vhost */
1734         const char *server_string;
1735         /**< CONTEXT: string used in HTTP headers to identify server
1736  *              software, if NULL, "libwebsockets". */
1737         unsigned int pt_serv_buf_size;
1738         /**< CONTEXT: 0 = default of 4096.  This buffer is used by
1739          * various service related features including file serving, it
1740          * defines the max chunk of file that can be sent at once.
1741          * At the risk of lws having to buffer failed large sends, it
1742          * can be increased to, eg, 128KiB to improve throughput. */
1743         unsigned int max_http_header_data2;
1744         /**< CONTEXT: if max_http_header_data is 0 and this
1745          * is nonzero, this will be used in place of the default.  It's
1746          * like this for compatibility with the original short version,
1747          * this is unsigned int length. */
1748         long ssl_options_set;
1749         /**< VHOST: Any bits set here will be set as SSL options */
1750         long ssl_options_clear;
1751         /**< VHOST: Any bits set here will be cleared as SSL options */
1752         unsigned short ws_ping_pong_interval;
1753         /**< CONTEXT: 0 for none, else interval in seconds between sending
1754          * PINGs on idle websocket connections.  When the PING is sent,
1755          * the PONG must come within the normal timeout_secs timeout period
1756          * or the connection will be dropped.
1757          * Any RX or TX traffic on the connection restarts the interval timer,
1758          * so a connection which always sends or receives something at intervals
1759          * less than the interval given here will never send PINGs / expect
1760          * PONGs.  Conversely as soon as the ws connection is established, an
1761          * idle connection will do the PING / PONG roundtrip as soon as
1762          * ws_ping_pong_interval seconds has passed without traffic
1763          */
1764         const struct lws_protocol_vhost_options *headers;
1765                 /**< VHOST: pointer to optional linked list of per-vhost
1766                  * canned headers that are added to server responses */
1767
1768         const struct lws_protocol_vhost_options *reject_service_keywords;
1769         /**< CONTEXT: Optional list of keywords and rejection codes + text.
1770          *
1771          * The keywords are checked for existing in the user agent string.
1772          *
1773          * Eg, "badrobot" "404 Not Found"
1774          */
1775         void *external_baggage_free_on_destroy;
1776         /**< CONTEXT: NULL, or pointer to something externally malloc'd, that
1777          * should be freed when the context is destroyed.  This allows you to
1778          * automatically sync the freeing action to the context destruction
1779          * action, so there is no need for an external free() if the context
1780          * succeeded to create.
1781          */
1782
1783         /* Add new things just above here ---^
1784          * This is part of the ABI, don't needlessly break compatibility
1785          *
1786          * The below is to ensure later library versions with new
1787          * members added above will see 0 (default) even if the app
1788          * was not built against the newer headers.
1789          */
1790
1791         void *_unused[8]; /**< dummy */
1792 };
1793
1794 /**
1795  * lws_create_context() - Create the websocket handler
1796  * \param info: pointer to struct with parameters
1797  *
1798  *      This function creates the listening socket (if serving) and takes care
1799  *      of all initialization in one step.
1800  *
1801  *      If option LWS_SERVER_OPTION_EXPLICIT_VHOSTS is given, no vhost is
1802  *      created; you're expected to create your own vhosts afterwards using
1803  *      lws_create_vhost().  Otherwise a vhost named "default" is also created
1804  *      using the information in the vhost-related members, for compatibility.
1805  *
1806  *      After initialization, it returns a struct lws_context * that
1807  *      represents this server.  After calling, user code needs to take care
1808  *      of calling lws_service() with the context pointer to get the
1809  *      server's sockets serviced.  This must be done in the same process
1810  *      context as the initialization call.
1811  *
1812  *      The protocol callback functions are called for a handful of events
1813  *      including http requests coming in, websocket connections becoming
1814  *      established, and data arriving; it's also called periodically to allow
1815  *      async transmission.
1816  *
1817  *      HTTP requests are sent always to the FIRST protocol in protocol, since
1818  *      at that time websocket protocol has not been negotiated.  Other
1819  *      protocols after the first one never see any HTTP callback activity.
1820  *
1821  *      The server created is a simple http server by default; part of the
1822  *      websocket standard is upgrading this http connection to a websocket one.
1823  *
1824  *      This allows the same server to provide files like scripts and favicon /
1825  *      images or whatever over http and dynamic data over websockets all in
1826  *      one place; they're all handled in the user callback.
1827  */
1828 LWS_VISIBLE LWS_EXTERN struct lws_context *
1829 lws_create_context(struct lws_context_creation_info *info);
1830
1831 /**
1832  * lws_context_destroy() - Destroy the websocket context
1833  * \param context:      Websocket context
1834  *
1835  *      This function closes any active connections and then frees the
1836  *      context.  After calling this, any further use of the context is
1837  *      undefined.
1838  */
1839 LWS_VISIBLE LWS_EXTERN void
1840 lws_context_destroy(struct lws_context *context);
1841
1842 LWS_VISIBLE LWS_EXTERN void
1843 lws_context_destroy2(struct lws_context *context);
1844
1845 typedef int (*lws_reload_func)(void);
1846
1847 /**
1848  * lws_context_deprecate() - Deprecate the websocket context
1849  * \param context:      Websocket context
1850  *
1851  *      This function is used on an existing context before superceding it
1852  *      with a new context.
1853  *
1854  *      It closes any listen sockets in the context, so new connections are
1855  *      not possible.
1856  *
1857  *      And it marks the context to be deleted when the number of active
1858  *      connections into it falls to zero.
1859  *
1860  *      Otherwise if you attach the deprecated context to the replacement
1861  *      context when it has been created using lws_context_attach_deprecated()
1862  *      both any deprecated and the new context will service their connections.
1863  *
1864  *      This is aimed at allowing seamless configuration reloads.
1865  *
1866  *      The callback cb will be called after the listen sockets are actually
1867  *      closed and may be reopened.  In the callback the new context should be
1868  *      configured and created.  (With libuv, socket close happens async after
1869  *      more loop events).
1870  */
1871 LWS_VISIBLE LWS_EXTERN void
1872 lws_context_deprecate(struct lws_context *context, lws_reload_func cb);
1873
1874 LWS_VISIBLE LWS_EXTERN int
1875 lws_context_is_deprecated(struct lws_context *context);
1876
1877 /**
1878  * lws_set_proxy() - Setups proxy to lws_context.
1879  * \param vhost:        pointer to struct lws_vhost you want set proxy for
1880  * \param proxy: pointer to c string containing proxy in format address:port
1881  *
1882  * Returns 0 if proxy string was parsed and proxy was setup.
1883  * Returns -1 if proxy is NULL or has incorrect format.
1884  *
1885  * This is only required if your OS does not provide the http_proxy
1886  * environment variable (eg, OSX)
1887  *
1888  *   IMPORTANT! You should call this function right after creation of the
1889  *   lws_context and before call to connect. If you call this
1890  *   function after connect behavior is undefined.
1891  *   This function will override proxy settings made on lws_context
1892  *   creation with genenv() call.
1893  */
1894 LWS_VISIBLE LWS_EXTERN int
1895 lws_set_proxy(struct lws_vhost *vhost, const char *proxy);
1896
1897
1898 struct lws_vhost;
1899
1900 /**
1901  * lws_create_vhost() - Create a vhost (virtual server context)
1902  * \param context:      pointer to result of lws_create_context()
1903  * \param info:         pointer to struct with parameters
1904  *
1905  * This function creates a virtual server (vhost) using the vhost-related
1906  * members of the info struct.  You can create many vhosts inside one context
1907  * if you created the context with the option LWS_SERVER_OPTION_EXPLICIT_VHOSTS
1908  */
1909 LWS_EXTERN LWS_VISIBLE struct lws_vhost *
1910 lws_create_vhost(struct lws_context *context,
1911                  struct lws_context_creation_info *info);
1912
1913 /**
1914  * lwsws_get_config_globals() - Parse a JSON server config file
1915  * \param info:         pointer to struct with parameters
1916  * \param d:            filepath of the config file
1917  * \param config_strings: storage for the config strings extracted from JSON,
1918  *                        the pointer is incremented as strings are stored
1919  * \param len:          pointer to the remaining length left in config_strings
1920  *                        the value is decremented as strings are stored
1921  *
1922  * This function prepares a n lws_context_creation_info struct with global
1923  * settings from a file d.
1924  *
1925  * Requires CMake option LWS_WITH_LEJP_CONF to have been enabled
1926  */
1927 LWS_VISIBLE LWS_EXTERN int
1928 lwsws_get_config_globals(struct lws_context_creation_info *info, const char *d,
1929                          char **config_strings, int *len);
1930
1931 /**
1932  * lwsws_get_config_vhosts() - Create vhosts from a JSON server config file
1933  * \param context:      pointer to result of lws_create_context()
1934  * \param info:         pointer to struct with parameters
1935  * \param d:            filepath of the config file
1936  * \param config_strings: storage for the config strings extracted from JSON,
1937  *                        the pointer is incremented as strings are stored
1938  * \param len:          pointer to the remaining length left in config_strings
1939  *                        the value is decremented as strings are stored
1940  *
1941  * This function creates vhosts into a context according to the settings in
1942  *JSON files found in directory d.
1943  *
1944  * Requires CMake option LWS_WITH_LEJP_CONF to have been enabled
1945  */
1946 LWS_VISIBLE LWS_EXTERN int
1947 lwsws_get_config_vhosts(struct lws_context *context,
1948                         struct lws_context_creation_info *info, const char *d,
1949                         char **config_strings, int *len);
1950
1951 /** lws_vhost_get() - \deprecated deprecated: use lws_get_vhost() */
1952 LWS_VISIBLE LWS_EXTERN struct lws_vhost *
1953 lws_vhost_get(struct lws *wsi) LWS_WARN_DEPRECATED;
1954
1955 /**
1956  * lws_get_vhost() - return the vhost a wsi belongs to
1957  *
1958  * \param wsi: which connection
1959  */
1960 LWS_VISIBLE LWS_EXTERN struct lws_vhost *
1961 lws_get_vhost(struct lws *wsi);
1962
1963 /**
1964  * lws_json_dump_vhost() - describe vhost state and stats in JSON
1965  *
1966  * \param vh: the vhost
1967  * \param buf: buffer to fill with JSON
1968  * \param len: max length of buf
1969  */
1970 LWS_VISIBLE LWS_EXTERN int
1971 lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len);
1972
1973 /**
1974  * lws_json_dump_context() - describe context state and stats in JSON
1975  *
1976  * \param context: the context
1977  * \param buf: buffer to fill with JSON
1978  * \param len: max length of buf
1979  */
1980 LWS_VISIBLE LWS_EXTERN int
1981 lws_json_dump_context(const struct lws_context *context, char *buf, int len,
1982                       int hide_vhosts);
1983
1984 /**
1985  * lws_context_user() - get the user data associated with the context
1986  * \param context: Websocket context
1987  *
1988  * This returns the optional user allocation that can be attached to
1989  * the context the sockets live in at context_create time.  It's a way
1990  * to let all sockets serviced in the same context share data without
1991  * using globals statics in the user code.
1992  */
1993 LWS_VISIBLE LWS_EXTERN void *
1994 lws_context_user(struct lws_context *context);
1995
1996 /*! \defgroup vhost-mounts Vhost mounts and options
1997  * \ingroup context-and-vhost-creation
1998  *
1999  * ##Vhost mounts and options
2000  */
2001 ///@{
2002 /** struct lws_protocol_vhost_options - linked list of per-vhost protocol
2003  *                                      name=value options
2004  *
2005  * This provides a general way to attach a linked-list of name=value pairs,
2006  * which can also have an optional child link-list using the options member.
2007  */
2008 struct lws_protocol_vhost_options {
2009         const struct lws_protocol_vhost_options *next; /**< linked list */
2010         const struct lws_protocol_vhost_options *options; /**< child linked-list of more options for this node */
2011         const char *name; /**< name of name=value pair */
2012         const char *value; /**< value of name=value pair */
2013 };
2014
2015 /** enum lws_mount_protocols
2016  * This specifies the mount protocol for a mountpoint, whether it is to be
2017  * served from a filesystem, or it is a cgi etc.
2018  */
2019 enum lws_mount_protocols {
2020         LWSMPRO_HTTP            = 0, /**< not supported yet */
2021         LWSMPRO_HTTPS           = 1, /**< not supported yet */
2022         LWSMPRO_FILE            = 2, /**< serve from filesystem directory */
2023         LWSMPRO_CGI             = 3, /**< pass to CGI to handle */
2024         LWSMPRO_REDIR_HTTP      = 4, /**< redirect to http:// url */
2025         LWSMPRO_REDIR_HTTPS     = 5, /**< redirect to https:// url */
2026         LWSMPRO_CALLBACK        = 6, /**< hand by named protocol's callback */
2027 };
2028
2029 /** struct lws_http_mount
2030  *
2031  * arguments for mounting something in a vhost's url namespace
2032  */
2033 struct lws_http_mount {
2034         const struct lws_http_mount *mount_next;
2035         /**< pointer to next struct lws_http_mount */
2036         const char *mountpoint;
2037         /**< mountpoint in http pathspace, eg, "/" */
2038         const char *origin;
2039         /**< path to be mounted, eg, "/var/www/warmcat.com" */
2040         const char *def;
2041         /**< default target, eg, "index.html" */
2042         const char *protocol;
2043         /**<"protocol-name" to handle mount */
2044
2045         const struct lws_protocol_vhost_options *cgienv;
2046         /**< optional linked-list of cgi options.  These are created
2047          * as environment variables for the cgi process
2048          */
2049         const struct lws_protocol_vhost_options *extra_mimetypes;
2050         /**< optional linked-list of mimetype mappings */
2051         const struct lws_protocol_vhost_options *interpret;
2052         /**< optional linked-list of files to be interpreted */
2053
2054         int cgi_timeout;
2055         /**< seconds cgi is allowed to live, if cgi://mount type */
2056         int cache_max_age;
2057         /**< max-age for reuse of client cache of files, seconds */
2058         unsigned int auth_mask;
2059         /**< bits set here must be set for authorized client session */
2060
2061         unsigned int cache_reusable:1; /**< set if client cache may reuse this */
2062         unsigned int cache_revalidate:1; /**< set if client cache should revalidate on use */
2063         unsigned int cache_intermediaries:1; /**< set if intermediaries are allowed to cache */
2064
2065         unsigned char origin_protocol; /**< one of enum lws_mount_protocols */
2066         unsigned char mountpoint_len; /**< length of mountpoint string */
2067
2068         const char *basic_auth_login_file;
2069         /**<NULL, or filepath to use to check basic auth logins against */
2070
2071         /* Add new things just above here ---^
2072          * This is part of the ABI, don't needlessly break compatibility
2073          *
2074          * The below is to ensure later library versions with new
2075          * members added above will see 0 (default) even if the app
2076          * was not built against the newer headers.
2077          */
2078
2079         void *_unused[2]; /**< dummy */
2080 };
2081 ///@}
2082 ///@}
2083
2084 /*! \defgroup client
2085  * \ingroup lwsapi
2086  *
2087  * ##Client releated functions
2088  * */
2089 ///@{
2090
2091 /** enum lws_client_connect_ssl_connection_flags - flags that may be used
2092  * with struct lws_client_connect_info ssl_connection member to control if
2093  * and how SSL checks apply to the client connection being created
2094  */
2095
2096 enum lws_client_connect_ssl_connection_flags {
2097         LCCSCF_USE_SSL                          = (1 << 0),
2098         LCCSCF_ALLOW_SELFSIGNED                 = (1 << 1),
2099         LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK  = (1 << 2),
2100         LCCSCF_ALLOW_EXPIRED                    = (1 << 3)
2101 };
2102
2103 /** struct lws_client_connect_info - parameters to connect with when using
2104  *                                  lws_client_connect_via_info() */
2105
2106 struct lws_client_connect_info {
2107         struct lws_context *context;
2108         /**< lws context to create connection in */
2109         const char *address;
2110         /**< remote address to connect to */
2111         int port;
2112         /**< remote port to connect to */
2113         int ssl_connection;
2114         /**< nonzero for ssl */
2115         const char *path;
2116         /**< uri path */
2117         const char *host;
2118         /**< content of host header */
2119         const char *origin;
2120         /**< content of origin header */
2121         const char *protocol;
2122         /**< list of ws protocols we could accept */
2123         int ietf_version_or_minus_one;
2124         /**< deprecated: currently leave at 0 or -1 */
2125         void *userdata;
2126         /**< if non-NULL, use this as wsi user_data instead of malloc it */
2127         const void *client_exts;
2128         /**< UNUSED... provide in info.extensions at context creation time */
2129         const char *method;
2130         /**< if non-NULL, do this http method instead of ws[s] upgrade.
2131          * use "GET" to be a simple http client connection */
2132         struct lws *parent_wsi;
2133         /**< if another wsi is responsible for this connection, give it here.
2134          * this is used to make sure if the parent closes so do any
2135          * child connections first. */
2136         const char *uri_replace_from;
2137         /**< if non-NULL, when this string is found in URIs in
2138          * text/html content-encoding, it's replaced with uri_replace_to */
2139         const char *uri_replace_to;
2140         /**< see uri_replace_from */
2141         struct lws_vhost *vhost;
2142         /**< vhost to bind to (used to determine related SSL_CTX) */
2143         struct lws **pwsi;
2144         /**< if not NULL, store the new wsi here early in the connection
2145          * process.  Although we return the new wsi, the call to create the
2146          * client connection does progress the connection somewhat and may
2147          * meet an error that will result in the connection being scrubbed and
2148          * NULL returned.  While the wsi exists though, he may process a
2149          * callback like CLIENT_CONNECTION_ERROR with his wsi: this gives the
2150          * user callback a way to identify which wsi it is that faced the error
2151          * even before the new wsi is returned and even if ultimately no wsi
2152          * is returned.
2153          */
2154
2155         /* Add new things just above here ---^
2156          * This is part of the ABI, don't needlessly break compatibility
2157          *
2158          * The below is to ensure later library versions with new
2159          * members added above will see 0 (default) even if the app
2160          * was not built against the newer headers.
2161          */
2162
2163         void *_unused[4]; /**< dummy */
2164 };
2165
2166 /**
2167  * lws_client_connect_via_info() - Connect to another websocket server
2168  * \param ccinfo: pointer to lws_client_connect_info struct
2169  *
2170  *      This function creates a connection to a remote server using the
2171  *      information provided in ccinfo.
2172  */
2173 LWS_VISIBLE LWS_EXTERN struct lws *
2174 lws_client_connect_via_info(struct lws_client_connect_info * ccinfo);
2175
2176 /**
2177  * lws_client_connect() - Connect to another websocket server
2178  *              \deprecated DEPRECATED use lws_client_connect_via_info
2179  * \param clients:      Websocket context
2180  * \param address:      Remote server address, eg, "myserver.com"
2181  * \param port: Port to connect to on the remote server, eg, 80
2182  * \param ssl_connection:       0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
2183  *                      signed certs
2184  * \param path: Websocket path on server
2185  * \param host: Hostname on server
2186  * \param origin:       Socket origin name
2187  * \param protocol:     Comma-separated list of protocols being asked for from
2188  *              the server, or just one.  The server will pick the one it
2189  *              likes best.  If you don't want to specify a protocol, which is
2190  *              legal, use NULL here.
2191  * \param ietf_version_or_minus_one: -1 to ask to connect using the default, latest
2192  *              protocol supported, or the specific protocol ordinal
2193  *
2194  *      This function creates a connection to a remote server
2195  */
2196 /* deprecated, use lws_client_connect_via_info() */
2197 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
2198 lws_client_connect(struct lws_context *clients, const char *address,
2199                    int port, int ssl_connection, const char *path,
2200                    const char *host, const char *origin, const char *protocol,
2201                    int ietf_version_or_minus_one) LWS_WARN_DEPRECATED;
2202 /* deprecated, use lws_client_connect_via_info() */
2203 /**
2204  * lws_client_connect_extended() - Connect to another websocket server
2205  *                      \deprecated DEPRECATED use lws_client_connect_via_info
2206  * \param clients:      Websocket context
2207  * \param address:      Remote server address, eg, "myserver.com"
2208  * \param port: Port to connect to on the remote server, eg, 80
2209  * \param ssl_connection:       0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
2210  *                      signed certs
2211  * \param path: Websocket path on server
2212  * \param host: Hostname on server
2213  * \param origin:       Socket origin name
2214  * \param protocol:     Comma-separated list of protocols being asked for from
2215  *              the server, or just one.  The server will pick the one it
2216  *              likes best.
2217  * \param ietf_version_or_minus_one: -1 to ask to connect using the default, latest
2218  *              protocol supported, or the specific protocol ordinal
2219  * \param userdata: Pre-allocated user data
2220  *
2221  *      This function creates a connection to a remote server
2222  */
2223 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
2224 lws_client_connect_extended(struct lws_context *clients, const char *address,
2225                             int port, int ssl_connection, const char *path,
2226                             const char *host, const char *origin,
2227                             const char *protocol, int ietf_version_or_minus_one,
2228                             void *userdata) LWS_WARN_DEPRECATED;
2229
2230 /**
2231  * lws_init_vhost_client_ssl() - also enable client SSL on an existing vhost
2232  *
2233  * \param info: client ssl related info
2234  * \param vhost: which vhost to initialize client ssl operations on
2235  *
2236  * You only need to call this if you plan on using SSL client connections on
2237  * the vhost.  For non-SSL client connections, it's not necessary to call this.
2238  *
2239  * The following members of info are used during the call
2240  *
2241  *       - options must have LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT set,
2242  *           otherwise the call does nothing
2243  *       - provided_client_ssl_ctx must be NULL to get a generated client
2244  *           ssl context, otherwise you can pass a prepared one in by setting it
2245  *       - ssl_cipher_list may be NULL or set to the client valid cipher list
2246  *       - ssl_ca_filepath may be NULL or client cert filepath
2247  *       - ssl_cert_filepath may be NULL or client cert filepath
2248  *       - ssl_private_key_filepath may be NULL or client cert private key
2249  *
2250  * You must create your vhost explicitly if you want to use this, so you have
2251  * a pointer to the vhost.  Create the context first with the option flag
2252  * LWS_SERVER_OPTION_EXPLICIT_VHOSTS and then call lws_create_vhost() with
2253  * the same info struct.
2254  */
2255 LWS_VISIBLE LWS_EXTERN int
2256 lws_init_vhost_client_ssl(const struct lws_context_creation_info *info,
2257                           struct lws_vhost *vhost);
2258
2259 /**
2260  * lws_http_client_read() - consume waiting received http client data
2261  *
2262  * \param wsi: client connection
2263  * \param buf: pointer to buffer pointer - fill with pointer to your buffer
2264  * \param len: pointer to chunk length - fill with max length of buffer
2265  *
2266  * This is called when the user code is notified client http data has arrived.
2267  * The user code may choose to delay calling it to consume the data, for example
2268  * waiting until an onward connection is writeable.
2269  *
2270  * For non-chunked connections, up to len bytes of buf are filled with the
2271  * received content.  len is set to the actual amount filled before return.
2272  *
2273  * For chunked connections, the linear buffer content contains the chunking
2274  * headers and it cannot be passed in one lump.  Instead, this function will
2275  * call back LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ with in pointing to the
2276  * chunk start and len set to the chunk length.  There will be as many calls
2277  * as there are chunks or partial chunks in the buffer.
2278  */
2279 LWS_VISIBLE LWS_EXTERN int
2280 lws_http_client_read(struct lws *wsi, char **buf, int *len);
2281
2282 /**
2283  * lws_http_client_http_response() - get last HTTP response code
2284  *
2285  * \param wsi: client connection
2286  *
2287  * Returns the last server response code, eg, 200 for client http connections.
2288  */
2289 LWS_VISIBLE LWS_EXTERN unsigned int
2290 lws_http_client_http_response(struct lws *wsi);
2291
2292 LWS_VISIBLE LWS_EXTERN void
2293 lws_client_http_body_pending(struct lws *wsi, int something_left_to_send);
2294
2295 /**
2296  * lws_client_http_body_pending() - control if client connection neeeds to send body
2297  *
2298  * \param wsi: client connection
2299  * \param something_left_to_send: nonzero if need to send more body, 0 (default)
2300  *                              if nothing more to send
2301  *
2302  * If you will send payload data with your HTTP client connection, eg, for POST,
2303  * when you set the related http headers in
2304  * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER callback you should also call
2305  * this API with something_left_to_send nonzero, and call
2306  * lws_callback_on_writable(wsi);
2307  *
2308  * After sending the headers, lws will call your callback with
2309  * LWS_CALLBACK_CLIENT_HTTP_WRITEABLE reason when writable.  You can send the
2310  * next part of the http body payload, calling lws_callback_on_writable(wsi);
2311  * if there is more to come, or lws_client_http_body_pending(wsi, 0); to
2312  * let lws know the last part is sent and the connection can move on.
2313  */
2314
2315 ///@}
2316
2317 /** \defgroup service Built-in service loop entry
2318  *
2319  * ##Built-in service loop entry
2320  *
2321  * If you're not using libev / libuv, these apis are needed to enter the poll()
2322  * wait in lws and service any connections with pending events.
2323  */
2324 ///@{
2325
2326 /**
2327  * lws_service() - Service any pending websocket activity
2328  * \param context:      Websocket context
2329  * \param timeout_ms:   Timeout for poll; 0 means return immediately if nothing needed
2330  *              service otherwise block and service immediately, returning
2331  *              after the timeout if nothing needed service.
2332  *
2333  *      This function deals with any pending websocket traffic, for three
2334  *      kinds of event.  It handles these events on both server and client
2335  *      types of connection the same.
2336  *
2337  *      1) Accept new connections to our context's server
2338  *
2339  *      2) Call the receive callback for incoming frame data received by
2340  *          server or client connections.
2341  *
2342  *      You need to call this service function periodically to all the above
2343  *      functions to happen; if your application is single-threaded you can
2344  *      just call it in your main event loop.
2345  *
2346  *      Alternatively you can fork a new process that asynchronously handles
2347  *      calling this service in a loop.  In that case you are happy if this
2348  *      call blocks your thread until it needs to take care of something and
2349  *      would call it with a large nonzero timeout.  Your loop then takes no
2350  *      CPU while there is nothing happening.
2351  *
2352  *      If you are calling it in a single-threaded app, you don't want it to
2353  *      wait around blocking other things in your loop from happening, so you
2354  *      would call it with a timeout_ms of 0, so it returns immediately if
2355  *      nothing is pending, or as soon as it services whatever was pending.
2356  */
2357 LWS_VISIBLE LWS_EXTERN int
2358 lws_service(struct lws_context *context, int timeout_ms);
2359
2360 /**
2361  * lws_service() - Service any pending websocket activity
2362  *
2363  * \param context:      Websocket context
2364  * \param timeout_ms:   Timeout for poll; 0 means return immediately if nothing needed
2365  *              service otherwise block and service immediately, returning
2366  *              after the timeout if nothing needed service.
2367  *
2368  * Same as lws_service(), but for a specific thread service index.  Only needed
2369  * if you are spawning multiple service threads.
2370  */
2371 LWS_VISIBLE LWS_EXTERN int
2372 lws_service_tsi(struct lws_context *context, int timeout_ms, int tsi);
2373
2374 /**
2375  * lws_cancel_service_pt() - Cancel servicing of pending socket activity
2376  *                              on one thread
2377  * \param wsi:  Cancel service on the thread this wsi is serviced by
2378  *
2379  *      This function lets a call to lws_service() waiting for a timeout
2380  *      immediately return.
2381  *
2382  *      It works by creating a phony event and then swallowing it silently.
2383  *
2384  *      The reason it may be needed is when waiting in poll(), changes to
2385  *      the event masks are ignored by the OS until poll() is reentered.  This
2386  *      lets you halt the poll() wait and make the reentry happen immediately
2387  *      instead of having the wait out the rest of the poll timeout.
2388  */
2389 LWS_VISIBLE LWS_EXTERN void
2390 lws_cancel_service_pt(struct lws *wsi);
2391
2392 /**
2393  * lws_cancel_service() - Cancel wait for new pending socket activity
2394  * \param context:      Websocket context
2395  *
2396  *      This function let a call to lws_service() waiting for a timeout
2397  *      immediately return.
2398  *
2399  *      What it basically does is provide a fake event that will be swallowed,
2400  *      so the wait in poll() is ended.  That's useful because poll() doesn't
2401  *      attend to changes in POLLIN/OUT/ERR until it re-enters the wait.
2402  */
2403 LWS_VISIBLE LWS_EXTERN void
2404 lws_cancel_service(struct lws_context *context);
2405
2406 /**
2407  * lws_service_fd() - Service polled socket with something waiting
2408  * \param context:      Websocket context
2409  * \param pollfd:       The pollfd entry describing the socket fd and which events
2410  *              happened, or NULL to tell lws to do only timeout servicing.
2411  *
2412  * This function takes a pollfd that has POLLIN or POLLOUT activity and
2413  * services it according to the state of the associated
2414  * struct lws.
2415  *
2416  * The one call deals with all "service" that might happen on a socket
2417  * including listen accepts, http files as well as websocket protocol.
2418  *
2419  * If a pollfd says it has something, you can just pass it to
2420  * lws_service_fd() whether it is a socket handled by lws or not.
2421  * If it sees it is a lws socket, the traffic will be handled and
2422  * pollfd->revents will be zeroed now.
2423  *
2424  * If the socket is foreign to lws, it leaves revents alone.  So you can
2425  * see if you should service yourself by checking the pollfd revents
2426  * after letting lws try to service it.
2427  *
2428  * You should also call this with pollfd = NULL to just allow the
2429  * once-per-second global timeout checks; if less than a second since the last
2430  * check it returns immediately then.
2431  */
2432 LWS_VISIBLE LWS_EXTERN int
2433 lws_service_fd(struct lws_context *context, struct lws_pollfd *pollfd);
2434
2435 /**
2436  * lws_service_fd_tsi() - Service polled socket in specific service thread
2437  * \param context:      Websocket context
2438  * \param pollfd:       The pollfd entry describing the socket fd and which events
2439  *              happened.
2440  * \param tsi: thread service index
2441  *
2442  * Same as lws_service_fd() but used with multiple service threads
2443  */
2444 LWS_VISIBLE LWS_EXTERN int
2445 lws_service_fd_tsi(struct lws_context *context, struct lws_pollfd *pollfd,
2446                    int tsi);
2447
2448 /**
2449  * lws_service_adjust_timeout() - Check for any connection needing forced service
2450  * \param context:      Websocket context
2451  * \param timeout_ms:   The original poll timeout value.  You can just set this
2452  *                      to 1 if you don't really have a poll timeout.
2453  * \param tsi: thread service index
2454  *
2455  * Under some conditions connections may need service even though there is no
2456  * pending network action on them, this is "forced service".  For default
2457  * poll() and libuv / libev, the library takes care of calling this and
2458  * dealing with it for you.  But for external poll() integration, you need
2459  * access to the apis.
2460  *
2461  * If anybody needs "forced service", returned timeout is zero.  In that case,
2462  * you can call lws_service_tsi() with a timeout of -1 to only service
2463  * guys who need forced service.
2464  */
2465 LWS_VISIBLE LWS_EXTERN int
2466 lws_service_adjust_timeout(struct lws_context *context, int timeout_ms, int tsi);
2467
2468 /* Backwards compatibility */
2469 #define lws_plat_service_tsi lws_service_tsi
2470
2471 ///@}
2472
2473 /*! \defgroup http HTTP
2474
2475     Modules related to handling HTTP
2476 */
2477 //@{
2478
2479 /*! \defgroup httpft HTTP File transfer
2480  * \ingroup http
2481
2482     APIs for sending local files in response to HTTP requests
2483 */
2484 //@{
2485
2486 /**
2487  * lws_get_mimetype() - Determine mimetype to use from filename
2488  *
2489  * \param file:         filename
2490  * \param m:            NULL, or mount context
2491  *
2492  * This uses a canned list of known filetypes first, if no match and m is
2493  * non-NULL, then tries a list of per-mount file suffix to mimtype mappings.
2494  *
2495  * Returns either NULL or a pointer to the mimetype matching the file.
2496  */
2497 LWS_VISIBLE LWS_EXTERN const char *
2498 lws_get_mimetype(const char *file, const struct lws_http_mount *m);
2499
2500 /**
2501  * lws_serve_http_file() - Send a file back to the client using http
2502  * \param wsi:          Websocket instance (available from user callback)
2503  * \param file:         The file to issue over http
2504  * \param content_type: The http content type, eg, text/html
2505  * \param other_headers:        NULL or pointer to header string
2506  * \param other_headers_len:    length of the other headers if non-NULL
2507  *
2508  *      This function is intended to be called from the callback in response
2509  *      to http requests from the client.  It allows the callback to issue
2510  *      local files down the http link in a single step.
2511  *
2512  *      Returning <0 indicates error and the wsi should be closed.  Returning
2513  *      >0 indicates the file was completely sent and
2514  *      lws_http_transaction_completed() called on the wsi (and close if != 0)
2515  *      ==0 indicates the file transfer is started and needs more service later,
2516  *      the wsi should be left alone.
2517  */
2518 LWS_VISIBLE LWS_EXTERN int
2519 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
2520                     const char *other_headers, int other_headers_len);
2521 LWS_VISIBLE LWS_EXTERN int
2522 lws_serve_http_file_fragment(struct lws *wsi);
2523 //@}
2524
2525 /*! \defgroup html-chunked-substitution HTML Chunked Substitution
2526  * \ingroup http
2527  *
2528  * ##HTML chunked Substitution
2529  *
2530  * APIs for receiving chunks of text, replacing a set of variable names via
2531  * a callback, and then prepending and appending HTML chunked encoding
2532  * headers.
2533  */
2534 //@{
2535
2536 enum http_status {
2537         HTTP_STATUS_OK                                          = 200,
2538         HTTP_STATUS_NO_CONTENT                                  = 204,
2539         HTTP_STATUS_PARTIAL_CONTENT                             = 206,
2540
2541         HTTP_STATUS_MOVED_PERMANENTLY                           = 301,
2542         HTTP_STATUS_FOUND                                       = 302,
2543         HTTP_STATUS_SEE_OTHER                                   = 303,
2544
2545         HTTP_STATUS_BAD_REQUEST                                 = 400,
2546         HTTP_STATUS_UNAUTHORIZED,
2547         HTTP_STATUS_PAYMENT_REQUIRED,
2548         HTTP_STATUS_FORBIDDEN,
2549         HTTP_STATUS_NOT_FOUND,
2550         HTTP_STATUS_METHOD_NOT_ALLOWED,
2551         HTTP_STATUS_NOT_ACCEPTABLE,
2552         HTTP_STATUS_PROXY_AUTH_REQUIRED,
2553         HTTP_STATUS_REQUEST_TIMEOUT,
2554         HTTP_STATUS_CONFLICT,
2555         HTTP_STATUS_GONE,
2556         HTTP_STATUS_LENGTH_REQUIRED,
2557         HTTP_STATUS_PRECONDITION_FAILED,
2558         HTTP_STATUS_REQ_ENTITY_TOO_LARGE,
2559         HTTP_STATUS_REQ_URI_TOO_LONG,
2560         HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE,
2561         HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE,
2562         HTTP_STATUS_EXPECTATION_FAILED,
2563
2564         HTTP_STATUS_INTERNAL_SERVER_ERROR                       = 500,
2565         HTTP_STATUS_NOT_IMPLEMENTED,
2566         HTTP_STATUS_BAD_GATEWAY,
2567         HTTP_STATUS_SERVICE_UNAVAILABLE,
2568         HTTP_STATUS_GATEWAY_TIMEOUT,
2569         HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED,
2570 };
2571
2572 struct lws_process_html_args {
2573         char *p; /**< pointer to the buffer containing the data */
2574         int len; /**< length of the original data at p */
2575         int max_len; /**< maximum length we can grow the data to */
2576         int final; /**< set if this is the last chunk of the file */
2577 };
2578
2579 typedef const char *(*lws_process_html_state_cb)(void *data, int index);
2580
2581 struct lws_process_html_state {
2582         char *start; /**< pointer to start of match */
2583         char swallow[16]; /**< matched character buffer */
2584         int pos; /**< position in match */
2585         void *data; /**< opaque pointer */
2586         const char * const *vars; /**< list of variable names */
2587         int count_vars; /**< count of variable names */
2588
2589         lws_process_html_state_cb replace; /**< called on match to perform substitution */
2590 };
2591
2592 /*! lws_chunked_html_process() - generic chunked substitution
2593  * \param args: buffer to process using chunked encoding
2594  * \param s: current processing state
2595  */
2596 LWS_VISIBLE LWS_EXTERN int
2597 lws_chunked_html_process(struct lws_process_html_args *args,
2598                          struct lws_process_html_state *s);
2599 //@}
2600
2601 /** \defgroup HTTP-headers-read HTTP headers: read
2602  * \ingroup http
2603  *
2604  * ##HTTP header releated functions
2605  *
2606  *  In lws the client http headers are temporarily stored in a pool, only for the
2607  *  duration of the http part of the handshake.  It's because in most cases,
2608  *  the header content is ignored for the whole rest of the connection lifetime
2609  *  and would then just be taking up space needlessly.
2610  *
2611  *  During LWS_CALLBACK_HTTP when the URI path is delivered is the last time
2612  *  the http headers are still allocated, you can use these apis then to
2613  *  look at and copy out interesting header content (cookies, etc)
2614  *
2615  *  Notice that the header total length reported does not include a terminating
2616  *  '\0', however you must allocate for it when using the _copy apis.  So the
2617  *  length reported for a header containing "123" is 3, but you must provide
2618  *  a buffer of length 4 so that "123\0" may be copied into it, or the copy
2619  *  will fail with a nonzero return code.
2620  *
2621  *  In the special case of URL arguments, like ?x=1&y=2, the arguments are
2622  *  stored in a token named for the method, eg,  WSI_TOKEN_GET_URI if it
2623  *  was a GET or WSI_TOKEN_POST_URI if POST.  You can check the total
2624  *  length to confirm the method.
2625  *
2626  *  For URL arguments, each argument is stored urldecoded in a "fragment", so
2627  *  you can use the fragment-aware api lws_hdr_copy_fragment() to access each
2628  *  argument in turn: the fragments contain urldecoded strings like x=1 or y=2.
2629  *
2630  *  As a convenience, lws has an api that will find the fragment with a
2631  *  given name= part, lws_get_urlarg_by_name().
2632  */
2633 ///@{
2634
2635 /** struct lws_tokens
2636  * you need these to look at headers that have been parsed if using the
2637  * LWS_CALLBACK_FILTER_CONNECTION callback.  If a header from the enum
2638  * list below is absent, .token = NULL and token_len = 0.  Otherwise .token
2639  * points to .token_len chars containing that header content.
2640  */
2641 struct lws_tokens {
2642         char *token; /**< pointer to start of the token */
2643         int token_len; /**< length of the token's value */
2644 };
2645
2646 /* enum lws_token_indexes
2647  * these have to be kept in sync with lextable.h / minilex.c
2648  *
2649  * NOTE: These public enums are part of the abi.  If you want to add one,
2650  * add it at where specified so existing users are unaffected.
2651  */
2652 enum lws_token_indexes {
2653         WSI_TOKEN_GET_URI                                       =  0,
2654         WSI_TOKEN_POST_URI                                      =  1,
2655         WSI_TOKEN_OPTIONS_URI                                   =  2,
2656         WSI_TOKEN_HOST                                          =  3,
2657         WSI_TOKEN_CONNECTION                                    =  4,
2658         WSI_TOKEN_UPGRADE                                       =  5,
2659         WSI_TOKEN_ORIGIN                                        =  6,
2660         WSI_TOKEN_DRAFT                                         =  7,
2661         WSI_TOKEN_CHALLENGE                                     =  8,
2662         WSI_TOKEN_EXTENSIONS                                    =  9,
2663         WSI_TOKEN_KEY1                                          = 10,
2664         WSI_TOKEN_KEY2                                          = 11,
2665         WSI_TOKEN_PROTOCOL                                      = 12,
2666         WSI_TOKEN_ACCEPT                                        = 13,
2667         WSI_TOKEN_NONCE                                         = 14,
2668         WSI_TOKEN_HTTP                                          = 15,
2669         WSI_TOKEN_HTTP2_SETTINGS                                = 16,
2670         WSI_TOKEN_HTTP_ACCEPT                                   = 17,
2671         WSI_TOKEN_HTTP_AC_REQUEST_HEADERS                       = 18,
2672         WSI_TOKEN_HTTP_IF_MODIFIED_SINCE                        = 19,
2673         WSI_TOKEN_HTTP_IF_NONE_MATCH                            = 20,
2674         WSI_TOKEN_HTTP_ACCEPT_ENCODING                          = 21,
2675         WSI_TOKEN_HTTP_ACCEPT_LANGUAGE                          = 22,
2676         WSI_TOKEN_HTTP_PRAGMA                                   = 23,
2677         WSI_TOKEN_HTTP_CACHE_CONTROL                            = 24,
2678         WSI_TOKEN_HTTP_AUTHORIZATION                            = 25,
2679         WSI_TOKEN_HTTP_COOKIE                                   = 26,
2680         WSI_TOKEN_HTTP_CONTENT_LENGTH                           = 27,
2681         WSI_TOKEN_HTTP_CONTENT_TYPE                             = 28,
2682         WSI_TOKEN_HTTP_DATE                                     = 29,
2683         WSI_TOKEN_HTTP_RANGE                                    = 30,
2684         WSI_TOKEN_HTTP_REFERER                                  = 31,
2685         WSI_TOKEN_KEY                                           = 32,
2686         WSI_TOKEN_VERSION                                       = 33,
2687         WSI_TOKEN_SWORIGIN                                      = 34,
2688
2689         WSI_TOKEN_HTTP_COLON_AUTHORITY                          = 35,
2690         WSI_TOKEN_HTTP_COLON_METHOD                             = 36,
2691         WSI_TOKEN_HTTP_COLON_PATH                               = 37,
2692         WSI_TOKEN_HTTP_COLON_SCHEME                             = 38,
2693         WSI_TOKEN_HTTP_COLON_STATUS                             = 39,
2694
2695         WSI_TOKEN_HTTP_ACCEPT_CHARSET                           = 40,
2696         WSI_TOKEN_HTTP_ACCEPT_RANGES                            = 41,
2697         WSI_TOKEN_HTTP_ACCESS_CONTROL_ALLOW_ORIGIN              = 42,
2698         WSI_TOKEN_HTTP_AGE                                      = 43,
2699         WSI_TOKEN_HTTP_ALLOW                                    = 44,
2700         WSI_TOKEN_HTTP_CONTENT_DISPOSITION                      = 45,
2701         WSI_TOKEN_HTTP_CONTENT_ENCODING                         = 46,
2702         WSI_TOKEN_HTTP_CONTENT_LANGUAGE                         = 47,
2703         WSI_TOKEN_HTTP_CONTENT_LOCATION                         = 48,
2704         WSI_TOKEN_HTTP_CONTENT_RANGE                            = 49,
2705         WSI_TOKEN_HTTP_ETAG                                     = 50,
2706         WSI_TOKEN_HTTP_EXPECT                                   = 51,
2707         WSI_TOKEN_HTTP_EXPIRES                                  = 52,
2708         WSI_TOKEN_HTTP_FROM                                     = 53,
2709         WSI_TOKEN_HTTP_IF_MATCH                                 = 54,
2710         WSI_TOKEN_HTTP_IF_RANGE                                 = 55,
2711         WSI_TOKEN_HTTP_IF_UNMODIFIED_SINCE                      = 56,
2712         WSI_TOKEN_HTTP_LAST_MODIFIED                            = 57,
2713         WSI_TOKEN_HTTP_LINK                                     = 58,
2714         WSI_TOKEN_HTTP_LOCATION                                 = 59,
2715         WSI_TOKEN_HTTP_MAX_FORWARDS                             = 60,
2716         WSI_TOKEN_HTTP_PROXY_AUTHENTICATE                       = 61,
2717         WSI_TOKEN_HTTP_PROXY_AUTHORIZATION                      = 62,
2718         WSI_TOKEN_HTTP_REFRESH                                  = 63,
2719         WSI_TOKEN_HTTP_RETRY_AFTER                              = 64,
2720         WSI_TOKEN_HTTP_SERVER                                   = 65,
2721         WSI_TOKEN_HTTP_SET_COOKIE                               = 66,
2722         WSI_TOKEN_HTTP_STRICT_TRANSPORT_SECURITY                = 67,
2723         WSI_TOKEN_HTTP_TRANSFER_ENCODING                        = 68,
2724         WSI_TOKEN_HTTP_USER_AGENT                               = 69,
2725         WSI_TOKEN_HTTP_VARY                                     = 70,
2726         WSI_TOKEN_HTTP_VIA                                      = 71,
2727         WSI_TOKEN_HTTP_WWW_AUTHENTICATE                         = 72,
2728
2729         WSI_TOKEN_PATCH_URI                                     = 73,
2730         WSI_TOKEN_PUT_URI                                       = 74,
2731         WSI_TOKEN_DELETE_URI                                    = 75,
2732
2733         WSI_TOKEN_HTTP_URI_ARGS                                 = 76,
2734         WSI_TOKEN_PROXY                                         = 77,
2735         WSI_TOKEN_HTTP_X_REAL_IP                                = 78,
2736         WSI_TOKEN_HTTP1_0                                       = 79,
2737         WSI_TOKEN_X_FORWARDED_FOR                               = 80,
2738
2739         /****** add new things just above ---^ ******/
2740
2741         /* use token storage to stash these internally, not for
2742          * user use */
2743
2744         _WSI_TOKEN_CLIENT_SENT_PROTOCOLS,
2745         _WSI_TOKEN_CLIENT_PEER_ADDRESS,
2746         _WSI_TOKEN_CLIENT_URI,
2747         _WSI_TOKEN_CLIENT_HOST,
2748         _WSI_TOKEN_CLIENT_ORIGIN,
2749         _WSI_TOKEN_CLIENT_METHOD,
2750
2751         /* always last real token index*/
2752         WSI_TOKEN_COUNT,
2753
2754         /* parser state additions, no storage associated */
2755         WSI_TOKEN_NAME_PART,
2756         WSI_TOKEN_SKIPPING,
2757         WSI_TOKEN_SKIPPING_SAW_CR,
2758         WSI_PARSING_COMPLETE,
2759         WSI_INIT_TOKEN_MUXURL,
2760 };
2761
2762 struct lws_token_limits {
2763         unsigned short token_limit[WSI_TOKEN_COUNT]; /**< max chars for this token */
2764 };
2765
2766 /**
2767  * lws_token_to_string() - returns a textual representation of a hdr token index
2768  *
2769  * \param: token index
2770  */
2771 LWS_VISIBLE LWS_EXTERN const unsigned char *
2772 lws_token_to_string(enum lws_token_indexes token);
2773
2774
2775 /**
2776  * lws_hdr_total_length: report length of all fragments of a header totalled up
2777  *              The returned length does not include the space for a
2778  *              terminating '\0'
2779  *
2780  * \param wsi: websocket connection
2781  * \param h: which header index we are interested in
2782  */
2783 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2784 lws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h);
2785
2786 /**
2787  * lws_hdr_fragment_length: report length of a single fragment of a header
2788  *              The returned length does not include the space for a
2789  *              terminating '\0'
2790  *
2791  * \param wsi: websocket connection
2792  * \param h: which header index we are interested in
2793  * \param frag_idx: which fragment of h we want to get the length of
2794  */
2795 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2796 lws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx);
2797
2798 /**
2799  * lws_hdr_copy() - copy a single fragment of the given header to a buffer
2800  *              The buffer length len must include space for an additional
2801  *              terminating '\0', or it will fail returning -1.
2802  *
2803  * \param wsi: websocket connection
2804  * \param dest: destination buffer
2805  * \param len: length of destination buffer
2806  * \param h: which header index we are interested in
2807  *
2808  * copies the whole, aggregated header, even if it was delivered in
2809  * several actual headers piece by piece
2810  */
2811 LWS_VISIBLE LWS_EXTERN int
2812 lws_hdr_copy(struct lws *wsi, char *dest, int len, enum lws_token_indexes h);
2813
2814 /**
2815  * lws_hdr_copy_fragment() - copy a single fragment of the given header to a buffer
2816  *              The buffer length len must include space for an additional
2817  *              terminating '\0', or it will fail returning -1.
2818  *              If the requested fragment index is not present, it fails
2819  *              returning -1.
2820  *
2821  * \param wsi: websocket connection
2822  * \param dest: destination buffer
2823  * \param len: length of destination buffer
2824  * \param h: which header index we are interested in
2825  * \param frag_idx: which fragment of h we want to copy
2826  *
2827  * Normally this is only useful
2828  * to parse URI arguments like ?x=1&y=2, token index WSI_TOKEN_HTTP_URI_ARGS
2829  * fragment 0 will contain "x=1" and fragment 1 "y=2"
2830  */
2831 LWS_VISIBLE LWS_EXTERN int
2832 lws_hdr_copy_fragment(struct lws *wsi, char *dest, int len,
2833                       enum lws_token_indexes h, int frag_idx);
2834
2835 /**
2836  * lws_get_urlarg_by_name() - return pointer to arg value if present
2837  * \param wsi: the connection to check
2838  * \param name: the arg name, like "token="
2839  * \param buf: the buffer to receive the urlarg (including the name= part)
2840  * \param len: the length of the buffer to receive the urlarg
2841  *
2842  *     Returns NULL if not found or a pointer inside buf to just after the
2843  *     name= part.
2844  */
2845 LWS_VISIBLE LWS_EXTERN const char *
2846 lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len);
2847 ///@}
2848
2849 /*! \defgroup HTTP-headers-create HTTP headers: create
2850  *
2851  * ## HTTP headers: Create
2852  *
2853  * These apis allow you to create HTTP response headers in a way compatible with
2854  * both HTTP/1.x and HTTP/2.
2855  *
2856  * They each append to a buffer taking care about the buffer end, which is
2857  * passed in as a pointer.  When data is written to the buffer, the current
2858  * position p is updated accordingly.
2859  *
2860  * All of these apis are LWS_WARN_UNUSED_RESULT as they can run out of space
2861  * and fail with nonzero return.
2862  */
2863 ///@{
2864 /**
2865  * lws_add_http_header_status() - add the HTTP response status code
2866  *
2867  * \param wsi: the connection to check
2868  * \param code: an HTTP code like 200, 404 etc (see enum http_status)
2869  * \param p: pointer to current position in buffer pointer
2870  * \param end: pointer to end of buffer
2871  *
2872  * Adds the initial response code, so should be called first
2873  */
2874 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2875 lws_add_http_header_status(struct lws *wsi,
2876                            unsigned int code, unsigned char **p,
2877                            unsigned char *end);
2878 /**
2879  * lws_add_http_header_by_name() - append named header and value
2880  *
2881  * \param wsi: the connection to check
2882  * \param name: the hdr name, like "my-header"
2883  * \param value: the value after the = for this header
2884  * \param length: the length of the value
2885  * \param p: pointer to current position in buffer pointer
2886  * \param end: pointer to end of buffer
2887  *
2888  * Appends name: value to the headers
2889  */
2890 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2891 lws_add_http_header_by_name(struct lws *wsi, const unsigned char *name,
2892                             const unsigned char *value, int length,
2893                             unsigned char **p, unsigned char *end);
2894 /**
2895  * lws_add_http_header_by_token() - append given header and value
2896  *
2897  * \param wsi: the connection to check
2898  * \param token: the token index for the hdr
2899  * \param value: the value after the = for this header
2900  * \param length: the length of the value
2901  * \param p: pointer to current position in buffer pointer
2902  * \param end: pointer to end of buffer
2903  *
2904  * Appends name=value to the headers, but is able to take advantage of better
2905  * HTTP/2 coding mechanisms where possible.
2906  */
2907 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2908 lws_add_http_header_by_token(struct lws *wsi, enum lws_token_indexes token,
2909                              const unsigned char *value, int length,
2910                              unsigned char **p, unsigned char *end);
2911 /**
2912  * lws_add_http_header_by_name() - append content-length helper
2913  *
2914  * \param wsi: the connection to check
2915  * \param content_length: the content length to use
2916  * \param p: pointer to current position in buffer pointer
2917  * \param end: pointer to end of buffer
2918  *
2919  * Appends content-length: content_length to the headers
2920  */
2921 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2922 lws_add_http_header_content_length(struct lws *wsi,
2923                                    unsigned long content_length,
2924                                    unsigned char **p, unsigned char *end);
2925 /**
2926  * lws_finalize_http_header() - terminate header block
2927  *
2928  * \param wsi: the connection to check
2929  * \param p: pointer to current position in buffer pointer
2930  * \param end: pointer to end of buffer
2931  *
2932  * Indicates no more headers will be added
2933  */
2934 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
2935 lws_finalize_http_header(struct lws *wsi, unsigned char **p,
2936                          unsigned char *end);
2937 ///@}
2938
2939 /** \defgroup form-parsing  Form Parsing
2940  * \ingroup http
2941  * ##POSTed form parsing functions
2942  *
2943  * These lws_spa (stateful post arguments) apis let you parse and urldecode
2944  * POSTed form arguments, both using simple urlencoded and multipart transfer
2945  * encoding.
2946  *
2947  * It's capable of handling file uploads as well a named input parsing,
2948  * and the apis are the same for both form upload styles.
2949  *
2950  * You feed it a list of parameter names and it creates pointers to the
2951  * urldecoded arguments: file upload parameters pass the file data in chunks to
2952  * a user-supplied callback as they come.
2953  *
2954  * Since it's stateful, it handles the incoming data needing more than one
2955  * POST_BODY callback and has no limit on uploaded file size.
2956  */
2957 ///@{
2958
2959 /** enum lws_spa_fileupload_states */
2960 enum lws_spa_fileupload_states {
2961         LWS_UFS_CONTENT,
2962         /**< a chunk of file content has arrived */
2963         LWS_UFS_FINAL_CONTENT,
2964         /**< the last chunk (possibly zero length) of file content has arrived */
2965         LWS_UFS_OPEN
2966         /**< a new file is starting to arrive */
2967 };
2968
2969 /**
2970  * lws_spa_fileupload_cb() - callback to receive file upload data
2971  *
2972  * \param data: opt_data pointer set in lws_spa_create
2973  * \param name: name of the form field being uploaded
2974  * \param filename: original filename from client
2975  * \param buf: start of data to receive
2976  * \param len: length of data to receive
2977  * \param state: information about how this call relates to file
2978  *
2979  * Notice name and filename shouldn't be trusted, as they are passed from
2980  * HTTP provided by the client.
2981  */
2982 typedef int (*lws_spa_fileupload_cb)(void *data, const char *name,
2983                         const char *filename, char *buf, int len,
2984                         enum lws_spa_fileupload_states state);
2985
2986 /** struct lws_spa - opaque urldecode parser capable of handling multipart
2987  *                      and file uploads */
2988 struct lws_spa;
2989
2990 /**
2991  * lws_spa_create() - create urldecode parser
2992  *
2993  * \param wsi: lws connection (used to find Content Type)
2994  * \param param_names: array of form parameter names, like "username"
2995  * \param count_params: count of param_names
2996  * \param max_storage: total amount of form parameter values we can store
2997  * \param opt_cb: NULL, or callback to receive file upload data.
2998  * \param opt_data: NULL, or user pointer provided to opt_cb.
2999  *
3000  * Creates a urldecode parser and initializes it.
3001  *
3002  * opt_cb can be NULL if you just want normal name=value parsing, however
3003  * if one or more entries in your form are bulk data (file transfer), you
3004  * can provide this callback and filter on the name callback parameter to
3005  * treat that urldecoded data separately.  The callback should return -1
3006  * in case of fatal error, and 0 if OK.
3007  */
3008 LWS_VISIBLE LWS_EXTERN struct lws_spa *
3009 lws_spa_create(struct lws *wsi, const char * const *param_names,
3010                int count_params, int max_storage, lws_spa_fileupload_cb opt_cb,
3011                void *opt_data);
3012
3013 /**
3014  * lws_spa_process() - parses a chunk of input data
3015  *
3016  * \param spa: the parser object previously created
3017  * \param in: incoming, urlencoded data
3018  * \param len: count of bytes valid at \param in
3019  */
3020 LWS_VISIBLE LWS_EXTERN int
3021 lws_spa_process(struct lws_spa *spa, const char *in, int len);
3022
3023 /**
3024  * lws_spa_finalize() - indicate incoming data completed
3025  *
3026  * \param spa: the parser object previously created
3027  */
3028 LWS_VISIBLE LWS_EXTERN int
3029 lws_spa_finalize(struct lws_spa *spa);
3030
3031 /**
3032  * lws_spa_get_length() - return length of parameter value
3033  *
3034  * \param spa: the parser object previously created
3035  * \param n: parameter ordinal to return length of value for
3036  */
3037 LWS_VISIBLE LWS_EXTERN int
3038 lws_spa_get_length(struct lws_spa *spa, int n);
3039
3040 /**
3041  * lws_spa_get_string() - return pointer to parameter value
3042  * \param spa: the parser object previously created
3043  * \param n: parameter ordinal to return pointer to value for
3044  */
3045 LWS_VISIBLE LWS_EXTERN const char *
3046 lws_spa_get_string(struct lws_spa *spa, int n);
3047
3048 /**
3049  * lws_spa_destroy() - destroy parser object
3050  *
3051  * \param spa: the parser object previously created
3052  */
3053 LWS_VISIBLE LWS_EXTERN int
3054 lws_spa_destroy(struct lws_spa *spa);
3055 ///@}
3056
3057 /*! \defgroup urlendec Urlencode and Urldecode
3058  * \ingroup http
3059  *
3060  * ##HTML chunked Substitution
3061  *
3062  * APIs for receiving chunks of text, replacing a set of variable names via
3063  * a callback, and then prepending and appending HTML chunked encoding
3064  * headers.
3065  */
3066 //@{
3067
3068 /**
3069  * lws_urlencode() - like strncpy but with urlencoding
3070  *
3071  * \param escaped: output buffer
3072  * \param string: input buffer ('/0' terminated)
3073  * \param len: output buffer max length
3074  *
3075  * Because urlencoding expands the output string, it's not
3076  * possible to do it in-place, ie, with escaped == string
3077  */
3078 LWS_VISIBLE LWS_EXTERN const char *
3079 lws_urlencode(char *escaped, const char *string, int len);
3080
3081 /*
3082  * URLDECODE 1 / 2
3083  *
3084  * This simple urldecode only operates until the first '\0' and requires the
3085  * data to exist all at once
3086  */
3087 /**
3088  * lws_urldecode() - like strncpy but with urldecoding
3089  *
3090  * \param string: output buffer
3091  * \param escaped: input buffer ('\0' terminated)
3092  * \param len: output buffer max length
3093  *
3094  * This is only useful for '\0' terminated strings
3095  *
3096  * Since urldecoding only shrinks the output string, it is possible to
3097  * do it in-place, ie, string == escaped
3098  */
3099 LWS_VISIBLE LWS_EXTERN int
3100 lws_urldecode(char *string, const char *escaped, int len);
3101 ///@}
3102 /**
3103  * lws_return_http_status() - Return simple http status
3104  * \param wsi:          Websocket instance (available from user callback)
3105  * \param code:         Status index, eg, 404
3106  * \param html_body:            User-readable HTML description < 1KB, or NULL
3107  *
3108  *      Helper to report HTTP errors back to the client cleanly and
3109  *      consistently
3110  */
3111 LWS_VISIBLE LWS_EXTERN int
3112 lws_return_http_status(struct lws *wsi, unsigned int code,
3113                        const char *html_body);
3114
3115 /**
3116  * lws_http_redirect() - write http redirect into buffer
3117  *
3118  * \param wsi:  websocket connection
3119  * \param code: HTTP response code (eg, 301)
3120  * \param loc:  where to redirect to
3121  * \param len:  length of loc
3122  * \param p:    pointer current position in buffer (updated as we write)
3123  * \param end:  pointer to end of buffer
3124  */
3125 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3126 lws_http_redirect(struct lws *wsi, int code, const unsigned char *loc, int len,
3127                   unsigned char **p, unsigned char *end);
3128
3129 /**
3130  * lws_http_transaction_completed() - wait for new http transaction or close
3131  * \param wsi:  websocket connection
3132  *
3133  *      Returns 1 if the HTTP connection must close now
3134  *      Returns 0 and resets connection to wait for new HTTP header /
3135  *        transaction if possible
3136  */
3137 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3138 lws_http_transaction_completed(struct lws *wsi);
3139 ///@}
3140
3141 /*! \defgroup pur Sanitize / purify SQL and JSON helpers
3142  *
3143  * ##Sanitize / purify SQL and JSON helpers
3144  *
3145  * APIs for escaping untrusted JSON and SQL safely before use
3146  */
3147 //@{
3148
3149 /**
3150  * lws_sql_purify() - like strncpy but with escaping for sql quotes
3151  *
3152  * \param escaped: output buffer
3153  * \param string: input buffer ('/0' terminated)
3154  * \param len: output buffer max length
3155  *
3156  * Because escaping expands the output string, it's not
3157  * possible to do it in-place, ie, with escaped == string
3158  */
3159 LWS_VISIBLE LWS_EXTERN const char *
3160 lws_sql_purify(char *escaped, const char *string, int len);
3161
3162 /**
3163  * lws_json_purify() - like strncpy but with escaping for json chars
3164  *
3165  * \param escaped: output buffer
3166  * \param string: input buffer ('/0' terminated)
3167  * \param len: output buffer max length
3168  *
3169  * Because escaping expands the output string, it's not
3170  * possible to do it in-place, ie, with escaped == string
3171  */
3172 LWS_VISIBLE LWS_EXTERN const char *
3173 lws_json_purify(char *escaped, const char *string, int len);
3174 ///@}
3175
3176 /*! \defgroup ev libev helpers
3177  *
3178  * ##libev helpers
3179  *
3180  * APIs specific to libev event loop itegration
3181  */
3182 ///@{
3183
3184 #ifdef LWS_USE_LIBEV
3185 typedef void (lws_ev_signal_cb_t)(EV_P_ struct ev_signal *w, int revents);
3186
3187 LWS_VISIBLE LWS_EXTERN int
3188 lws_ev_sigint_cfg(struct lws_context *context, int use_ev_sigint,
3189                   lws_ev_signal_cb_t *cb);
3190
3191 LWS_VISIBLE LWS_EXTERN int
3192 lws_ev_initloop(struct lws_context *context, struct ev_loop *loop, int tsi);
3193
3194 LWS_VISIBLE LWS_EXTERN void
3195 lws_ev_sigint_cb(struct ev_loop *loop, struct ev_signal *watcher, int revents);
3196 #endif /* LWS_USE_LIBEV */
3197
3198 ///@}
3199
3200 /*! \defgroup uv libuv helpers
3201  *
3202  * ##libuv helpers
3203  *
3204  * APIs specific to libuv event loop itegration
3205  */
3206 ///@{
3207 #ifdef LWS_USE_LIBUV
3208 LWS_VISIBLE LWS_EXTERN int
3209 lws_uv_sigint_cfg(struct lws_context *context, int use_uv_sigint,
3210                   uv_signal_cb cb);
3211
3212 LWS_VISIBLE LWS_EXTERN void
3213 lws_libuv_run(const struct lws_context *context, int tsi);
3214
3215 LWS_VISIBLE LWS_EXTERN void
3216 lws_libuv_stop(struct lws_context *context);
3217
3218 LWS_VISIBLE LWS_EXTERN void
3219 lws_libuv_stop_without_kill(const struct lws_context *context, int tsi);
3220
3221 LWS_VISIBLE LWS_EXTERN int
3222 lws_uv_initloop(struct lws_context *context, uv_loop_t *loop, int tsi);
3223
3224 LWS_VISIBLE LWS_EXTERN uv_loop_t *
3225 lws_uv_getloop(struct lws_context *context, int tsi);
3226
3227 LWS_VISIBLE LWS_EXTERN void
3228 lws_uv_sigint_cb(uv_signal_t *watcher, int signum);
3229 #endif /* LWS_USE_LIBUV */
3230 ///@}
3231
3232 /*! \defgroup timeout Connection timeouts
3233
3234     APIs related to setting connection timeouts
3235 */
3236 //@{
3237
3238 /*
3239  * NOTE: These public enums are part of the abi.  If you want to add one,
3240  * add it at where specified so existing users are unaffected.
3241  */
3242 enum pending_timeout {
3243         NO_PENDING_TIMEOUT                                      =  0,
3244         PENDING_TIMEOUT_AWAITING_PROXY_RESPONSE                 =  1,
3245         PENDING_TIMEOUT_AWAITING_CONNECT_RESPONSE               =  2,
3246         PENDING_TIMEOUT_ESTABLISH_WITH_SERVER                   =  3,
3247         PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE                =  4,
3248         PENDING_TIMEOUT_AWAITING_PING                           =  5,
3249         PENDING_TIMEOUT_CLOSE_ACK                               =  6,
3250         PENDING_TIMEOUT_AWAITING_EXTENSION_CONNECT_RESPONSE     =  7,
3251         PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE                   =  8,
3252         PENDING_TIMEOUT_SSL_ACCEPT                              =  9,
3253         PENDING_TIMEOUT_HTTP_CONTENT                            = 10,
3254         PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND                 = 11,
3255         PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE                  = 12,
3256         PENDING_TIMEOUT_SHUTDOWN_FLUSH                          = 13,
3257         PENDING_TIMEOUT_CGI                                     = 14,
3258         PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE                     = 15,
3259         PENDING_TIMEOUT_WS_PONG_CHECK_SEND_PING                 = 16,
3260         PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG                  = 17,
3261         PENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD                    = 18,
3262
3263         /****** add new things just above ---^ ******/
3264 };
3265
3266 /**
3267  * lws_set_timeout() - marks the wsi as subject to a timeout
3268  *
3269  * You will not need this unless you are doing something special
3270  *
3271  * \param wsi:  Websocket connection instance
3272  * \param reason:       timeout reason
3273  * \param secs: how many seconds
3274  */
3275 LWS_VISIBLE LWS_EXTERN void
3276 lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs);
3277 ///@}
3278
3279 /*! \defgroup sending-data Sending data
3280
3281     APIs related to writing data on a connection
3282 */
3283 //@{
3284 #if !defined(LWS_SIZEOFPTR)
3285 #define LWS_SIZEOFPTR (sizeof (void *))
3286 #endif
3287 #if !defined(u_int64_t)
3288 #define u_int64_t unsigned long long
3289 #endif
3290
3291 #if defined(__x86_64__)
3292 #define _LWS_PAD_SIZE 16        /* Intel recommended for best performance */
3293 #else
3294 #define _LWS_PAD_SIZE LWS_SIZEOFPTR   /* Size of a pointer on the target arch */
3295 #endif
3296 #define _LWS_PAD(n) (((n) % _LWS_PAD_SIZE) ? \
3297                 ((n) + (_LWS_PAD_SIZE - ((n) % _LWS_PAD_SIZE))) : (n))
3298 #define LWS_PRE _LWS_PAD(4 + 10)
3299 /* used prior to 1.7 and retained for backward compatibility */
3300 #define LWS_SEND_BUFFER_PRE_PADDING LWS_PRE
3301 #define LWS_SEND_BUFFER_POST_PADDING 0
3302
3303 /*
3304  * NOTE: These public enums are part of the abi.  If you want to add one,
3305  * add it at where specified so existing users are unaffected.
3306  */
3307 enum lws_write_protocol {
3308         LWS_WRITE_TEXT                                          = 0,
3309         /**< Send a ws TEXT message,the pointer must have LWS_PRE valid
3310          * memory behind it.  The receiver expects only valid utf-8 in the
3311          * payload */
3312         LWS_WRITE_BINARY                                        = 1,
3313         /**< Send a ws BINARY message, the pointer must have LWS_PRE valid
3314          * memory behind it.  Any sequence of bytes is valid */
3315         LWS_WRITE_CONTINUATION                                  = 2,
3316         /**< Continue a previous ws message, the pointer must have LWS_PRE valid
3317          * memory behind it */
3318         LWS_WRITE_HTTP                                          = 3,
3319         /**< Send HTTP content */
3320
3321         /* LWS_WRITE_CLOSE is handled by lws_close_reason() */
3322         LWS_WRITE_PING                                          = 5,
3323         LWS_WRITE_PONG                                          = 6,
3324
3325         /* Same as write_http but we know this write ends the transaction */
3326         LWS_WRITE_HTTP_FINAL                                    = 7,
3327
3328         /* HTTP2 */
3329
3330         LWS_WRITE_HTTP_HEADERS                                  = 8,
3331         /**< Send http headers (http2 encodes this payload and LWS_WRITE_HTTP
3332          * payload differently, http 1.x links also handle this correctly. so
3333          * to be compatible with both in the future,header response part should
3334          * be sent using this regardless of http version expected)
3335          */
3336
3337         /****** add new things just above ---^ ******/
3338
3339         /* flags */
3340
3341         LWS_WRITE_NO_FIN = 0x40,
3342         /**< This part of the message is not the end of the message */
3343
3344         LWS_WRITE_CLIENT_IGNORE_XOR_MASK = 0x80
3345         /**< client packet payload goes out on wire unmunged
3346          * only useful for security tests since normal servers cannot
3347          * decode the content if used */
3348 };
3349
3350
3351 /**
3352  * lws_write() - Apply protocol then write data to client
3353  * \param wsi:  Websocket instance (available from user callback)
3354  * \param buf:  The data to send.  For data being sent on a websocket
3355  *              connection (ie, not default http), this buffer MUST have
3356  *              LWS_PRE bytes valid BEFORE the pointer.
3357  *              This is so the protocol header data can be added in-situ.
3358  * \param len:  Count of the data bytes in the payload starting from buf
3359  * \param protocol:     Use LWS_WRITE_HTTP to reply to an http connection, and one
3360  *              of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
3361  *              data on a websockets connection.  Remember to allow the extra
3362  *              bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
3363  *              are used.
3364  *
3365  *      This function provides the way to issue data back to the client
3366  *      for both http and websocket protocols.
3367  *
3368  * IMPORTANT NOTICE!
3369  *
3370  * When sending with websocket protocol
3371  *
3372  * LWS_WRITE_TEXT,
3373  * LWS_WRITE_BINARY,
3374  * LWS_WRITE_CONTINUATION,
3375  * LWS_WRITE_PING,
3376  * LWS_WRITE_PONG
3377  *
3378  * the send buffer has to have LWS_PRE bytes valid BEFORE
3379  * the buffer pointer you pass to lws_write().
3380  *
3381  * This allows us to add protocol info before and after the data, and send as
3382  * one packet on the network without payload copying, for maximum efficiency.
3383  *
3384  * So for example you need this kind of code to use lws_write with a
3385  * 128-byte payload
3386  *
3387  *   char buf[LWS_PRE + 128];
3388  *
3389  *   // fill your part of the buffer... for example here it's all zeros
3390  *   memset(&buf[LWS_PRE], 0, 128);
3391  *
3392  *   lws_write(wsi, &buf[LWS_PRE], 128, LWS_WRITE_TEXT);
3393  *
3394  * When sending HTTP, with
3395  *
3396  * LWS_WRITE_HTTP,
3397  * LWS_WRITE_HTTP_HEADERS
3398  * LWS_WRITE_HTTP_FINAL
3399  *
3400  * there is no protocol data prepended, and don't need to take care about the
3401  * LWS_PRE bytes valid before the buffer pointer.
3402  *
3403  * LWS_PRE is at least the frame nonce + 2 header + 8 length
3404  * LWS_SEND_BUFFER_POST_PADDING is deprecated, it's now 0 and can be left off.
3405  * The example apps no longer use it.
3406  *
3407  * Pad LWS_PRE to the CPU word size, so that word references
3408  * to the address immediately after the padding won't cause an unaligned access
3409  * error. Sometimes for performance reasons the recommended padding is even
3410  * larger than sizeof(void *).
3411  *
3412  *      In the case of sending using websocket protocol, be sure to allocate
3413  *      valid storage before and after buf as explained above.  This scheme
3414  *      allows maximum efficiency of sending data and protocol in a single
3415  *      packet while not burdening the user code with any protocol knowledge.
3416  *
3417  *      Return may be -1 for a fatal error needing connection close, or the
3418  *      number of bytes sent.
3419  *
3420  * Truncated Writes
3421  * ================
3422  *
3423  * The OS may not accept everything you asked to write on the connection.
3424  *
3425  * Posix defines POLLOUT indication from poll() to show that the connection
3426  * will accept more write data, but it doesn't specifiy how much.  It may just
3427  * accept one byte of whatever you wanted to send.
3428  *
3429  * LWS will buffer the remainder automatically, and send it out autonomously.
3430  *
3431  * During that time, WRITABLE callbacks will be suppressed.
3432  *
3433  * This is to handle corner cases where unexpectedly the OS refuses what we
3434  * usually expect it to accept.  You should try to send in chunks that are
3435  * almost always accepted in order to avoid the inefficiency of the buffering.
3436  */
3437 LWS_VISIBLE LWS_EXTERN int
3438 lws_write(struct lws *wsi, unsigned char *buf, size_t len,
3439           enum lws_write_protocol protocol);
3440
3441 /* helper for case where buffer may be const */
3442 #define lws_write_http(wsi, buf, len) \
3443         lws_write(wsi, (unsigned char *)(buf), len, LWS_WRITE_HTTP)
3444 ///@}
3445
3446 /** \defgroup callback-when-writeable Callback when writeable
3447  *
3448  * ##Callback When Writeable
3449  *
3450  * lws can only write data on a connection when it is able to accept more
3451  * data without blocking.
3452  *
3453  * So a basic requirement is we should only use the lws_write() apis when the
3454  * connection we want to write on says that he can accept more data.
3455  *
3456  * When lws cannot complete your send at the time, it will buffer the data
3457  * and send it in the background, suppressing any further WRITEABLE callbacks
3458  * on that connection until it completes.  So it is important to write new
3459  * things in a new writeable callback.
3460  *
3461  * These apis reflect the various ways we can indicate we would like to be
3462  * called back when one or more connections is writeable.
3463  */
3464 ///@{
3465
3466 /**
3467  * lws_callback_on_writable() - Request a callback when this socket
3468  *                                       becomes able to be written to without
3469  *                                       blocking
3470  *
3471  * \param wsi:  Websocket connection instance to get callback for
3472  *
3473  * - Which:  only this wsi
3474  * - When:   when the individual connection becomes writeable
3475  * - What: LWS_CALLBACK_*_WRITEABLE
3476  */
3477 LWS_VISIBLE LWS_EXTERN int
3478 lws_callback_on_writable(struct lws *wsi);
3479
3480 /**
3481  * lws_callback_on_writable_all_protocol() - Request a callback for all
3482  *                      connections on same vhost using the given protocol when it
3483  *                      becomes possible to write to each socket without
3484  *                      blocking in turn.
3485  *
3486  * \param context:      lws_context
3487  * \param protocol:     Protocol whose connections will get callbacks
3488  *
3489  * - Which:  connections using this protocol on ANY VHOST
3490  * - When:   when the individual connection becomes writeable
3491  * - What: LWS_CALLBACK_*_WRITEABLE
3492  */
3493 LWS_VISIBLE LWS_EXTERN int
3494 lws_callback_on_writable_all_protocol(const struct lws_context *context,
3495                                       const struct lws_protocols *protocol);
3496
3497 /**
3498  * lws_callback_on_writable_all_protocol_vhost() - Request a callback for
3499  *                      all connections using the given protocol when it
3500  *                      becomes possible to write to each socket without
3501  *                      blocking in turn.
3502  *
3503  * \param vhost:        Only consider connections on this lws_vhost
3504  * \param protocol:     Protocol whose connections will get callbacks
3505  *
3506  * - Which:  connections using this protocol on GIVEN VHOST ONLY
3507  * - When:   when the individual connection becomes writeable
3508  * - What: LWS_CALLBACK_*_WRITEABLE
3509  */
3510 LWS_VISIBLE LWS_EXTERN int
3511 lws_callback_on_writable_all_protocol_vhost(const struct lws_vhost *vhost,
3512                                       const struct lws_protocols *protocol);
3513
3514 /**
3515  * lws_callback_all_protocol() - Callback all connections using
3516  *                              the given protocol with the given reason
3517  *
3518  * \param context:      lws_context
3519  * \param protocol:     Protocol whose connections will get callbacks
3520  * \param reason:       Callback reason index
3521  *
3522  * - Which:  connections using this protocol on ALL VHOSTS
3523  * - When:   when the individual connection becomes writeable
3524  * - What:   reason
3525  */
3526 LWS_VISIBLE LWS_EXTERN int
3527 lws_callback_all_protocol(struct lws_context *context,
3528                           const struct lws_protocols *protocol, int reason);
3529
3530 /**
3531  * lws_callback_all_protocol_vhost() - Callback all connections using
3532  *                              the given protocol with the given reason
3533  *
3534  * \param vh:           Vhost whose connections will get callbacks
3535  * \param protocol:     Which protocol to match
3536  * \param reason:       Callback reason index
3537  *
3538  * - Which:  connections using this protocol on GIVEN VHOST ONLY
3539  * - When:   now
3540  * - What:   reason
3541  */
3542 LWS_VISIBLE LWS_EXTERN int
3543 lws_callback_all_protocol_vhost(struct lws_vhost *vh,
3544                           const struct lws_protocols *protocol, int reason);
3545
3546 /**
3547  * lws_callback_vhost_protocols() - Callback all protocols enabled on a vhost
3548  *                                      with the given reason
3549  *
3550  * \param wsi:  wsi whose vhost will get callbacks
3551  * \param reason:       Callback reason index
3552  * \param in:           in argument to callback
3553  * \param len:  len argument to callback
3554  *
3555  * - Which:  connections using this protocol on same VHOST as wsi ONLY
3556  * - When:   now
3557  * - What:   reason
3558  */
3559 LWS_VISIBLE LWS_EXTERN int
3560 lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len);
3561
3562 LWS_VISIBLE LWS_EXTERN int
3563 lws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason,
3564                     void *user, void *in, size_t len);
3565
3566 /**
3567  * lws_get_socket_fd() - returns the socket file descriptor
3568  *
3569  * You will not need this unless you are doing something special
3570  *
3571  * \param wsi:  Websocket connection instance
3572  */
3573 LWS_VISIBLE LWS_EXTERN int
3574 lws_get_socket_fd(struct lws *wsi);
3575
3576 /**
3577  * lws_get_peer_write_allowance() - get the amount of data writeable to peer
3578  *                                      if known
3579  *
3580  * \param wsi:  Websocket connection instance
3581  *
3582  * if the protocol does not have any guidance, returns -1.  Currently only
3583  * http2 connections get send window information from this API.  But your code
3584  * should use it so it can work properly with any protocol.
3585  *
3586  * If nonzero return is the amount of payload data the peer or intermediary has
3587  * reported it has buffer space for.  That has NO relationship with the amount
3588  * of buffer space your OS can accept on this connection for a write action.
3589  *
3590  * This number represents the maximum you could send to the peer or intermediary
3591  * on this connection right now without the protocol complaining.
3592  *
3593  * lws manages accounting for send window updates and payload writes
3594  * automatically, so this number reflects the situation at the peer or
3595  * intermediary dynamically.
3596  */
3597 LWS_VISIBLE LWS_EXTERN size_t
3598 lws_get_peer_write_allowance(struct lws *wsi);
3599 ///@}
3600
3601 /**
3602  * lws_rx_flow_control() - Enable and disable socket servicing for
3603  *                              received packets.
3604  *
3605  * If the output side of a server process becomes choked, this allows flow
3606  * control for the input side.
3607  *
3608  * \param wsi:  Websocket connection instance to get callback for
3609  * \param enable:       0 = disable read servicing for this connection, 1 = enable
3610  */
3611 LWS_VISIBLE LWS_EXTERN int
3612 lws_rx_flow_control(struct lws *wsi, int enable);
3613
3614 /**
3615  * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
3616  *
3617  * When the user server code realizes it can accept more input, it can
3618  * call this to have the RX flow restriction removed from all connections using
3619  * the given protocol.
3620  * \param context:      lws_context
3621  * \param protocol:     all connections using this protocol will be allowed to receive
3622  */
3623 LWS_VISIBLE LWS_EXTERN void
3624 lws_rx_flow_allow_all_protocol(const struct lws_context *context,
3625                                const struct lws_protocols *protocol);
3626
3627 /**
3628  * lws_remaining_packet_payload() - Bytes to come before "overall"
3629  *                                            rx packet is complete
3630  * \param wsi:          Websocket instance (available from user callback)
3631  *
3632  *      This function is intended to be called from the callback if the
3633  *  user code is interested in "complete packets" from the client.
3634  *  libwebsockets just passes through payload as it comes and issues a buffer
3635  *  additionally when it hits a built-in limit.  The LWS_CALLBACK_RECEIVE
3636  *  callback handler can use this API to find out if the buffer it has just
3637  *  been given is the last piece of a "complete packet" from the client --
3638  *  when that is the case lws_remaining_packet_payload() will return
3639  *  0.
3640  *
3641  *  Many protocols won't care becuse their packets are always small.
3642  */
3643 LWS_VISIBLE LWS_EXTERN size_t
3644 lws_remaining_packet_payload(struct lws *wsi);
3645
3646
3647 /** \defgroup sock-adopt Socket adoption helpers
3648  * ##Socket adoption helpers
3649  *
3650  * When integrating with an external app with its own event loop, these can
3651  * be used to accept connections from someone else's listening socket.
3652  *
3653  * When using lws own event loop, these are not needed.
3654  */
3655 ///@{
3656
3657 /**
3658  * lws_adopt_socket() - adopt foreign socket as if listen socket accepted it
3659  * for the default vhost of context.
3660  * \param context: lws context
3661  * \param accept_fd: fd of already-accepted socket to adopt
3662  *
3663  * Either returns new wsi bound to accept_fd, or closes accept_fd and
3664  * returns NULL, having cleaned up any new wsi pieces.
3665  *
3666  * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
3667  * to ws or just serve http.
3668  */
3669 LWS_VISIBLE LWS_EXTERN struct lws *
3670 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd);
3671 /**
3672  * lws_adopt_socket_vhost() - adopt foreign socket as if listen socket accepted it
3673  * for vhost
3674  * \param vhost: lws vhost
3675  * \param accept_fd: fd of already-accepted socket to adopt
3676  *
3677  * Either returns new wsi bound to accept_fd, or closes accept_fd and
3678  * returns NULL, having cleaned up any new wsi pieces.
3679  *
3680  * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
3681  * to ws or just serve http.
3682  */
3683 LWS_VISIBLE LWS_EXTERN struct lws *
3684 lws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd);
3685 /**
3686  * lws_adopt_socket_readbuf() - adopt foreign socket and first rx as if listen socket accepted it
3687  * for the default vhost of context.
3688  * \param context:      lws context
3689  * \param accept_fd:    fd of already-accepted socket to adopt
3690  * \param readbuf:      NULL or pointer to data that must be drained before reading from
3691  *              accept_fd
3692  * \param len:  The length of the data held at \param readbuf
3693  *
3694  * Either returns new wsi bound to accept_fd, or closes accept_fd and
3695  * returns NULL, having cleaned up any new wsi pieces.
3696  *
3697  * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
3698  * to ws or just serve http.
3699  *
3700  * If your external code did not already read from the socket, you can use
3701  * lws_adopt_socket() instead.
3702  *
3703  * This api is guaranteed to use the data at \param readbuf first, before reading from
3704  * the socket.
3705  *
3706  * readbuf is limited to the size of the ah rx buf, currently 2048 bytes.
3707  */
3708 LWS_VISIBLE LWS_EXTERN struct lws *
3709 lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
3710                          const char *readbuf, size_t len);
3711 /**
3712  * lws_adopt_socket_vhost_readbuf() - adopt foreign socket and first rx as if listen socket
3713  * accepted it for vhost.
3714  * \param vhost:        lws vhost
3715  * \param accept_fd:    fd of already-accepted socket to adopt
3716  * \param readbuf:      NULL or pointer to data that must be drained before reading from
3717  *                      accept_fd
3718  * \param len:          The length of the data held at \param readbuf
3719  *
3720  * Either returns new wsi bound to accept_fd, or closes accept_fd and
3721  * returns NULL, having cleaned up any new wsi pieces.
3722  *
3723  * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
3724  * to ws or just serve http.
3725  *
3726  * If your external code did not already read from the socket, you can use
3727  * lws_adopt_socket() instead.
3728  *
3729  * This api is guaranteed to use the data at \param readbuf first, before reading from
3730  * the socket.
3731  *
3732  * readbuf is limited to the size of the ah rx buf, currently 2048 bytes.
3733  */
3734 LWS_VISIBLE LWS_EXTERN struct lws *
3735 lws_adopt_socket_vhost_readbuf(struct lws_vhost *vhost, lws_sockfd_type accept_fd,
3736                                const char *readbuf, size_t len);
3737 ///@}
3738
3739 /** \defgroup net Network related helper APIs
3740  * ##Network related helper APIs
3741  *
3742  * These wrap miscellaneous useful network-related functions
3743  */
3744 ///@{
3745
3746 /**
3747  * lws_canonical_hostname() - returns this host's hostname
3748  *
3749  * This is typically used by client code to fill in the host parameter
3750  * when making a client connection.  You can only call it after the context
3751  * has been created.
3752  *
3753  * \param context:      Websocket context
3754  */
3755 LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
3756 lws_canonical_hostname(struct lws_context *context);
3757
3758 /**
3759  * lws_get_peer_addresses() - Get client address information
3760  * \param wsi:  Local struct lws associated with
3761  * \param fd:           Connection socket descriptor
3762  * \param name: Buffer to take client address name
3763  * \param name_len:     Length of client address name buffer
3764  * \param rip:  Buffer to take client address IP dotted quad
3765  * \param rip_len:      Length of client address IP buffer
3766  *
3767  *      This function fills in name and rip with the name and IP of
3768  *      the client connected with socket descriptor fd.  Names may be
3769  *      truncated if there is not enough room.  If either cannot be
3770  *      determined, they will be returned as valid zero-length strings.
3771  */
3772 LWS_VISIBLE LWS_EXTERN void
3773 lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
3774                        int name_len, char *rip, int rip_len);
3775
3776 /**
3777  * lws_get_peer_simple() - Get client address information without RDNS
3778  *
3779  * \param wsi:  Local struct lws associated with
3780  * \param name: Buffer to take client address name
3781  * \param namelen:      Length of client address name buffer
3782  *
3783  * This provides a 123.123.123.123 type IP address in name from the
3784  * peer that has connected to wsi
3785  */
3786 LWS_VISIBLE LWS_EXTERN const char *
3787 lws_get_peer_simple(struct lws *wsi, char *name, int namelen);
3788 #ifndef LWS_WITH_ESP8266
3789 /**
3790  * lws_interface_to_sa() - Convert interface name or IP to sockaddr struct
3791  *
3792  * \param ipv6: Allow IPV6 addresses
3793  * \param ifname:       Interface name or IP
3794  * \param addr: struct sockaddr_in * to be written
3795  * \param addrlen:      Length of addr
3796  *
3797  * This converts a textual network interface name to a sockaddr usable by
3798  * other network functions
3799  */
3800 LWS_VISIBLE LWS_EXTERN int
3801 lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr,
3802                     size_t addrlen);
3803 ///@}
3804 #endif
3805
3806 /** \defgroup misc Miscellaneous APIs
3807 * ##Miscellaneous APIs
3808 *
3809 * Various APIs outside of other categories
3810 */
3811 ///@{
3812
3813 /**
3814  * lws_snprintf(): snprintf that truncates the returned length too
3815  *
3816  * \param str: destination buffer
3817  * \param size: bytes left in destination buffer
3818  * \param format: format string
3819  * \param ...: args for format
3820  *
3821  * This lets you correctly truncate buffers by concatenating lengths, if you
3822  * reach the limit the reported length doesn't exceed the limit.
3823  */
3824 LWS_VISIBLE LWS_EXTERN int
3825 lws_snprintf(char *str, size_t size, const char *format, ...) LWS_FORMAT(3);
3826
3827 /**
3828  * lws_get_random(): fill a buffer with platform random data
3829  *
3830  * \param context: the lws context
3831  * \param buf: buffer to fill
3832  * \param len: how much to fill
3833  *
3834  * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
3835  * it's interested to see if the frame it's dealing with was sent in binary
3836  * mode.
3837  */
3838 LWS_VISIBLE LWS_EXTERN int
3839 lws_get_random(struct lws_context *context, void *buf, int len);
3840 /**
3841  * lws_daemonize(): make current process run in the background
3842  *
3843  * \param _lock_path: the filepath to write the lock file
3844  *
3845  * Spawn lws as a background process, taking care of various things
3846  */
3847 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3848 lws_daemonize(const char *_lock_path);
3849 /**
3850  * lws_get_library_version(): return string describing the version of lws
3851  *
3852  * On unix, also includes the git describe
3853  */
3854 LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
3855 lws_get_library_version(void);
3856
3857 /**
3858  * lws_wsi_user() - get the user data associated with the connection
3859  * \param wsi: lws connection
3860  *
3861  * Not normally needed since it's passed into the callback
3862  */
3863 LWS_VISIBLE LWS_EXTERN void *
3864 lws_wsi_user(struct lws *wsi);
3865
3866 /**
3867  * lws_parse_uri:       cut up prot:/ads:port/path into pieces
3868  *                      Notice it does so by dropping '\0' into input string
3869  *                      and the leading / on the path is consequently lost
3870  *
3871  * \param p:                    incoming uri string.. will get written to
3872  * \param prot:         result pointer for protocol part (https://)
3873  * \param ads:          result pointer for address part
3874  * \param port:         result pointer for port part
3875  * \param path:         result pointer for path part
3876  */
3877 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3878 lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
3879               const char **path);
3880
3881 /**
3882  * lws_now_secs(): return seconds since 1970-1-1
3883  */
3884 LWS_VISIBLE LWS_EXTERN unsigned long
3885 lws_now_secs(void);
3886
3887 /**
3888  * lws_get_context - Allow geting lws_context from a Websocket connection
3889  * instance
3890  *
3891  * With this function, users can access context in the callback function.
3892  * Otherwise users may have to declare context as a global variable.
3893  *
3894  * \param wsi:  Websocket connection instance
3895  */
3896 LWS_VISIBLE LWS_EXTERN struct lws_context * LWS_WARN_UNUSED_RESULT
3897 lws_get_context(const struct lws *wsi);
3898
3899 /**
3900  * lws_get_count_threads(): how many service threads the context uses
3901  *
3902  * \param context: the lws context
3903  *
3904  * By default this is always 1, if you asked for more than lws can handle it
3905  * will clip the number of threads.  So you can use this to find out how many
3906  * threads are actually in use.
3907  */
3908 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3909 lws_get_count_threads(struct lws_context *context);
3910
3911 /**
3912  * lws_get_parent() - get parent wsi or NULL
3913  * \param wsi: lws connection
3914  *
3915  * Specialized wsi like cgi stdin/out/err are associated to a parent wsi,
3916  * this allows you to get their parent.
3917  */
3918 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
3919 lws_get_parent(const struct lws *wsi);
3920
3921 /**
3922  * lws_get_child() - get child wsi or NULL
3923  * \param wsi: lws connection
3924  *
3925  * Allows you to find a related wsi from the parent wsi.
3926  */
3927 LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
3928 lws_get_child(const struct lws *wsi);
3929
3930
3931 /*
3932  * \deprecated DEPRECATED Note: this is not normally needed as a user api.
3933  * It's provided in case it is
3934  * useful when integrating with other app poll loop service code.
3935  */
3936 LWS_VISIBLE LWS_EXTERN int
3937 lws_read(struct lws *wsi, unsigned char *buf, size_t len);
3938
3939 /**
3940  * lws_set_allocator() - custom allocator support
3941  *
3942  * \param realloc
3943  *
3944  * Allows you to replace the allocator (and deallocator) used by lws
3945  */
3946 LWS_VISIBLE LWS_EXTERN void
3947 lws_set_allocator(void *(*realloc)(void *ptr, size_t size));
3948 ///@}
3949
3950 /** \defgroup wsstatus Websocket status APIs
3951  * ##Websocket connection status APIs
3952  *
3953  * These provide information about ws connection or message status
3954  */
3955 ///@{
3956 /**
3957  * lws_send_pipe_choked() - tests if socket is writable or not
3958  * \param wsi: lws connection
3959  *
3960  * Allows you to check if you can write more on the socket
3961  */
3962 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3963 lws_send_pipe_choked(struct lws *wsi);
3964
3965 /**
3966  * lws_is_final_fragment() - tests if last part of ws message
3967  * \param wsi: lws connection
3968  */
3969 LWS_VISIBLE LWS_EXTERN int
3970 lws_is_final_fragment(struct lws *wsi);
3971
3972 /**
3973  * lws_get_reserved_bits() - access reserved bits of ws frame
3974  * \param wsi: lws connection
3975  */
3976 LWS_VISIBLE LWS_EXTERN unsigned char
3977 lws_get_reserved_bits(struct lws *wsi);
3978
3979 /**
3980  * lws_partial_buffered() - find out if lws buffered the last write
3981  * \param wsi:  websocket connection to check
3982  *
3983  * Returns 1 if you cannot use lws_write because the last
3984  * write on this connection is still buffered, and can't be cleared without
3985  * returning to the service loop and waiting for the connection to be
3986  * writeable again.
3987  *
3988  * If you will try to do >1 lws_write call inside a single
3989  * WRITEABLE callback, you must check this after every write and bail if
3990  * set, ask for a new writeable callback and continue writing from there.
3991  *
3992  * This is never set at the start of a writeable callback, but any write
3993  * may set it.
3994  */
3995 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
3996 lws_partial_buffered(struct lws *wsi);
3997
3998 /**
3999  * lws_frame_is_binary(): true if the current frame was sent in binary mode
4000  *
4001  * \param wsi: the connection we are inquiring about
4002  *
4003  * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
4004  * it's interested to see if the frame it's dealing with was sent in binary
4005  * mode.
4006  */
4007 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
4008 lws_frame_is_binary(struct lws *wsi);
4009
4010 /**
4011  * lws_is_ssl() - Find out if connection is using SSL
4012  * \param wsi:  websocket connection to check
4013  *
4014  *      Returns 0 if the connection is not using SSL, 1 if using SSL and
4015  *      using verified cert, and 2 if using SSL but the cert was not
4016  *      checked (appears for client wsi told to skip check on connection)
4017  */
4018 LWS_VISIBLE LWS_EXTERN int
4019 lws_is_ssl(struct lws *wsi);
4020 /**
4021  * lws_is_cgi() - find out if this wsi is running a cgi process
4022  * \param wsi: lws connection
4023  */
4024 LWS_VISIBLE LWS_EXTERN int
4025 lws_is_cgi(struct lws *wsi);
4026
4027 #ifdef LWS_OPENSSL_SUPPORT
4028 /**
4029  * lws_get_ssl() - Return wsi's SSL context structure
4030  * \param wsi:  websocket connection
4031  *
4032  * Returns pointer to the SSL library's context structure
4033  */
4034 LWS_VISIBLE LWS_EXTERN SSL*
4035 lws_get_ssl(struct lws *wsi);
4036 #endif
4037 ///@}
4038
4039
4040 /** \defgroup sha SHA and B64 helpers
4041  * ##SHA and B64 helpers
4042  *
4043  * These provide SHA-1 and B64 helper apis
4044  */
4045 ///@{
4046 #ifdef LWS_SHA1_USE_OPENSSL_NAME
4047 #define lws_SHA1 SHA1
4048 #else
4049 /**
4050  * lws_SHA1(): make a SHA-1 digest of a buffer
4051  *
4052  * \param d: incoming buffer
4053  * \param n: length of incoming buffer
4054  * \param md: buffer for message digest (must be >= 20 bytes)
4055  *
4056  * Reduces any size buffer into a 20-byte SHA-1 hash.
4057  */
4058 LWS_VISIBLE LWS_EXTERN unsigned char *
4059 lws_SHA1(const unsigned char *d, size_t n, unsigned char *md);
4060 #endif
4061 /**
4062  * lws_b64_encode_string(): encode a string into base 64
4063  *
4064  * \param in: incoming buffer
4065  * \param in_len: length of incoming buffer
4066  * \param out: result buffer
4067  * \param out_size: length of result buffer
4068  *
4069  * Encodes a string using b64
4070  */
4071 LWS_VISIBLE LWS_EXTERN int
4072 lws_b64_encode_string(const char *in, int in_len, char *out, int out_size);
4073 /**
4074  * lws_b64_decode_string(): decode a string from base 64
4075  *
4076  * \param in: incoming buffer
4077  * \param out: result buffer
4078  * \param out_size: length of result buffer
4079  *
4080  * Decodes a string using b64
4081  */
4082 LWS_VISIBLE LWS_EXTERN int
4083 lws_b64_decode_string(const char *in, char *out, int out_size);
4084 ///@}
4085
4086
4087 /*! \defgroup cgi cgi handling
4088  *
4089  * ##CGI handling
4090  *
4091  * These functions allow low-level control over stdin/out/err of the cgi.
4092  *
4093  * However for most cases, binding the cgi to http in and out, the default
4094  * lws implementation already does the right thing.
4095  */
4096 #ifdef LWS_WITH_CGI
4097 enum lws_enum_stdinouterr {
4098         LWS_STDIN = 0,
4099         LWS_STDOUT = 1,
4100         LWS_STDERR = 2,
4101 };
4102
4103 enum lws_cgi_hdr_state {
4104         LCHS_HEADER,
4105         LCHS_CR1,
4106         LCHS_LF1,
4107         LCHS_CR2,
4108         LCHS_LF2,
4109         LHCS_PAYLOAD,
4110         LCHS_SINGLE_0A,
4111 };
4112
4113 struct lws_cgi_args {
4114         struct lws **stdwsi; /**< get fd with lws_get_socket_fd() */
4115         enum lws_enum_stdinouterr ch; /**< channel index */
4116         unsigned char *data; /**< for messages with payload */
4117         enum lws_cgi_hdr_state hdr_state; /**< track where we are in cgi headers */
4118         int len; /**< length */
4119 };
4120
4121
4122 /**
4123  * lws_cgi: spawn network-connected cgi process
4124  *
4125  * \param wsi: connection to own the process
4126  * \param exec_array: array of "exec-name" "arg1" ... "argn" NULL
4127  * \param script_uri_path_len: how many chars on the left of the uri are the path to the cgi
4128  * \param timeout_secs: seconds script should be allowed to run
4129  * \param mp_cgienv: pvo list with per-vhost cgi options to put in env
4130  */
4131 LWS_VISIBLE LWS_EXTERN int
4132 lws_cgi(struct lws *wsi, const char * const *exec_array,
4133         int script_uri_path_len, int timeout_secs,
4134         const struct lws_protocol_vhost_options *mp_cgienv);
4135
4136 /**
4137  * lws_cgi_write_split_stdout_headers: write cgi output accounting for header part
4138  *
4139  * \param wsi: connection to own the process
4140  */
4141 LWS_VISIBLE LWS_EXTERN int
4142 lws_cgi_write_split_stdout_headers(struct lws *wsi);
4143
4144 /**
4145  * lws_cgi_kill: terminate cgi process associated with wsi
4146  *
4147  * \param wsi: connection to own the process
4148  */
4149 LWS_VISIBLE LWS_EXTERN int
4150 lws_cgi_kill(struct lws *wsi);
4151 #endif
4152 ///@}
4153
4154
4155 /*! \defgroup fops file operation wrapping
4156  *
4157  * ##File operation wrapping
4158  *
4159  * Use these helper functions if you want to access a file from the perspective
4160  * of a specific wsi, which is usually the case.  If you just want contextless
4161  * file access, use the fops callbacks directly with NULL wsi instead of these
4162  * helpers.
4163  *
4164  * If so, then it calls the platform handler or user overrides where present
4165  * (as defined in info->fops)
4166  *
4167  * The advantage from all this is user code can be portable for file operations
4168  * without having to deal with differences between platforms.
4169  */
4170 //@{
4171
4172 /** struct lws_plat_file_ops - Platform-specific file operations
4173  *
4174  * These provide platform-agnostic ways to deal with filesystem access in the
4175  * library and in the user code.
4176  */
4177
4178 #define LWS_FOP_OPEN open
4179 #define LWS_FOP_CLOSE close
4180 #define LWS_FOP_SEEK_CUR seek_cur
4181 #define LWS_FOP_READ read
4182 #define LWS_FOP_WRITE write
4183
4184 struct lws_plat_file_ops {
4185         lws_filefd_type (*LWS_FOP_OPEN)(struct lws *wsi, const char *filename,
4186                                 unsigned long *filelen, int flags);
4187         /**< Open file (always binary access if plat supports it)
4188          * filelen is filled on exit to be the length of the file
4189          * flags should be set to O_RDONLY or O_RDWR */
4190         int (*LWS_FOP_CLOSE)(struct lws *wsi, lws_filefd_type fd);
4191         /**< close file */
4192         unsigned long (*LWS_FOP_SEEK_CUR)(struct lws *wsi, lws_filefd_type fd,
4193                                   long offset_from_cur_pos);
4194         /**< seek from current position */
4195         int (*LWS_FOP_READ)(struct lws *wsi, lws_filefd_type fd,
4196                             unsigned long *amount, unsigned char *buf,
4197                             unsigned long len);
4198         /**< Read from file, on exit *amount is set to amount actually read */
4199         int (*LWS_FOP_WRITE)(struct lws *wsi, lws_filefd_type fd,
4200                              unsigned long *amount, unsigned char *buf,
4201                              unsigned long len);
4202         /**< Write to file, on exit *amount is set to amount actually written */
4203
4204         /* Add new things just above here ---^
4205          * This is part of the ABI, don't needlessly break compatibility */
4206 };
4207
4208 /**
4209  * lws_get_fops() - get current file ops
4210  *
4211  * \param context: context
4212  */
4213 LWS_VISIBLE LWS_EXTERN struct lws_plat_file_ops * LWS_WARN_UNUSED_RESULT
4214 lws_get_fops(struct lws_context *context);
4215
4216 /**
4217  * lws_plat_file_open() - file open operations
4218  *
4219  * \param wsi: connection doing the opening
4220  * \param filename: filename to open
4221  * \param filelen: length of file (filled in by call)
4222  * \param flags: open flags
4223  */
4224 static LWS_INLINE lws_filefd_type LWS_WARN_UNUSED_RESULT
4225 lws_plat_file_open(struct lws *wsi, const char *filename,
4226                    unsigned long *filelen, int flags)
4227 {
4228         return lws_get_fops(lws_get_context(wsi))->LWS_FOP_OPEN(wsi, filename,
4229                                                     filelen, flags);
4230 }
4231
4232 /**
4233  * lws_plat_file_close() - close file
4234  *
4235  * \param wsi: connection opened by
4236  * \param fd: file descriptor
4237  */
4238 static LWS_INLINE int
4239 lws_plat_file_close(struct lws *wsi, lws_filefd_type fd)
4240 {
4241         return lws_get_fops(lws_get_context(wsi))->LWS_FOP_CLOSE(wsi, fd);
4242 }
4243
4244 /**
4245  * lws_plat_file_seek_cur() - close file
4246  *
4247  * \param wsi: connection opened by
4248  * \param fd: file descriptor
4249  * \param offset: position to seek to
4250  */
4251 static LWS_INLINE unsigned long
4252 lws_plat_file_seek_cur(struct lws *wsi, lws_filefd_type fd, long offset)
4253 {
4254         return lws_get_fops(lws_get_context(wsi))->LWS_FOP_SEEK_CUR(wsi,
4255                                                                     fd, offset);
4256 }
4257 /**
4258  * lws_plat_file_read() - read from file
4259  *
4260  * \param wsi: connection opened by
4261  * \param fd: file descriptor
4262  * \param amount: how much to read (rewritten by call)
4263  * \param buf: buffer to write to
4264  * \param len: max length
4265  */
4266 static LWS_INLINE int LWS_WARN_UNUSED_RESULT
4267 lws_plat_file_read(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
4268                    unsigned char *buf, unsigned long len)
4269 {
4270         return lws_get_fops(lws_get_context(wsi))->LWS_FOP_READ(wsi, fd,
4271                         amount, buf, len);
4272 }
4273 /**
4274  * lws_plat_file_write() - write from file
4275  *
4276  * \param wsi: connection opened by
4277  * \param fd: file descriptor
4278  * \param amount: how much to write (rewritten by call)
4279  * \param buf: buffer to read from
4280  * \param len: max length
4281  */
4282 static LWS_INLINE int LWS_WARN_UNUSED_RESULT
4283 lws_plat_file_write(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
4284                     unsigned char *buf, unsigned long len)
4285 {
4286         return lws_get_fops(lws_get_context(wsi))->LWS_FOP_WRITE(wsi, fd,
4287                                                 amount, buf, len);
4288 }
4289 //@}
4290
4291 /** \defgroup smtp
4292  * \ingroup lwsapi
4293  * ##SMTP related functions
4294  *
4295  * These apis let you communicate with a local SMTP server to send email from
4296  * lws.  It handles all the SMTP sequencing and protocol actions.
4297  *
4298  * Your system should have postfix, sendmail or another MTA listening on port
4299  * 25 and able to send email using the "mail" commandline app.  Usually distro
4300  * MTAs are configured for this by default.
4301  *
4302  * It runs via its own libuv events if initialized (which requires giving it
4303  * a libuv loop to attach to).
4304  *
4305  * It operates using three callbacks, on_next() queries if there is a new email
4306  * to send, on_get_body() asks for the body of the email, and on_sent() is
4307  * called after the email is successfully sent.
4308  *
4309  * To use it
4310  *
4311  *  - create an lws_email struct
4312  *
4313  *  - initialize data, loop, the email_* strings, max_content_size and
4314  *    the callbacks
4315  *
4316  *  - call lws_email_init()
4317  *
4318  *  When you have at least one email to send, call lws_email_check() to
4319  *  schedule starting to send it.
4320  */
4321 //@{
4322 #ifdef LWS_WITH_SMTP
4323
4324 /** enum lwsgs_smtp_states - where we are in SMTP protocol sequence */
4325 enum lwsgs_smtp_states {
4326         LGSSMTP_IDLE, /**< awaiting new email */
4327         LGSSMTP_CONNECTING, /**< opening tcp connection to MTA */
4328         LGSSMTP_CONNECTED, /**< tcp connection to MTA is connected */
4329         LGSSMTP_SENT_HELO, /**< sent the HELO */
4330         LGSSMTP_SENT_FROM, /**< sent FROM */
4331         LGSSMTP_SENT_TO, /**< sent TO */
4332         LGSSMTP_SENT_DATA, /**< sent DATA request */
4333         LGSSMTP_SENT_BODY, /**< sent the email body */
4334         LGSSMTP_SENT_QUIT, /**< sent the session quit */
4335 };
4336
4337 /** struct lws_email - abstract context for performing SMTP operations */
4338 struct lws_email {
4339         void *data;
4340         /**< opaque pointer set by user code and available to the callbacks */
4341         uv_loop_t *loop;
4342         /**< the libuv loop we will work on */
4343
4344         char email_smtp_ip[32]; /**< Fill before init, eg, "127.0.0.1" */
4345         char email_helo[32];    /**< Fill before init, eg, "myserver.com" */
4346         char email_from[100];   /**< Fill before init or on_next */
4347         char email_to[100];     /**< Fill before init or on_next */
4348
4349         unsigned int max_content_size;
4350         /**< largest possible email body size */
4351
4352         /* Fill all the callbacks before init */
4353
4354         int (*on_next)(struct lws_email *email);
4355         /**< (Fill in before calling lws_email_init)
4356          * called when idle, 0 = another email to send, nonzero is idle.
4357          * If you return 0, all of the email_* char arrays must be set
4358          * to something useful. */
4359         int (*on_sent)(struct lws_email *email);
4360         /**< (Fill in before calling lws_email_init)
4361          * called when transfer of the email to the SMTP server was
4362          * successful, your callback would remove the current email
4363          * from its queue */
4364         int (*on_get_body)(struct lws_email *email, char *buf, int len);
4365         /**< (Fill in before calling lws_email_init)
4366          * called when the body part of the queued email is about to be
4367          * sent to the SMTP server. */
4368
4369
4370         /* private things */
4371         uv_timer_t timeout_email; /**< private */
4372         enum lwsgs_smtp_states estate; /**< private */
4373         uv_connect_t email_connect_req; /**< private */
4374         uv_tcp_t email_client; /**< private */
4375         time_t email_connect_started; /**< private */
4376         char email_buf[256]; /**< private */
4377         char *content; /**< private */
4378 };
4379
4380 /**
4381  * lws_email_init() - Initialize a struct lws_email
4382  *
4383  * \param email: struct lws_email to init
4384  * \param loop: libuv loop to use
4385  * \param max_content: max email content size
4386  *
4387  * Prepares a struct lws_email for use ending SMTP
4388  */
4389 LWS_VISIBLE LWS_EXTERN int
4390 lws_email_init(struct lws_email *email, uv_loop_t *loop, int max_content);
4391
4392 /**
4393  * lws_email_check() - Request check for new email
4394  *
4395  * \param email: struct lws_email context to check
4396  *
4397  * Schedules a check for new emails in 1s... call this when you have queued an
4398  * email for send.
4399  */
4400 LWS_VISIBLE LWS_EXTERN void
4401 lws_email_check(struct lws_email *email);
4402 /**
4403  * lws_email_destroy() - stop using the struct lws_email
4404  *
4405  * \param email: the struct lws_email context
4406  *
4407  * Stop sending email using email and free allocations
4408  */
4409 LWS_VISIBLE LWS_EXTERN void
4410 lws_email_destroy(struct lws_email *email);
4411
4412 #endif
4413 //@}
4414
4415 #ifdef __cplusplus
4416 }
4417 #endif
4418
4419 #endif