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