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