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