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