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