1 // Copyright (c) 2004-2013 Sergey Lyubka <valenok@gmail.com>
2 // Copyright (c) 2013-2014 Cesanta Software Limited
5 // This library is dual-licensed: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License version 2 as
7 // published by the Free Software Foundation. For the terms of this
8 // license, see <http://www.gnu.org/licenses/>.
10 // You are free to use this library under the terms of the GNU General
11 // Public License, but WITHOUT ANY WARRANTY; without even the implied
12 // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 // See the GNU General Public License for more details.
15 // Alternatively, you can license this library under a commercial
16 // license, as set out in <http://cesanta.com/>.
18 #ifdef NOEMBED_NET_SKELETON
19 #include "net_skeleton.h"
22 // Copyright (c) 2014 Cesanta Software Limited
23 // All rights reserved
25 // This software is dual-licensed: you can redistribute it and/or modify
26 // it under the terms of the GNU General Public License version 2 as
27 // published by the Free Software Foundation. For the terms of this
28 // license, see <http://www.gnu.org/licenses/>.
30 // You are free to use this software under the terms of the GNU General
31 // Public License, but WITHOUT ANY WARRANTY; without even the implied
32 // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
33 // See the GNU General Public License for more details.
35 // Alternatively, you can license this software under a commercial
36 // license, as set out in <http://cesanta.com/>.
38 #ifndef NS_SKELETON_HEADER_INCLUDED
39 #define NS_SKELETON_HEADER_INCLUDED
41 #define NS_SKELETON_VERSION "2.1.0"
43 #undef UNICODE // Use ANSI WinAPI functions
44 #undef _UNICODE // Use multibyte encoding on Windows
45 #define _MBCS // Use multibyte encoding on Windows
46 #define _INTEGRAL_MAX_BITS 64 // Enable _stati64() on Windows
47 #ifndef _CRT_SECURE_NO_WARNINGS
48 #define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005+
50 #undef WIN32_LEAN_AND_MEAN // Let windows.h always include winsock2.h
52 #define _XOPEN_SOURCE 600 // For flockfile() on Linux
54 #define __STDC_FORMAT_MACROS // <inttypes.h> wants this for C++
55 #define __STDC_LIMIT_MACROS // C++ wants that for INT64_MAX
56 #ifndef _LARGEFILE_SOURCE
57 #define _LARGEFILE_SOURCE // Enable fseeko() and ftello() functions
59 #define _FILE_OFFSET_BITS 64 // Enable 64-bit file offsets
62 #pragma warning (disable : 4127) // FD_SET() emits warning, disable it
63 #pragma warning (disable : 4204) // missing c99 support
66 #if defined(_WIN32) && !defined(MONGOOSE_NO_CGI)
67 #define MONGOOSE_ENABLE_THREADS /* Windows uses stdio threads for CGI */
70 #ifndef MONGOOSE_ENABLE_THREADS
71 #define NS_DISABLE_THREADS
75 #define _MMAP_DECLARED // Prevent dummy mmap() declaration in stdio.h
78 #include <sys/types.h>
94 #pragma comment(lib, "ws2_32.lib") // Linking with winsock library
96 typedef SSIZE_T ssize_t;
99 #define FD_SETSIZE 1024
101 #include <winsock2.h>
102 #include <ws2tcpip.h>
106 #define EINPROGRESS WSAEINPROGRESS
109 #define EWOULDBLOCK WSAEWOULDBLOCK
113 #define STR(x) STRX(x)
114 #define __func__ __FILE__ ":" STR(__LINE__)
117 #define va_copy(x,y) x = y
118 #endif // MINGW #defines va_copy
119 #define snprintf _snprintf
120 #define vsnprintf _vsnprintf
121 #define sleep(x) Sleep((x) * 1000)
122 #define to64(x) _atoi64(x)
123 typedef int socklen_t;
124 typedef unsigned char uint8_t;
125 typedef unsigned int uint32_t;
126 typedef unsigned short uint16_t;
127 typedef unsigned __int64 uint64_t;
128 typedef __int64 int64_t;
129 typedef SOCKET sock_t;
130 typedef struct _stati64 ns_stat_t;
132 #define S_ISDIR(x) ((x) & _S_IFDIR)
141 #include <arpa/inet.h> // For inet_pton() when NS_ENABLE_IPV6 is defined
142 #include <netinet/in.h>
143 #include <sys/socket.h>
144 #include <sys/select.h>
145 #define closesocket(x) close(x)
149 #include <sys/time.h>
150 typedef int socklen_t;
152 #define INVALID_SOCKET (-1)
153 #define to64(x) strtoll(x, NULL, 10)
155 typedef struct stat ns_stat_t;
158 #ifdef NS_ENABLE_DEBUG
159 #define DBG(x) do { printf("%-20s ", __func__); printf x; putchar('\n'); \
160 fflush(stdout); } while(0)
166 #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
171 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
173 #include <openssl/ssl.h>
176 typedef void *SSL_CTX;
181 #endif // __cplusplus
183 union socket_address {
185 struct sockaddr_in sin;
186 #ifdef NS_ENABLE_IPV6
187 struct sockaddr_in6 sin6;
189 struct sockaddr sin6;
193 // Describes chunk of memory
199 // IO buffers interface
206 void iobuf_init(struct iobuf *, size_t initial_size);
207 void iobuf_free(struct iobuf *);
208 size_t iobuf_append(struct iobuf *, const void *data, size_t data_size);
209 void iobuf_remove(struct iobuf *, size_t data_size);
210 void iobuf_resize(struct iobuf *, size_t new_size);
212 // Callback function (event handler) prototype, must be defined by user.
213 // Net skeleton will call event handler, passing events defined above.
214 struct ns_connection;
215 typedef void (*ns_callback_t)(struct ns_connection *, int event_num, void *evp);
217 // Events. Meaning of event parameter (evp) is given in the comment.
218 #define NS_POLL 0 // Sent to each connection on each call to ns_mgr_poll()
219 #define NS_ACCEPT 1 // New connection accept()-ed. union socket_address *addr
220 #define NS_CONNECT 2 // connect() succeeded or failed. int *success_status
221 #define NS_RECV 3 // Data has benn received. int *num_bytes
222 #define NS_SEND 4 // Data has been written to a socket. int *num_bytes
223 #define NS_CLOSE 5 // Connection is closed. NULL
227 struct ns_connection *active_connections;
228 const char *hexdump_file; // Debug hexdump file path
229 sock_t ctl[2]; // Socketpair for mg_wakeup()
230 void *user_data; // User data
234 struct ns_connection {
235 struct ns_connection *next, *prev; // ns_mgr::active_connections linkage
236 struct ns_connection *listener; // Set only for accept()-ed connections
239 sock_t sock; // Socket
240 union socket_address sa; // Peer address
241 size_t recv_iobuf_limit; /* Max size of recv buffer */
242 struct iobuf recv_iobuf; // Received data
243 struct iobuf send_iobuf; // Data scheduled for sending
246 void *user_data; // User-specific data
247 void *proto_data; // Application protocol-specific data
248 time_t last_io_time; // Timestamp of the last socket IO
249 ns_callback_t callback; // Event handler function
252 #define NSF_FINISHED_SENDING_DATA (1 << 0)
253 #define NSF_BUFFER_BUT_DONT_SEND (1 << 1)
254 #define NSF_SSL_HANDSHAKE_DONE (1 << 2)
255 #define NSF_CONNECTING (1 << 3)
256 #define NSF_CLOSE_IMMEDIATELY (1 << 4)
257 #define NSF_WANT_READ (1 << 5)
258 #define NSF_WANT_WRITE (1 << 6)
259 #define NSF_LISTENING (1 << 7)
260 #define NSF_UDP (1 << 8)
262 #define NSF_USER_1 (1 << 20)
263 #define NSF_USER_2 (1 << 21)
264 #define NSF_USER_3 (1 << 22)
265 #define NSF_USER_4 (1 << 23)
266 #define NSF_USER_5 (1 << 24)
267 #define NSF_USER_6 (1 << 25)
270 void ns_mgr_init(struct ns_mgr *, void *user_data);
271 void ns_mgr_free(struct ns_mgr *);
272 time_t ns_mgr_poll(struct ns_mgr *, int milli);
273 void ns_broadcast(struct ns_mgr *, ns_callback_t, void *, size_t);
275 struct ns_connection *ns_next(struct ns_mgr *, struct ns_connection *);
276 struct ns_connection *ns_add_sock(struct ns_mgr *, sock_t,
277 ns_callback_t, void *);
278 struct ns_connection *ns_bind(struct ns_mgr *, const char *,
279 ns_callback_t, void *);
280 struct ns_connection *ns_connect(struct ns_mgr *, const char *,
281 ns_callback_t, void *);
283 int ns_send(struct ns_connection *, const void *buf, size_t len);
284 int ns_printf(struct ns_connection *, const char *fmt, ...);
285 int ns_vprintf(struct ns_connection *, const char *fmt, va_list ap);
288 void *ns_start_thread(void *(*f)(void *), void *p);
289 int ns_socketpair(sock_t [2]);
290 int ns_socketpair2(sock_t [2], int sock_type); // SOCK_STREAM or SOCK_DGRAM
291 void ns_set_close_on_exec(sock_t);
292 void ns_sock_to_str(sock_t sock, char *buf, size_t len, int flags);
293 int ns_hexdump(const void *buf, int len, char *dst, int dst_len);
294 int ns_avprintf(char **buf, size_t size, const char *fmt, va_list ap);
295 int ns_resolve(const char *domain_name, char *ip_addr_buf, size_t buf_len);
299 #endif // __cplusplus
301 #endif // NS_SKELETON_HEADER_INCLUDED
302 // Copyright (c) 2014 Cesanta Software Limited
303 // All rights reserved
305 // This software is dual-licensed: you can redistribute it and/or modify
306 // it under the terms of the GNU General Public License version 2 as
307 // published by the Free Software Foundation. For the terms of this
308 // license, see <http://www.gnu.org/licenses/>.
310 // You are free to use this software under the terms of the GNU General
311 // Public License, but WITHOUT ANY WARRANTY; without even the implied
312 // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
313 // See the GNU General Public License for more details.
315 // Alternatively, you can license this software under a commercial
316 // license, as set out in <http://cesanta.com/>.
318 // $Date: 2014-09-28 05:04:41 UTC $
322 #define NS_MALLOC malloc
326 #define NS_REALLOC realloc
334 #define NS_CALLOC calloc
337 #define NS_CTL_MSG_MESSAGE_SIZE (8 * 1024)
338 #define NS_READ_BUFFER_SIZE 2048
339 #define NS_UDP_RECEIVE_BUFFER_SIZE 2000
340 #define NS_VPRINTF_BUFFER_SIZE 500
343 ns_callback_t callback;
344 char message[NS_CTL_MSG_MESSAGE_SIZE];
347 void iobuf_resize(struct iobuf *io, size_t new_size) {
349 if ((new_size > io->size || (new_size < io->size && new_size >= io->len)) &&
350 (p = (char *) NS_REALLOC(io->buf, new_size)) != NULL) {
356 void iobuf_init(struct iobuf *iobuf, size_t initial_size) {
357 iobuf->len = iobuf->size = 0;
359 iobuf_resize(iobuf, initial_size);
362 void iobuf_free(struct iobuf *iobuf) {
364 if (iobuf->buf != NULL) NS_FREE(iobuf->buf);
365 iobuf_init(iobuf, 0);
369 size_t iobuf_append(struct iobuf *io, const void *buf, size_t len) {
373 assert(io->len <= io->size);
376 if (len > ~(size_t)0 - (size_t)(io->buf + io->len)) {
381 } else if (io->len + len <= io->size) {
382 memcpy(io->buf + io->len, buf, len);
384 } else if ((p = (char *) NS_REALLOC(io->buf, io->len + len)) != NULL) {
386 memcpy(io->buf + io->len, buf, len);
396 void iobuf_remove(struct iobuf *io, size_t n) {
397 if (n > 0 && n <= io->len) {
398 memmove(io->buf, io->buf + n, io->len - n);
403 static size_t ns_out(struct ns_connection *nc, const void *buf, size_t len) {
404 if (nc->flags & NSF_UDP) {
405 long n = sendto(nc->sock, (const char *) buf, len, 0, &nc->sa.sa,
407 DBG(("%p %d send %ld (%d %s)", nc, nc->sock, n, errno, strerror(errno)));
408 return n < 0 ? 0 : n;
410 return iobuf_append(&nc->send_iobuf, buf, len);
414 #ifndef NS_DISABLE_THREADS
415 void *ns_start_thread(void *(*f)(void *), void *p) {
417 return (void *) _beginthread((void (__cdecl *)(void *)) f, 0, p);
419 pthread_t thread_id = (pthread_t) 0;
422 (void) pthread_attr_init(&attr);
423 (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
425 #if defined(NS_STACK_SIZE) && NS_STACK_SIZE > 1
426 (void) pthread_attr_setstacksize(&attr, NS_STACK_SIZE);
429 pthread_create(&thread_id, &attr, f, p);
430 pthread_attr_destroy(&attr);
432 return (void *) thread_id;
435 #endif // NS_DISABLE_THREADS
437 static void ns_add_conn(struct ns_mgr *mgr, struct ns_connection *c) {
438 c->next = mgr->active_connections;
439 mgr->active_connections = c;
441 if (c->next != NULL) c->next->prev = c;
444 static void ns_remove_conn(struct ns_connection *conn) {
445 if (conn->prev == NULL) conn->mgr->active_connections = conn->next;
446 if (conn->prev) conn->prev->next = conn->next;
447 if (conn->next) conn->next->prev = conn->prev;
450 // Print message to buffer. If buffer is large enough to hold the message,
451 // return buffer. If buffer is to small, allocate large enough buffer on heap,
452 // and return allocated buffer.
453 int ns_avprintf(char **buf, size_t size, const char *fmt, va_list ap) {
457 va_copy(ap_copy, ap);
458 len = vsnprintf(*buf, size, fmt, ap_copy);
462 // eCos and Windows are not standard-compliant and return -1 when
463 // the buffer is too small. Keep allocating larger buffers until we
464 // succeed or out of memory.
467 if (*buf) NS_FREE(*buf);
469 if ((*buf = (char *) NS_MALLOC(size)) == NULL) break;
470 va_copy(ap_copy, ap);
471 len = vsnprintf(*buf, size, fmt, ap_copy);
474 } else if (len > (int) size) {
475 // Standard-compliant code path. Allocate a buffer that is large enough.
476 if ((*buf = (char *) NS_MALLOC(len + 1)) == NULL) {
479 va_copy(ap_copy, ap);
480 len = vsnprintf(*buf, len + 1, fmt, ap_copy);
488 int ns_vprintf(struct ns_connection *nc, const char *fmt, va_list ap) {
489 char mem[NS_VPRINTF_BUFFER_SIZE], *buf = mem;
492 if ((len = ns_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
493 ns_out(nc, buf, len);
495 if (buf != mem && buf != NULL) {
502 int ns_printf(struct ns_connection *conn, const char *fmt, ...) {
506 len = ns_vprintf(conn, fmt, ap);
511 static void hexdump(struct ns_connection *nc, const char *path,
512 int num_bytes, int ev) {
513 const struct iobuf *io = ev == NS_SEND ? &nc->send_iobuf : &nc->recv_iobuf;
515 char *buf, src[60], dst[60];
516 int buf_size = num_bytes * 5 + 100;
518 if ((fp = fopen(path, "a")) != NULL) {
519 ns_sock_to_str(nc->sock, src, sizeof(src), 3);
520 ns_sock_to_str(nc->sock, dst, sizeof(dst), 7);
521 fprintf(fp, "%lu %p %s %s %s %d\n", (unsigned long) time(NULL),
523 ev == NS_RECV ? "<-" : ev == NS_SEND ? "->" :
524 ev == NS_ACCEPT ? "<A" : ev == NS_CONNECT ? "C>" : "XX",
526 if (num_bytes > 0 && (buf = (char *) NS_MALLOC(buf_size)) != NULL) {
527 ns_hexdump(io->buf + (ev == NS_SEND ? 0 : io->len) -
528 (ev == NS_SEND ? 0 : num_bytes), num_bytes, buf, buf_size);
529 fprintf(fp, "%s", buf);
536 static void ns_call(struct ns_connection *nc, int ev, void *p) {
537 if (nc->mgr->hexdump_file != NULL && ev != NS_POLL) {
538 int len = (ev == NS_RECV || ev == NS_SEND) ? * (int *) p : 0;
539 hexdump(nc, nc->mgr->hexdump_file, len, ev);
542 nc->callback(nc, ev, p);
545 static void ns_destroy_conn(struct ns_connection *conn) {
546 closesocket(conn->sock);
547 iobuf_free(&conn->recv_iobuf);
548 iobuf_free(&conn->send_iobuf);
550 if (conn->ssl != NULL) {
553 if (conn->ssl_ctx != NULL) {
554 SSL_CTX_free(conn->ssl_ctx);
560 static void ns_close_conn(struct ns_connection *conn) {
561 DBG(("%p %d", conn, conn->flags));
562 ns_call(conn, NS_CLOSE, NULL);
563 ns_remove_conn(conn);
564 ns_destroy_conn(conn);
567 void ns_set_close_on_exec(sock_t sock) {
569 (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
571 fcntl(sock, F_SETFD, FD_CLOEXEC);
575 static void ns_set_non_blocking_mode(sock_t sock) {
577 unsigned long on = 1;
578 ioctlsocket(sock, FIONBIO, &on);
580 int flags = fcntl(sock, F_GETFL, 0);
581 fcntl(sock, F_SETFL, flags | O_NONBLOCK);
585 #ifndef NS_DISABLE_SOCKETPAIR
586 int ns_socketpair2(sock_t sp[2], int sock_type) {
587 union socket_address sa;
589 socklen_t len = sizeof(sa.sin);
592 sp[0] = sp[1] = INVALID_SOCKET;
594 (void) memset(&sa, 0, sizeof(sa));
595 sa.sin.sin_family = AF_INET;
596 sa.sin.sin_port = htons(0);
597 sa.sin.sin_addr.s_addr = htonl(0x7f000001);
599 if ((sock = socket(AF_INET, sock_type, 0)) != INVALID_SOCKET &&
600 !bind(sock, &sa.sa, len) &&
601 (sock_type == SOCK_DGRAM || !listen(sock, 1)) &&
602 !getsockname(sock, &sa.sa, &len) &&
603 (sp[0] = socket(AF_INET, sock_type, 0)) != INVALID_SOCKET &&
604 !connect(sp[0], &sa.sa, len) &&
605 (sock_type == SOCK_STREAM ||
606 (!getsockname(sp[0], &sa.sa, &len) && !connect(sock, &sa.sa, len))) &&
607 (sp[1] = (sock_type == SOCK_DGRAM ? sock :
608 accept(sock, &sa.sa, &len))) != INVALID_SOCKET) {
609 ns_set_close_on_exec(sp[0]);
610 ns_set_close_on_exec(sp[1]);
613 if (sp[0] != INVALID_SOCKET) closesocket(sp[0]);
614 if (sp[1] != INVALID_SOCKET) closesocket(sp[1]);
615 sp[0] = sp[1] = INVALID_SOCKET;
617 if (sock_type != SOCK_DGRAM) closesocket(sock);
622 int ns_socketpair(sock_t sp[2]) {
623 return ns_socketpair2(sp, SOCK_STREAM);
625 #endif // NS_DISABLE_SOCKETPAIR
627 // TODO(lsm): use non-blocking resolver
628 static int ns_resolve2(const char *host, struct in_addr *ina) {
629 #ifdef NS_ENABLE_GETADDRINFO
631 struct addrinfo hints, *servinfo, *p;
632 struct sockaddr_in *h = NULL;
634 memset(&hints, 0, sizeof hints);
635 hints.ai_family = AF_INET;
636 hints.ai_socktype = SOCK_STREAM;
638 if((rv = getaddrinfo(host, NULL , NULL, &servinfo)) != 0) {
639 DBG(("getaddrinfo(%s) failed: %s", host, strerror(errno)));
643 for(p = servinfo; p != NULL; p = p->ai_next) {
644 memcpy(&h, &p->ai_addr, sizeof(struct sockaddr_in *));
645 memcpy(ina, &h->sin_addr, sizeof(ina));
648 freeaddrinfo(servinfo);
652 if ((he = gethostbyname(host)) == NULL) {
653 DBG(("gethostbyname(%s) failed: %s", host, strerror(errno)));
655 memcpy(ina, he->h_addr_list[0], sizeof(*ina));
662 // Resolve FDQN "host", store IP address in the "ip".
663 // Return > 0 (IP address length) on success.
664 int ns_resolve(const char *host, char *buf, size_t n) {
666 return ns_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0;
669 // Address format: [PROTO://][IP_ADDRESS:]PORT[:CERT][:CA_CERT]
670 static int ns_parse_address(const char *str, union socket_address *sa,
671 int *proto, int *use_ssl, char *cert, char *ca) {
672 unsigned int a, b, c, d, port;
675 #ifdef NS_ENABLE_IPV6
679 // MacOS needs that. If we do not zero it, subsequent bind() will fail.
680 // Also, all-zeroes in the socket address means binding to all addresses
681 // for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
682 memset(sa, 0, sizeof(*sa));
683 sa->sin.sin_family = AF_INET;
685 *proto = SOCK_STREAM;
687 cert[0] = ca[0] = '\0';
689 if (memcmp(str, "ssl://", 6) == 0) {
692 } else if (memcmp(str, "udp://", 6) == 0) {
695 } else if (memcmp(str, "tcp://", 6) == 0) {
699 if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
700 // Bind to a specific IPv4 address, e.g. 192.168.1.5:8080
701 sa->sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
702 sa->sin.sin_port = htons((uint16_t) port);
703 #ifdef NS_ENABLE_IPV6
704 } else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 &&
705 inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
706 // IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080
707 sa->sin6.sin6_family = AF_INET6;
708 sa->sin6.sin6_port = htons((uint16_t) port);
710 } else if (sscanf(str, "%199[^ :]:%u%n", host, &port, &len) == 2) {
711 sa->sin.sin_port = htons((uint16_t) port);
712 ns_resolve2(host, &sa->sin.sin_addr);
713 } else if (sscanf(str, "%u%n", &port, &len) == 1) {
714 // If only port is specified, bind to IPv4, INADDR_ANY
715 sa->sin.sin_port = htons((uint16_t) port);
718 if (*use_ssl && (sscanf(str + len, ":%99[^:,]:%99[^:,]%n", cert, ca, &n) == 2 ||
719 sscanf(str + len, ":%99[^:,]%n", cert, &n) == 1)) {
723 return port < 0xffff && str[len] == '\0' ? len : 0;
726 // 'sa' must be an initialized address to bind to
727 static sock_t ns_open_listening_socket(union socket_address *sa, int proto) {
728 socklen_t sa_len = (sa->sa.sa_family == AF_INET) ?
729 sizeof(sa->sin) : sizeof(sa->sin6);
730 sock_t sock = INVALID_SOCKET;
735 if ((sock = socket(sa->sa.sa_family, proto, 0)) != INVALID_SOCKET &&
737 // SO_RESUSEADDR is not enabled on Windows because the semantics of
738 // SO_REUSEADDR on UNIX and Windows is different. On Windows,
739 // SO_REUSEADDR allows to bind a socket to a port without error even if
740 // the port is already open by another program. This is not the behavior
741 // SO_REUSEADDR was designed for, and leads to hard-to-track failure
742 // scenarios. Therefore, SO_REUSEADDR was disabled on Windows.
743 !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) &&
745 !bind(sock, &sa->sa, sa_len) &&
746 (proto == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) {
747 ns_set_non_blocking_mode(sock);
748 // In case port was set to 0, get the real port number
749 (void) getsockname(sock, &sa->sa, &sa_len);
750 } else if (sock != INVALID_SOCKET) {
752 sock = INVALID_SOCKET;
759 // Certificate generation script is at
760 // https://github.com/cesanta/net_skeleton/blob/master/scripts/gen_certs.sh
762 static int ns_use_ca_cert(SSL_CTX *ctx, const char *cert) {
765 } else if (cert == NULL || cert[0] == '\0') {
768 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
769 return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? 0 : -2;
772 static int ns_use_cert(SSL_CTX *ctx, const char *pem_file) {
775 } else if (pem_file == NULL || pem_file[0] == '\0') {
777 } else if (SSL_CTX_use_certificate_file(ctx, pem_file, 1) == 0 ||
778 SSL_CTX_use_PrivateKey_file(ctx, pem_file, 1) == 0) {
781 SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
782 SSL_CTX_use_certificate_chain_file(ctx, pem_file);
786 #endif // NS_ENABLE_SSL
788 struct ns_connection *ns_bind(struct ns_mgr *srv, const char *str,
789 ns_callback_t callback, void *user_data) {
790 union socket_address sa;
791 struct ns_connection *nc = NULL;
793 char cert[100], ca_cert[100];
796 ns_parse_address(str, &sa, &proto, &use_ssl, cert, ca_cert);
797 if (use_ssl && cert[0] == '\0') return NULL;
799 if ((sock = ns_open_listening_socket(&sa, proto)) == INVALID_SOCKET) {
800 } else if ((nc = ns_add_sock(srv, sock, callback, NULL)) == NULL) {
804 nc->flags |= NSF_LISTENING;
805 nc->user_data = user_data;
806 nc->callback = callback;
808 if (proto == SOCK_DGRAM) {
809 nc->flags |= NSF_UDP;
814 nc->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
815 if (ns_use_cert(nc->ssl_ctx, cert) != 0 ||
816 ns_use_ca_cert(nc->ssl_ctx, ca_cert) != 0) {
823 DBG(("%p sock %d/%d ssl %p %p", nc, sock, proto, nc->ssl_ctx, nc->ssl));
829 static struct ns_connection *accept_conn(struct ns_connection *ls) {
830 struct ns_connection *c = NULL;
831 union socket_address sa;
832 socklen_t len = sizeof(sa);
833 sock_t sock = INVALID_SOCKET;
835 // NOTE(lsm): on Windows, sock is always > FD_SETSIZE
836 if ((sock = accept(ls->sock, &sa.sa, &len)) == INVALID_SOCKET) {
837 } else if ((c = ns_add_sock(ls->mgr, sock, ls->callback,
838 ls->user_data)) == NULL) {
841 } else if (ls->ssl_ctx != NULL &&
842 ((c->ssl = SSL_new(ls->ssl_ctx)) == NULL ||
843 SSL_set_fd(c->ssl, sock) != 1)) {
850 c->proto_data = ls->proto_data;
851 ns_call(c, NS_ACCEPT, &sa);
852 DBG(("%p %d %p %p", c, c->sock, c->ssl_ctx, c->ssl));
858 static int ns_is_error(int n) {
860 (n < 0 && errno != EINTR && errno != EINPROGRESS &&
861 errno != EAGAIN && errno != EWOULDBLOCK
863 && WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK
868 void ns_sock_to_str(sock_t sock, char *buf, size_t len, int flags) {
869 union socket_address sa;
870 socklen_t slen = sizeof(sa);
872 if (buf != NULL && len > 0) {
874 memset(&sa, 0, sizeof(sa));
876 getpeername(sock, &sa.sa, &slen);
878 getsockname(sock, &sa.sa, &slen);
881 #if defined(NS_ENABLE_IPV6)
882 inet_ntop(sa.sa.sa_family, sa.sa.sa_family == AF_INET ?
883 (void *) &sa.sin.sin_addr :
884 (void *) &sa.sin6.sin6_addr, buf, len);
885 #elif defined(_WIN32)
886 // Only Windoze Vista (and newer) have inet_ntop()
887 strncpy(buf, inet_ntoa(sa.sin.sin_addr), len);
889 inet_ntop(sa.sa.sa_family, (void *) &sa.sin.sin_addr, buf,(socklen_t)len);
893 snprintf(buf + strlen(buf), len - (strlen(buf) + 1), "%s%d",
894 flags & 1 ? ":" : "", (int) ntohs(sa.sin.sin_port));
899 int ns_hexdump(const void *buf, int len, char *dst, int dst_len) {
900 const unsigned char *p = (const unsigned char *) buf;
904 for (i = 0; i < len; i++) {
907 if (i > 0) n += snprintf(dst + n, dst_len - n, " %s\n", ascii);
908 n += snprintf(dst + n, dst_len - n, "%04x ", i);
910 n += snprintf(dst + n, dst_len - n, " %02x", p[i]);
911 ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i];
912 ascii[idx + 1] = '\0';
915 while (i++ % 16) n += snprintf(dst + n, dst_len - n, "%s", " ");
916 n += snprintf(dst + n, dst_len - n, " %s\n\n", ascii);
922 static int ns_ssl_err(struct ns_connection *conn, int res) {
923 int ssl_err = SSL_get_error(conn->ssl, res);
924 if (ssl_err == SSL_ERROR_WANT_READ) conn->flags |= NSF_WANT_READ;
925 if (ssl_err == SSL_ERROR_WANT_WRITE) conn->flags |= NSF_WANT_WRITE;
930 static void ns_read_from_socket(struct ns_connection *conn) {
931 char buf[NS_READ_BUFFER_SIZE];
934 if (conn->flags & NSF_CONNECTING) {
936 socklen_t len = sizeof(ok);
938 ret = getsockopt(conn->sock, SOL_SOCKET, SO_ERROR, (char *) &ok, &len);
941 if (ret == 0 && ok == 0 && conn->ssl != NULL) {
942 int res = SSL_connect(conn->ssl);
943 int ssl_err = ns_ssl_err(conn, res);
945 conn->flags |= NSF_SSL_HANDSHAKE_DONE;
946 } else if (ssl_err == SSL_ERROR_WANT_READ ||
947 ssl_err == SSL_ERROR_WANT_WRITE) {
948 return; // Call us again
952 conn->flags &= ~(NSF_WANT_READ | NSF_WANT_WRITE);
955 conn->flags &= ~NSF_CONNECTING;
956 DBG(("%p ok=%d", conn, ok));
958 conn->flags |= NSF_CLOSE_IMMEDIATELY;
960 ns_call(conn, NS_CONNECT, &ok);
965 if (conn->ssl != NULL) {
966 if (conn->flags & NSF_SSL_HANDSHAKE_DONE) {
967 // SSL library may have more bytes ready to read then we ask to read.
968 // Therefore, read in a loop until we read everything. Without the loop,
969 // we skip to the next select() cycle which can just timeout.
970 while ((n = SSL_read(conn->ssl, buf, sizeof(buf))) > 0) {
971 DBG(("%p %d <- %d bytes (SSL)", conn, conn->flags, n));
972 iobuf_append(&conn->recv_iobuf, buf, n);
973 ns_call(conn, NS_RECV, &n);
977 int res = SSL_accept(conn->ssl);
978 int ssl_err = ns_ssl_err(conn, res);
980 conn->flags |= NSF_SSL_HANDSHAKE_DONE;
981 conn->flags &= ~(NSF_WANT_READ | NSF_WANT_WRITE);
982 } else if (ssl_err == SSL_ERROR_WANT_READ ||
983 ssl_err == SSL_ERROR_WANT_WRITE) {
984 return; // Call us again
986 conn->flags |= NSF_CLOSE_IMMEDIATELY;
993 while ((n = (int) recv(conn->sock, buf, sizeof(buf), 0)) > 0) {
994 DBG(("%p %d <- %d bytes (PLAIN)", conn, conn->flags, n));
995 iobuf_append(&conn->recv_iobuf, buf, n);
996 ns_call(conn, NS_RECV, &n);
1000 if (ns_is_error(n)) {
1001 conn->flags |= NSF_CLOSE_IMMEDIATELY;
1005 static void ns_write_to_socket(struct ns_connection *conn) {
1006 struct iobuf *io = &conn->send_iobuf;
1009 #ifdef NS_ENABLE_SSL
1010 if (conn->ssl != NULL) {
1011 n = SSL_write(conn->ssl, io->buf, io->len);
1013 int ssl_err = ns_ssl_err(conn, n);
1014 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
1015 return; // Call us again
1017 conn->flags |= NSF_CLOSE_IMMEDIATELY;
1020 conn->flags &= ~(NSF_WANT_READ | NSF_WANT_WRITE);
1024 { n = (int) send(conn->sock, io->buf, io->len, 0); }
1026 DBG(("%p %d -> %d bytes", conn, conn->flags, n));
1028 ns_call(conn, NS_SEND, &n);
1029 if (ns_is_error(n)) {
1030 conn->flags |= NSF_CLOSE_IMMEDIATELY;
1032 iobuf_remove(io, n);
1036 int ns_send(struct ns_connection *conn, const void *buf, size_t len) {
1037 return (int) ns_out(conn, buf, len);
1040 static void ns_handle_udp(struct ns_connection *ls) {
1041 struct ns_connection nc;
1042 char buf[NS_UDP_RECEIVE_BUFFER_SIZE];
1044 socklen_t s_len = sizeof(nc.sa);
1046 memset(&nc, 0, sizeof(nc));
1047 n = recvfrom(ls->sock, buf, sizeof(buf), 0, &nc.sa.sa, &s_len);
1049 DBG(("%p recvfrom: %s", ls, strerror(errno)));
1052 nc.recv_iobuf.buf = buf;
1053 nc.recv_iobuf.len = nc.recv_iobuf.size = n;
1055 nc.callback = ls->callback;
1056 nc.user_data = ls->user_data;
1057 nc.proto_data = ls->proto_data;
1061 DBG(("%p %d bytes received", ls, n));
1062 ns_call(&nc, NS_RECV, &n);
1066 static void ns_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) {
1067 if ( (sock != INVALID_SOCKET) && (sock < FD_SETSIZE) ) {
1069 if (*max_fd == INVALID_SOCKET || sock > *max_fd) {
1075 time_t ns_mgr_poll(struct ns_mgr *mgr, int milli) {
1076 struct ns_connection *conn, *tmp_conn;
1078 fd_set read_set, write_set;
1079 sock_t max_fd = INVALID_SOCKET;
1080 time_t current_time = time(NULL);
1083 FD_ZERO(&write_set);
1084 ns_add_to_set(mgr->ctl[1], &read_set, &max_fd);
1086 for (conn = mgr->active_connections; conn != NULL; conn = tmp_conn) {
1087 tmp_conn = conn->next;
1088 if (!(conn->flags & (NSF_LISTENING | NSF_CONNECTING))) {
1089 ns_call(conn, NS_POLL, ¤t_time);
1091 if (conn->flags & NSF_CLOSE_IMMEDIATELY) {
1092 ns_close_conn(conn);
1094 if (!(conn->flags & NSF_WANT_WRITE)) {
1095 //DBG(("%p read_set", conn));
1096 ns_add_to_set(conn->sock, &read_set, &max_fd);
1098 if (((conn->flags & NSF_CONNECTING) && !(conn->flags & NSF_WANT_READ)) ||
1099 (conn->send_iobuf.len > 0 && !(conn->flags & NSF_CONNECTING) &&
1100 !(conn->flags & NSF_BUFFER_BUT_DONT_SEND))) {
1101 //DBG(("%p write_set", conn));
1102 ns_add_to_set(conn->sock, &write_set, &max_fd);
1107 tv.tv_sec = milli / 1000;
1108 tv.tv_usec = (milli % 1000) * 1000;
1110 if (select((int) max_fd + 1, &read_set, &write_set, NULL, &tv) > 0) {
1111 // select() might have been waiting for a long time, reset current_time
1112 // now to prevent last_io_time being set to the past.
1113 current_time = time(NULL);
1115 // Read wakeup messages
1116 if (mgr->ctl[1] != INVALID_SOCKET &&
1117 FD_ISSET(mgr->ctl[1], &read_set)) {
1118 struct ctl_msg ctl_msg;
1119 int len = (int) recv(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0);
1120 send(mgr->ctl[1], ctl_msg.message, 1, 0);
1121 if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) {
1122 struct ns_connection *c;
1123 for (c = ns_next(mgr, NULL); c != NULL; c = ns_next(mgr, c)) {
1124 ctl_msg.callback(c, NS_POLL, ctl_msg.message);
1129 for (conn = mgr->active_connections; conn != NULL; conn = tmp_conn) {
1130 tmp_conn = conn->next;
1131 if (FD_ISSET(conn->sock, &read_set)) {
1132 if (conn->flags & NSF_LISTENING) {
1133 if (conn->flags & NSF_UDP) {
1134 ns_handle_udp(conn);
1136 // We're not looping here, and accepting just one connection at
1137 // a time. The reason is that eCos does not respect non-blocking
1138 // flag on a listening socket and hangs in a loop.
1142 conn->last_io_time = current_time;
1143 ns_read_from_socket(conn);
1147 if (FD_ISSET(conn->sock, &write_set)) {
1148 if (conn->flags & NSF_CONNECTING) {
1149 ns_read_from_socket(conn);
1150 } else if (!(conn->flags & NSF_BUFFER_BUT_DONT_SEND)) {
1151 conn->last_io_time = current_time;
1152 ns_write_to_socket(conn);
1158 for (conn = mgr->active_connections; conn != NULL; conn = tmp_conn) {
1159 tmp_conn = conn->next;
1160 if ((conn->flags & NSF_CLOSE_IMMEDIATELY) ||
1161 (conn->send_iobuf.len == 0 &&
1162 (conn->flags & NSF_FINISHED_SENDING_DATA))) {
1163 ns_close_conn(conn);
1167 return current_time;
1170 struct ns_connection *ns_connect(struct ns_mgr *mgr, const char *address,
1171 ns_callback_t callback, void *user_data) {
1172 sock_t sock = INVALID_SOCKET;
1173 struct ns_connection *nc = NULL;
1174 union socket_address sa;
1175 char cert[100], ca_cert[100];
1176 int rc, use_ssl, proto;
1178 ns_parse_address(address, &sa, &proto, &use_ssl, cert, ca_cert);
1179 if ((sock = socket(AF_INET, proto, 0)) == INVALID_SOCKET) {
1182 ns_set_non_blocking_mode(sock);
1183 rc = (proto == SOCK_DGRAM) ? 0 : connect(sock, &sa.sa, sizeof(sa.sin));
1185 if (rc != 0 && ns_is_error(rc)) {
1188 } else if ((nc = ns_add_sock(mgr, sock, callback, user_data)) == NULL) {
1193 nc->sa = sa; // Important, cause UDP conns will use sendto()
1194 nc->flags = (proto == SOCK_DGRAM) ? NSF_UDP : NSF_CONNECTING;
1196 #ifdef NS_ENABLE_SSL
1198 if ((nc->ssl_ctx = SSL_CTX_new(SSLv23_client_method())) == NULL ||
1199 ns_use_cert(nc->ssl_ctx, cert) != 0 ||
1200 ns_use_ca_cert(nc->ssl_ctx, ca_cert) != 0 ||
1201 (nc->ssl = SSL_new(nc->ssl_ctx)) == NULL) {
1205 SSL_set_fd(nc->ssl, sock);
1213 struct ns_connection *ns_add_sock(struct ns_mgr *s, sock_t sock,
1214 ns_callback_t callback, void *user_data) {
1215 struct ns_connection *conn;
1216 if ((conn = (struct ns_connection *) NS_MALLOC(sizeof(*conn))) != NULL) {
1217 memset(conn, 0, sizeof(*conn));
1218 ns_set_non_blocking_mode(sock);
1219 ns_set_close_on_exec(sock);
1221 conn->user_data = user_data;
1222 conn->callback = callback;
1224 conn->last_io_time = time(NULL);
1225 ns_add_conn(s, conn);
1226 DBG(("%p %d", conn, sock));
1231 struct ns_connection *ns_next(struct ns_mgr *s, struct ns_connection *conn) {
1232 return conn == NULL ? s->active_connections : conn->next;
1235 void ns_broadcast(struct ns_mgr *mgr, ns_callback_t cb,void *data, size_t len) {
1236 struct ctl_msg ctl_msg;
1237 if (mgr->ctl[0] != INVALID_SOCKET && data != NULL &&
1238 len < sizeof(ctl_msg.message)) {
1239 ctl_msg.callback = cb;
1240 memcpy(ctl_msg.message, data, len);
1241 send(mgr->ctl[0], (char *) &ctl_msg,
1242 offsetof(struct ctl_msg, message) + len, 0);
1243 recv(mgr->ctl[0], (char *) &len, 1, 0);
1247 void ns_mgr_init(struct ns_mgr *s, void *user_data) {
1248 memset(s, 0, sizeof(*s));
1249 s->ctl[0] = s->ctl[1] = INVALID_SOCKET;
1250 s->user_data = user_data;
1253 { WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); }
1255 // Ignore SIGPIPE signal, so if client cancels the request, it
1256 // won't kill the whole process.
1257 signal(SIGPIPE, SIG_IGN);
1260 #ifndef NS_DISABLE_SOCKETPAIR
1262 ns_socketpair2(s->ctl, SOCK_DGRAM);
1263 } while (s->ctl[0] == INVALID_SOCKET);
1266 #ifdef NS_ENABLE_SSL
1267 {static int init_done; if (!init_done) { SSL_library_init(); init_done++; }}
1271 void ns_mgr_free(struct ns_mgr *s) {
1272 struct ns_connection *conn, *tmp_conn;
1275 if (s == NULL) return;
1276 // Do one last poll, see https://github.com/cesanta/mongoose/issues/286
1279 if (s->ctl[0] != INVALID_SOCKET) closesocket(s->ctl[0]);
1280 if (s->ctl[1] != INVALID_SOCKET) closesocket(s->ctl[1]);
1281 s->ctl[0] = s->ctl[1] = INVALID_SOCKET;
1283 for (conn = s->active_connections; conn != NULL; conn = tmp_conn) {
1284 tmp_conn = conn->next;
1285 ns_close_conn(conn);
1289 #endif // NOEMBED_NET_SKELETON
1293 #ifdef _WIN32 //////////////// Windows specific defines and includes
1294 #include <io.h> // For _lseeki64
1295 #include <direct.h> // For _mkdir
1297 #define S_ISDIR(x) ((x) & _S_IFDIR)
1311 #define stat(x, y) mg_stat((x), (y))
1312 #define fopen(x, y) mg_fopen((x), (y))
1313 #define open(x, y, z) mg_open((x), (y), (z))
1314 #define close(x) _close(x)
1315 #define fileno(x) _fileno(x)
1316 #define lseek(x, y, z) _lseeki64((x), (y), (z))
1317 #define read(x, y, z) _read((x), (y), (z))
1318 #define write(x, y, z) _write((x), (y), (z))
1319 #define popen(x, y) _popen((x), (y))
1320 #define pclose(x) _pclose(x)
1321 #define mkdir(x, y) _mkdir(x)
1322 #define rmdir(x) _rmdir(x)
1323 #define strdup(x) _strdup(x)
1326 #define STR(x) STRX(x)
1327 #define __func__ __FILE__ ":" STR(__LINE__)
1329 #define INT64_FMT "I64d"
1330 #define flockfile(x) ((void) (x))
1331 #define funlockfile(x) ((void) (x))
1332 typedef struct _stati64 file_stat_t;
1333 typedef HANDLE process_id_t;
1335 #else ////////////// UNIX specific defines and includes
1337 #if !defined(MONGOOSE_NO_FILESYSTEM) &&\
1338 (!defined(MONGOOSE_NO_DAV) || !defined(MONGOOSE_NO_DIRECTORY_LISTING))
1341 #if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_DL)
1344 #include <inttypes.h>
1346 #if !defined(O_BINARY)
1349 #define INT64_FMT PRId64
1350 typedef struct stat file_stat_t;
1351 typedef pid_t process_id_t;
1352 #endif //////// End of platform-specific defines and includes
1354 #include "mongoose.h"
1356 #define MAX_REQUEST_SIZE 16384
1357 #define IOBUF_SIZE 8192
1358 #define MAX_PATH_SIZE 8192
1359 #define DEFAULT_CGI_PATTERN "**.cgi$|**.pl$|**.php$"
1360 #define CGI_ENVIRONMENT_SIZE 8192
1361 #define MAX_CGI_ENVIR_VARS 64
1362 #define ENV_EXPORT_TO_CGI "MONGOOSE_CGI"
1363 #define PASSWORDS_FILE_NAME ".htpasswd"
1365 #ifndef MONGOOSE_USE_WEBSOCKET_PING_INTERVAL
1366 #define MONGOOSE_USE_WEBSOCKET_PING_INTERVAL 5
1369 // Extra HTTP headers to send in every static file reply
1370 #if !defined(MONGOOSE_USE_EXTRA_HTTP_HEADERS)
1371 #define MONGOOSE_USE_EXTRA_HTTP_HEADERS ""
1374 #ifndef MONGOOSE_POST_SIZE_LIMIT
1375 #define MONGOOSE_POST_SIZE_LIMIT 0
1378 #ifndef MONGOOSE_IDLE_TIMEOUT_SECONDS
1379 #define MONGOOSE_IDLE_TIMEOUT_SECONDS 300
1382 #if defined(NS_DISABLE_SOCKETPAIR) && !defined(MONGOOSE_NO_CGI)
1383 #define MONGOOSE_NO_CGI
1386 #ifdef MONGOOSE_NO_FILESYSTEM
1387 #define MONGOOSE_NO_AUTH
1388 #if !defined(MONGOOSE_NO_CGI)
1389 #define MONGOOSE_NO_CGI
1391 #define MONGOOSE_NO_DAV
1392 #define MONGOOSE_NO_DIRECTORY_LISTING
1393 #define MONGOOSE_NO_LOGGING
1394 #define MONGOOSE_NO_SSI
1395 #define MONGOOSE_NO_DL
1403 // For directory listing and WevDAV support
1405 struct connection *conn;
1410 // NOTE(lsm): this enum should be in sync with the config_options.
1412 ACCESS_CONTROL_LIST,
1413 #ifndef MONGOOSE_NO_FILESYSTEM
1415 #ifndef MONGOOSE_NO_AUTH
1418 #ifndef MONGOOSE_NO_CGI
1425 #ifndef MONGOOSE_NO_DIRECTORY_LISTING
1426 ENABLE_DIRECTORY_LISTING,
1431 #if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_AUTH)
1434 #ifndef MONGOOSE_NO_FILESYSTEM
1443 #ifndef MONGOOSE_NO_SSI
1450 static const char *static_config_options[] = {
1451 "access_control_list", NULL,
1452 #ifndef MONGOOSE_NO_FILESYSTEM
1453 "access_log_file", NULL,
1454 #ifndef MONGOOSE_NO_AUTH
1455 "auth_domain", "mydomain.com",
1457 #ifndef MONGOOSE_NO_CGI
1458 "cgi_interpreter", NULL,
1459 "cgi_pattern", DEFAULT_CGI_PATTERN,
1461 "dav_auth_file", NULL,
1463 "document_root", NULL,
1464 #ifndef MONGOOSE_NO_DIRECTORY_LISTING
1465 "enable_directory_listing", "yes",
1468 "enable_proxy", NULL,
1469 "extra_mime_types", NULL,
1470 #if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_AUTH)
1471 "global_auth_file", NULL,
1473 #ifndef MONGOOSE_NO_FILESYSTEM
1474 "hide_files_patterns", NULL,
1475 "hexdump_file", NULL,
1476 "index_files","index.html,index.htm,index.shtml,index.cgi,index.php",
1478 "listening_port", NULL,
1480 "run_as_user", NULL,
1482 #ifndef MONGOOSE_NO_SSI
1483 "ssi_pattern", "**.shtml$|**.shtm$",
1485 "url_rewrites", NULL,
1490 struct ns_mgr ns_mgr;
1491 union socket_address lsa; // Listening socket address
1492 mg_handler_t event_handler;
1493 char *config_options[NUM_OPTIONS];
1496 // Local endpoint representation
1498 int fd; // Opened regular local file
1499 struct ns_connection *nc; // CGI or proxy->target connection
1502 enum endpoint_type {
1503 EP_NONE, EP_FILE, EP_CGI, EP_USER, EP_PUT, EP_CLIENT, EP_PROXY
1506 #define MG_HEADERS_SENT NSF_USER_1
1507 #define MG_USING_CHUNKED_API NSF_USER_2
1508 #define MG_CGI_CONN NSF_USER_3
1509 #define MG_PROXY_CONN NSF_USER_4
1510 #define MG_PROXY_DONT_PARSE NSF_USER_5
1513 struct ns_connection *ns_conn; // NOTE(lsm): main.c depends on this order
1514 struct mg_connection mg_conn;
1515 struct mg_server *server;
1516 union endpoint endpoint;
1517 enum endpoint_type endpoint_type;
1520 int64_t num_bytes_recv; // Total number of bytes received
1521 int64_t cl; // Reply content length, for Range support
1522 ssize_t request_len; // Request length, including last \r\n after last header
1525 #define MG_CONN_2_CONN(c) ((struct connection *) ((char *) (c) - \
1526 offsetof(struct connection, mg_conn)))
1528 static void open_local_endpoint(struct connection *conn, int skip_user);
1529 static void close_local_endpoint(struct connection *conn);
1530 static void mg_ev_handler(struct ns_connection *nc, int ev, void *p);
1532 static const struct {
1533 const char *extension;
1535 const char *mime_type;
1536 } static_builtin_mime_types[] = {
1537 {".html", 5, "text/html"},
1538 {".htm", 4, "text/html"},
1539 {".shtm", 5, "text/html"},
1540 {".shtml", 6, "text/html"},
1541 {".css", 4, "text/css"},
1542 {".js", 3, "application/javascript"},
1543 {".ico", 4, "image/x-icon"},
1544 {".gif", 4, "image/gif"},
1545 {".jpg", 4, "image/jpeg"},
1546 {".jpeg", 5, "image/jpeg"},
1547 {".png", 4, "image/png"},
1548 {".svg", 4, "image/svg+xml"},
1549 {".txt", 4, "text/plain"},
1550 {".torrent", 8, "application/x-bittorrent"},
1551 {".wav", 4, "audio/x-wav"},
1552 {".mp3", 4, "audio/x-mp3"},
1553 {".mid", 4, "audio/mid"},
1554 {".m3u", 4, "audio/x-mpegurl"},
1555 {".ogg", 4, "application/ogg"},
1556 {".ram", 4, "audio/x-pn-realaudio"},
1557 {".xml", 4, "text/xml"},
1558 {".json", 5, "application/json"},
1559 {".xslt", 5, "application/xml"},
1560 {".xsl", 4, "application/xml"},
1561 {".ra", 3, "audio/x-pn-realaudio"},
1562 {".doc", 4, "application/msword"},
1563 {".exe", 4, "application/octet-stream"},
1564 {".zip", 4, "application/x-zip-compressed"},
1565 {".xls", 4, "application/excel"},
1566 {".tgz", 4, "application/x-tar-gz"},
1567 {".tar", 4, "application/x-tar"},
1568 {".gz", 3, "application/x-gunzip"},
1569 {".arj", 4, "application/x-arj-compressed"},
1570 {".rar", 4, "application/x-rar-compressed"},
1571 {".rtf", 4, "application/rtf"},
1572 {".pdf", 4, "application/pdf"},
1573 {".swf", 4, "application/x-shockwave-flash"},
1574 {".mpg", 4, "video/mpeg"},
1575 {".webm", 5, "video/webm"},
1576 {".mpeg", 5, "video/mpeg"},
1577 {".mov", 4, "video/quicktime"},
1578 {".mp4", 4, "video/mp4"},
1579 {".m4v", 4, "video/x-m4v"},
1580 {".asf", 4, "video/x-ms-asf"},
1581 {".avi", 4, "video/x-msvideo"},
1582 {".bmp", 4, "image/bmp"},
1583 {".ttf", 4, "application/x-font-ttf"},
1587 #ifdef MONGOOSE_ENABLE_THREADS
1588 void *mg_start_thread(void *(*f)(void *), void *p) {
1589 return ns_start_thread(f, p);
1591 #endif // MONGOOSE_ENABLE_THREADS
1593 #ifndef MONGOOSE_NO_MMAP
1595 static void *mmap(void *addr, int64_t len, int prot, int flags, int fd,
1597 HANDLE fh = (HANDLE) _get_osfhandle(fd);
1598 HANDLE mh = CreateFileMapping(fh, 0, PAGE_READONLY, 0, 0, 0);
1599 void *p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, (size_t) len);
1603 #define munmap(x, y) UnmapViewOfFile(x)
1604 #define MAP_FAILED NULL
1605 #define MAP_PRIVATE 0
1607 #elif defined(__OS2__)
1608 static void *mmap(void *addr, int64_t len, int prot, int flags, int fd,
1612 int pos = lseek( fd, 0, SEEK_CUR ); /* Get a current position */
1617 /* Seek to offset offset */
1618 if (lseek( fd, offset, SEEK_SET) == -1)
1623 /* Read in a file */
1624 if (!p || read(fd, p, len) == -1) {
1629 /* Restore the position */
1630 lseek(fd, pos, SEEK_SET);
1634 #define munmap(x, y) free(x)
1635 #define MAP_FAILED NULL
1636 #define MAP_PRIVATE 0
1639 #include <sys/mman.h>
1642 void *mg_mmap(FILE *fp, size_t size) {
1643 void *p = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fileno(fp), 0);
1644 return p == MAP_FAILED ? NULL : p;
1647 void mg_munmap(void *p, size_t size) {
1650 #endif // MONGOOSE_NO_MMAP
1652 #if defined(_WIN32) && !defined(MONGOOSE_NO_FILESYSTEM)
1653 // Encode 'path' which is assumed UTF-8 string, into UNICODE string.
1654 // wbuf and wbuf_len is a target buffer and its length.
1655 static void to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
1656 char buf[MAX_PATH_SIZE * 2], buf2[MAX_PATH_SIZE * 2], *p;
1658 strncpy(buf, path, sizeof(buf));
1659 buf[sizeof(buf) - 1] = '\0';
1661 // Trim trailing slashes. Leave backslash for paths like "X:\"
1662 p = buf + strlen(buf) - 1;
1663 while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
1665 // Convert to Unicode and back. If doubly-converted string does not
1666 // match the original, something is fishy, reject.
1667 memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
1668 MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
1669 WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
1671 if (strcmp(buf, buf2) != 0) {
1676 static int mg_stat(const char *path, file_stat_t *st) {
1677 wchar_t wpath[MAX_PATH_SIZE];
1678 to_wchar(path, wpath, ARRAY_SIZE(wpath));
1679 DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
1680 return _wstati64(wpath, st);
1683 static FILE *mg_fopen(const char *path, const char *mode) {
1684 wchar_t wpath[MAX_PATH_SIZE], wmode[10];
1685 to_wchar(path, wpath, ARRAY_SIZE(wpath));
1686 to_wchar(mode, wmode, ARRAY_SIZE(wmode));
1687 return _wfopen(wpath, wmode);
1690 static int mg_open(const char *path, int flag, int mode) {
1691 wchar_t wpath[MAX_PATH_SIZE];
1692 to_wchar(path, wpath, ARRAY_SIZE(wpath));
1693 return _wopen(wpath, flag, mode);
1695 #endif // _WIN32 && !MONGOOSE_NO_FILESYSTEM
1697 // A helper function for traversing a comma separated list of values.
1698 // It returns a list pointer shifted to the next value, or NULL if the end
1699 // of the list found.
1700 // Value is stored in val vector. If value has form "x=y", then eq_val
1701 // vector is initialized to point to the "y" part, and val vector length
1702 // is adjusted to point only to "x".
1703 static const char *next_option(const char *list, struct vec *val,
1704 struct vec *eq_val) {
1705 if (list == NULL || *list == '\0') {
1710 if ((list = strchr(val->ptr, ',')) != NULL) {
1711 // Comma found. Store length and shift the list ptr
1712 val->len = list - val->ptr;
1715 // This value is the last one
1716 list = val->ptr + strlen(val->ptr);
1717 val->len = list - val->ptr;
1720 if (eq_val != NULL) {
1721 // Value has form "x=y", adjust pointers and lengths
1722 // so that val points to "x", and eq_val points to "y".
1724 eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);
1725 if (eq_val->ptr != NULL) {
1726 eq_val->ptr++; // Skip over '=' character
1727 eq_val->len = val->ptr + val->len - eq_val->ptr;
1728 val->len = (eq_val->ptr - val->ptr) - 1;
1736 // Like snprintf(), but never returns negative value, or a value
1737 // that is larger than a supplied buffer.
1738 static int mg_vsnprintf(char *buf, size_t buflen, const char *fmt, va_list ap) {
1740 if (buflen < 1) return 0;
1741 n = vsnprintf(buf, buflen, fmt, ap);
1744 } else if (n >= (int) buflen) {
1745 n = (int) buflen - 1;
1751 static int mg_snprintf(char *buf, size_t buflen, const char *fmt, ...) {
1755 n = mg_vsnprintf(buf, buflen, fmt, ap);
1760 // Check whether full request is buffered. Return:
1761 // -1 if request is malformed
1762 // 0 if request is not yet fully buffered
1763 // >0 actual request length, including last \r\n\r\n
1764 static int get_request_len(const char *s, size_t buf_len) {
1765 const unsigned char *buf = (unsigned char *) s;
1768 for (i = 0; i < buf_len; i++) {
1769 // Control characters are not allowed but >=128 are.
1770 // Abort scan as soon as one malformed character is found.
1771 if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
1773 } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
1775 } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
1776 buf[i + 2] == '\n') {
1784 // Skip the characters until one of the delimiters characters found.
1785 // 0-terminate resulting word. Skip the rest of the delimiters if any.
1786 // Advance pointer to buffer to the next word. Return found 0-terminated word.
1787 static char *skip(char **buf, const char *delimiters) {
1788 char *p, *begin_word, *end_word, *end_delimiters;
1791 end_word = begin_word + strcspn(begin_word, delimiters);
1792 end_delimiters = end_word + strspn(end_word, delimiters);
1794 for (p = end_word; p < end_delimiters; p++) {
1798 *buf = end_delimiters;
1803 // Parse HTTP headers from the given buffer, advance buffer to the point
1804 // where parsing stopped.
1805 static void parse_http_headers(char **buf, struct mg_connection *ri) {
1808 for (i = 0; i < ARRAY_SIZE(ri->http_headers); i++) {
1809 ri->http_headers[i].name = skip(buf, ": ");
1810 ri->http_headers[i].value = skip(buf, "\r\n");
1811 if (ri->http_headers[i].name[0] == '\0')
1813 ri->num_headers = i + 1;
1817 static const char *status_code_to_str(int status_code) {
1818 switch (status_code) {
1820 case 100: return "Continue";
1821 case 101: return "Switching Protocols";
1822 case 102: return "Processing";
1824 case 200: return "OK";
1825 case 201: return "Created";
1826 case 202: return "Accepted";
1827 case 203: return "Non-Authoritative Information";
1828 case 204: return "No Content";
1829 case 205: return "Reset Content";
1830 case 206: return "Partial Content";
1831 case 207: return "Multi-Status";
1832 case 208: return "Already Reported";
1833 case 226: return "IM Used";
1835 case 300: return "Multiple Choices";
1836 case 301: return "Moved Permanently";
1837 case 302: return "Found";
1838 case 303: return "See Other";
1839 case 304: return "Not Modified";
1840 case 305: return "Use Proxy";
1841 case 306: return "Switch Proxy";
1842 case 307: return "Temporary Redirect";
1843 case 308: return "Permanent Redirect";
1845 case 400: return "Bad Request";
1846 case 401: return "Unauthorized";
1847 case 402: return "Payment Required";
1848 case 403: return "Forbidden";
1849 case 404: return "Not Found";
1850 case 405: return "Method Not Allowed";
1851 case 406: return "Not Acceptable";
1852 case 407: return "Proxy Authentication Required";
1853 case 408: return "Request Timeout";
1854 case 409: return "Conflict";
1855 case 410: return "Gone";
1856 case 411: return "Length Required";
1857 case 412: return "Precondition Failed";
1858 case 413: return "Payload Too Large";
1859 case 414: return "URI Too Long";
1860 case 415: return "Unsupported Media Type";
1861 case 416: return "Requested Range Not Satisfiable";
1862 case 417: return "Expectation Failed";
1863 case 418: return "I\'m a teapot";
1864 case 422: return "Unprocessable Entity";
1865 case 423: return "Locked";
1866 case 424: return "Failed Dependency";
1867 case 426: return "Upgrade Required";
1868 case 428: return "Precondition Required";
1869 case 429: return "Too Many Requests";
1870 case 431: return "Request Header Fields Too Large";
1871 case 451: return "Unavailable For Legal Reasons";
1873 case 500: return "Internal Server Error";
1874 case 501: return "Not Implemented";
1875 case 502: return "Bad Gateway";
1876 case 503: return "Service Unavailable";
1877 case 504: return "Gateway Timeout";
1878 case 505: return "HTTP Version Not Supported";
1879 case 506: return "Variant Also Negotiates";
1880 case 507: return "Insufficient Storage";
1881 case 508: return "Loop Detected";
1882 case 510: return "Not Extended";
1883 case 511: return "Network Authentication Required";
1885 default: return "Server Error";
1889 static int call_user(struct connection *conn, enum mg_event ev) {
1890 return conn != NULL && conn->server != NULL &&
1891 conn->server->event_handler != NULL ?
1892 conn->server->event_handler(&conn->mg_conn, ev) : MG_FALSE;
1895 static void send_http_error(struct connection *conn, int code,
1896 const char *fmt, ...) {
1897 const char *message = status_code_to_str(code);
1898 const char *rewrites = conn->server->config_options[URL_REWRITES];
1899 char headers[200], body[200];
1902 int body_len, headers_len, match_code;
1904 conn->mg_conn.status_code = code;
1906 // Invoke error handler if it is set
1907 if (call_user(conn, MG_HTTP_ERROR) == MG_TRUE) {
1908 close_local_endpoint(conn);
1912 // Handle error code rewrites
1913 while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
1914 if ((match_code = atoi(a.ptr)) > 0 && match_code == code) {
1915 struct mg_connection *c = &conn->mg_conn;
1916 c->status_code = 302;
1917 mg_printf(c, "HTTP/1.1 %d Moved\r\n"
1918 "Location: %.*s?code=%d&orig_uri=%s&query_string=%s\r\n\r\n",
1919 c->status_code, b.len, b.ptr, code, c->uri,
1920 c->query_string == NULL ? "" : c->query_string);
1921 close_local_endpoint(conn);
1926 body_len = mg_snprintf(body, sizeof(body), "%d %s\n", code, message);
1929 body_len += mg_vsnprintf(body + body_len, sizeof(body) - body_len, fmt, ap);
1932 if ((code >= 300 && code <= 399) || code == 204) {
1933 // 3xx errors do not have body
1936 headers_len = mg_snprintf(headers, sizeof(headers),
1937 "HTTP/1.1 %d %s\r\nContent-Length: %d\r\n"
1938 "Content-Type: text/plain\r\n\r\n",
1939 code, message, body_len);
1940 ns_send(conn->ns_conn, headers, headers_len);
1941 ns_send(conn->ns_conn, body, body_len);
1942 close_local_endpoint(conn); // This will write to the log file
1945 static void write_chunk(struct connection *conn, const char *buf, int len) {
1946 char chunk_size[50];
1947 int n = mg_snprintf(chunk_size, sizeof(chunk_size), "%X\r\n", len);
1948 ns_send(conn->ns_conn, chunk_size, n);
1949 ns_send(conn->ns_conn, buf, len);
1950 ns_send(conn->ns_conn, "\r\n", 2);
1953 size_t mg_printf(struct mg_connection *conn, const char *fmt, ...) {
1958 ret = mg_vprintf(conn, fmt, ap);
1964 size_t mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap) {
1965 struct connection *c = MG_CONN_2_CONN(conn);
1967 ns_vprintf(c->ns_conn, fmt, ap);
1969 return c->ns_conn->send_iobuf.len;
1972 static void ns_forward(struct ns_connection *from, struct ns_connection *to) {
1973 DBG(("%p -> %p %lu bytes", from, to, (unsigned long)from->recv_iobuf.len));
1974 ns_send(to, from->recv_iobuf.buf, from->recv_iobuf.len);
1975 iobuf_remove(&from->recv_iobuf, from->recv_iobuf.len);
1978 #ifndef MONGOOSE_NO_CGI
1980 struct threadparam {
1985 static int wait_until_ready(sock_t sock, int for_read) {
1987 if ( (sock == INVALID_SOCKET) || (sock >= FD_SETSIZE) )
1991 select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0);
1995 static void *push_to_stdin(void *arg) {
1996 struct threadparam *tp = (struct threadparam *)arg;
1997 int n, sent, stop = 0;
1999 char buf[IOBUF_SIZE];
2001 while (!stop && wait_until_ready(tp->s, 1) &&
2002 (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
2003 if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
2004 for (sent = 0; !stop && sent < n; sent += k) {
2005 if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
2008 DBG(("%s", "FORWARDED EVERYTHING TO CGI"));
2009 CloseHandle(tp->hPipe);
2015 static void *pull_from_stdout(void *arg) {
2016 struct threadparam *tp = (struct threadparam *)arg;
2017 int k = 0, stop = 0;
2019 char buf[IOBUF_SIZE];
2021 while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
2022 for (sent = 0; !stop && sent < n; sent += k) {
2023 if (wait_until_ready(tp->s, 0) &&
2024 (k = send(tp->s, buf + sent, n - sent, 0)) <= 0) stop = 1;
2027 DBG(("%s", "EOF FROM CGI"));
2028 CloseHandle(tp->hPipe);
2029 shutdown(tp->s, 2); // Without this, IO thread may get truncated data
2036 static void spawn_stdio_thread(sock_t sock, HANDLE hPipe,
2037 void *(*func)(void *)) {
2038 struct threadparam *tp = (struct threadparam *)NS_MALLOC(sizeof(*tp));
2042 mg_start_thread(func, tp);
2046 static void abs_path(const char *utf8_path, char *abs_path, size_t len) {
2047 wchar_t buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE];
2048 to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
2049 GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
2050 WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
2053 static process_id_t start_process(char *interp, const char *cmd,
2054 const char *env, const char *envp[],
2055 const char *dir, sock_t sock) {
2057 PROCESS_INFORMATION pi;
2058 HANDLE a[2], b[2], me = GetCurrentProcess();
2059 wchar_t wcmd[MAX_PATH_SIZE], full_dir[MAX_PATH_SIZE];
2060 char buf[MAX_PATH_SIZE], buf4[MAX_PATH_SIZE], buf5[MAX_PATH_SIZE],
2061 cmdline[MAX_PATH_SIZE], *p;
2062 DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
2065 memset(&si, 0, sizeof(si));
2066 memset(&pi, 0, sizeof(pi));
2069 si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
2070 si.wShowWindow = SW_HIDE;
2071 si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
2073 CreatePipe(&a[0], &a[1], NULL, 0);
2074 CreatePipe(&b[0], &b[1], NULL, 0);
2075 DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
2076 DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
2078 if (interp == NULL && (fp = fopen(cmd, "r")) != NULL) {
2079 buf[0] = buf[1] = '\0';
2080 fgets(buf, sizeof(buf), fp);
2081 buf[sizeof(buf) - 1] = '\0';
2082 if (buf[0] == '#' && buf[1] == '!') {
2084 for (p = interp + strlen(interp) - 1;
2085 isspace(* (uint8_t *) p) && p > interp; p--) *p = '\0';
2090 if (interp != NULL) {
2091 abs_path(interp, buf4, ARRAY_SIZE(buf4));
2094 abs_path(dir, buf5, ARRAY_SIZE(buf5));
2095 to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
2096 mg_snprintf(cmdline, sizeof(cmdline), "%s%s\"%s\"",
2097 interp ? interp : "", interp ? " " : "", cmd);
2098 to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
2100 if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
2101 (void *) env, full_dir, &si, &pi) != 0) {
2102 spawn_stdio_thread(sock, a[1], push_to_stdin);
2103 spawn_stdio_thread(sock, b[0], pull_from_stdout);
2109 DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
2111 // Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE
2112 CloseHandle(si.hStdOutput);
2113 CloseHandle(si.hStdInput);
2114 //CloseHandle(pi.hThread);
2115 //CloseHandle(pi.hProcess);
2120 static process_id_t start_process(const char *interp, const char *cmd,
2121 const char *env, const char *envp[],
2122 const char *dir, sock_t sock) {
2124 process_id_t pid = fork();
2129 (void) dup2(sock, 0);
2130 (void) dup2(sock, 1);
2133 // After exec, all signal handlers are restored to their default values,
2134 // with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
2135 // implementation, SIGCHLD's handler will leave unchanged after exec
2136 // if it was set to be ignored. Restore it to default action.
2137 signal(SIGCHLD, SIG_DFL);
2139 if (interp == NULL) {
2140 execle(cmd, cmd, (char *) 0, envp); // Using (char *) 0 to avoid warning
2142 execle(interp, interp, cmd, (char *) 0, envp);
2144 snprintf(buf, sizeof(buf), "Status: 500\r\n\r\n"
2145 "500 Server Error: %s%s%s: %s", interp == NULL ? "" : interp,
2146 interp == NULL ? "" : " ", cmd, strerror(errno));
2147 send(1, buf, strlen(buf), 0);
2148 exit(EXIT_FAILURE); // exec call failed
2155 // This structure helps to create an environment for the spawned CGI program.
2156 // Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
2157 // last element must be NULL.
2158 // However, on Windows there is a requirement that all these VARIABLE=VALUE\0
2159 // strings must reside in a contiguous buffer. The end of the buffer is
2160 // marked by two '\0' characters.
2161 // We satisfy both worlds: we create an envp array (which is vars), all
2162 // entries are actually pointers inside buf.
2163 struct cgi_env_block {
2164 struct mg_connection *conn;
2165 char buf[CGI_ENVIRONMENT_SIZE]; // Environment buffer
2166 const char *vars[MAX_CGI_ENVIR_VARS]; // char *envp[]
2167 int len; // Space taken
2168 int nvars; // Number of variables in envp[]
2171 // Append VARIABLE=VALUE\0 string to the buffer, and add a respective
2172 // pointer into the vars array.
2173 static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {
2178 // Calculate how much space is left in the buffer
2179 space = sizeof(block->buf) - block->len - 2;
2182 // Make a pointer to the free space int the buffer
2183 added = block->buf + block->len;
2185 // Copy VARIABLE=VALUE\0 string into the free space
2187 n = mg_vsnprintf(added, (size_t) space, fmt, ap);
2190 // Make sure we do not overflow buffer and the envp array
2191 if (n > 0 && n + 1 < space &&
2192 block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
2193 // Append a pointer to the added string into the envp array
2194 block->vars[block->nvars++] = added;
2195 // Bump up used length counter. Include \0 terminator
2196 block->len += n + 1;
2202 static void addenv2(struct cgi_env_block *blk, const char *name) {
2204 if ((s = getenv(name)) != NULL) addenv(blk, "%s=%s", name, s);
2207 static void prepare_cgi_environment(struct connection *conn,
2209 struct cgi_env_block *blk) {
2210 struct mg_connection *ri = &conn->mg_conn;
2211 const char *s, *slash;
2212 char *p, **opts = conn->server->config_options;
2215 blk->len = blk->nvars = 0;
2218 if ((s = getenv("SERVER_NAME")) != NULL) {
2219 addenv(blk, "SERVER_NAME=%s", s);
2221 addenv(blk, "SERVER_NAME=%s", ri->local_ip);
2223 addenv(blk, "SERVER_ROOT=%s", opts[DOCUMENT_ROOT]);
2224 addenv(blk, "DOCUMENT_ROOT=%s", opts[DOCUMENT_ROOT]);
2225 addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MONGOOSE_VERSION);
2227 // Prepare the environment block
2228 addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
2229 addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
2230 addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP
2232 // TODO(lsm): fix this for IPv6 case
2233 //addenv(blk, "SERVER_PORT=%d", ri->remote_port);
2235 addenv(blk, "REQUEST_METHOD=%s", ri->request_method);
2236 addenv(blk, "REMOTE_ADDR=%s", ri->remote_ip);
2237 addenv(blk, "REMOTE_PORT=%d", ri->remote_port);
2238 addenv(blk, "REQUEST_URI=%s%s%s", ri->uri,
2239 ri->query_string == NULL ? "" : "?",
2240 ri->query_string == NULL ? "" : ri->query_string);
2243 if (conn->path_info != NULL) {
2244 addenv(blk, "SCRIPT_NAME=%.*s",
2245 (int) (strlen(ri->uri) - strlen(conn->path_info)), ri->uri);
2246 addenv(blk, "PATH_INFO=%s", conn->path_info);
2248 s = strrchr(prog, '/');
2249 slash = strrchr(ri->uri, '/');
2250 addenv(blk, "SCRIPT_NAME=%.*s%s",
2251 slash == NULL ? 0 : (int) (slash - ri->uri), ri->uri,
2252 s == NULL ? prog : s);
2255 addenv(blk, "SCRIPT_FILENAME=%s", prog);
2256 addenv(blk, "PATH_TRANSLATED=%s", prog);
2257 addenv(blk, "HTTPS=%s", conn->ns_conn->ssl != NULL ? "on" : "off");
2259 if ((s = mg_get_header(ri, "Content-Type")) != NULL)
2260 addenv(blk, "CONTENT_TYPE=%s", s);
2262 if (ri->query_string != NULL)
2263 addenv(blk, "QUERY_STRING=%s", ri->query_string);
2265 if ((s = mg_get_header(ri, "Content-Length")) != NULL)
2266 addenv(blk, "CONTENT_LENGTH=%s", s);
2268 addenv2(blk, "PATH");
2269 addenv2(blk, "TMP");
2270 addenv2(blk, "TEMP");
2271 addenv2(blk, "TMPDIR");
2272 addenv2(blk, "PERLLIB");
2273 addenv2(blk, ENV_EXPORT_TO_CGI);
2276 addenv2(blk, "COMSPEC");
2277 addenv2(blk, "SYSTEMROOT");
2278 addenv2(blk, "SystemDrive");
2279 addenv2(blk, "ProgramFiles");
2280 addenv2(blk, "ProgramFiles(x86)");
2281 addenv2(blk, "CommonProgramFiles(x86)");
2283 addenv2(blk, "LD_LIBRARY_PATH");
2286 // Add all headers as HTTP_* variables
2287 for (i = 0; i < ri->num_headers; i++) {
2288 p = addenv(blk, "HTTP_%s=%s",
2289 ri->http_headers[i].name, ri->http_headers[i].value);
2291 // Convert variable name into uppercase, and change - to _
2292 for (; *p != '=' && *p != '\0'; p++) {
2295 *p = (char) toupper(* (unsigned char *) p);
2299 blk->vars[blk->nvars++] = NULL;
2300 blk->buf[blk->len++] = '\0';
2302 assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
2303 assert(blk->len > 0);
2304 assert(blk->len < (int) sizeof(blk->buf));
2307 static const char cgi_status[] = "HTTP/1.1 200 OK\r\n";
2309 static void open_cgi_endpoint(struct connection *conn, const char *prog) {
2310 struct cgi_env_block blk;
2311 char dir[MAX_PATH_SIZE];
2315 prepare_cgi_environment(conn, prog, &blk);
2316 // CGI must be executed in its own directory. 'dir' must point to the
2317 // directory containing executable program, 'p' must point to the
2318 // executable program name relative to 'dir'.
2319 if ((p = strrchr(prog, '/')) == NULL) {
2320 mg_snprintf(dir, sizeof(dir), "%s", ".");
2322 mg_snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
2325 // Try to create socketpair in a loop until success. ns_socketpair()
2326 // can be interrupted by a signal and fail.
2327 // TODO(lsm): use sigaction to restart interrupted syscall
2330 } while (fds[0] == INVALID_SOCKET);
2332 if (start_process(conn->server->config_options[CGI_INTERPRETER],
2333 prog, blk.buf, blk.vars, dir, fds[1]) != 0) {
2334 conn->endpoint_type = EP_CGI;
2335 conn->endpoint.nc = ns_add_sock(&conn->server->ns_mgr, fds[0],
2336 mg_ev_handler, conn);
2337 conn->endpoint.nc->flags |= MG_CGI_CONN;
2338 ns_send(conn->ns_conn, cgi_status, sizeof(cgi_status) - 1);
2339 conn->mg_conn.status_code = 200;
2340 conn->ns_conn->flags |= NSF_BUFFER_BUT_DONT_SEND;
2341 // Pass POST data to the CGI process
2342 conn->endpoint.nc->send_iobuf = conn->ns_conn->recv_iobuf;
2343 iobuf_init(&conn->ns_conn->recv_iobuf, 0);
2345 closesocket(fds[0]);
2346 send_http_error(conn, 500, "start_process(%s) failed", prog);
2350 closesocket(fds[1]); // On Windows, CGI stdio thread closes that socket
2354 static void on_cgi_data(struct ns_connection *nc) {
2355 struct connection *conn = (struct connection *) nc->user_data;
2356 const char *status = "500";
2357 struct mg_connection c;
2361 // Copy CGI data from CGI socket to the client send buffer
2362 ns_forward(nc, conn->ns_conn);
2364 // If reply has not been parsed yet, parse it
2365 if (conn->ns_conn->flags & NSF_BUFFER_BUT_DONT_SEND) {
2366 struct iobuf *io = &conn->ns_conn->send_iobuf;
2367 size_t s_len = sizeof(cgi_status) - 1;
2368 int len = get_request_len(io->buf + s_len, io->len - s_len);
2369 char buf[MAX_REQUEST_SIZE], *s = buf;
2371 if (len == 0) return;
2373 if (len < 0 || len > (int) sizeof(buf)) {
2375 iobuf_remove(io, io->len);
2376 send_http_error(conn, 500, "CGI program sent malformed headers: [%.*s]",
2379 memset(&c, 0, sizeof(c));
2380 memcpy(buf, io->buf + s_len, len);
2381 buf[len - 1] = '\0';
2382 parse_http_headers(&s, &c);
2383 if (mg_get_header(&c, "Location") != NULL) {
2385 } else if ((status = (char *) mg_get_header(&c, "Status")) == NULL) {
2388 memcpy(io->buf + 9, status, 3);
2389 conn->mg_conn.status_code = atoi(status);
2391 conn->ns_conn->flags &= ~NSF_BUFFER_BUT_DONT_SEND;
2394 #endif // !MONGOOSE_NO_CGI
2396 static char *mg_strdup(const char *str) {
2397 char *copy = (char *) NS_MALLOC(strlen(str) + 1);
2404 static int isbyte(int n) {
2405 return n >= 0 && n <= 255;
2408 static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
2409 int n, a, b, c, d, slash = 32, len = 0;
2411 if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
2412 sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
2413 isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&
2414 slash >= 0 && slash < 33) {
2416 *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
2417 *mask = slash ? 0xffffffffU << (32 - slash) : 0;
2423 // Verify given socket address against the ACL.
2424 // Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
2425 static int check_acl(const char *acl, uint32_t remote_ip) {
2430 // If any ACL is set, deny by default
2431 allowed = acl == NULL ? '+' : '-';
2433 while ((acl = next_option(acl, &vec, NULL)) != NULL) {
2435 if ((flag != '+' && flag != '-') ||
2436 parse_net(&vec.ptr[1], &net, &mask) == 0) {
2440 if (net == (remote_ip & mask)) {
2445 return allowed == '+';
2448 // Protect against directory disclosure attack by removing '..',
2449 // excessive '/' and '\' characters
2450 static void remove_double_dots_and_double_slashes(char *s) {
2453 while (*s != '\0') {
2455 if (s[-1] == '/' || s[-1] == '\\') {
2456 // Skip all following slashes, backslashes and double-dots
2457 while (s[0] != '\0') {
2458 if (s[0] == '/' || s[0] == '\\') { s++; }
2459 else if (s[0] == '.' && (s[1] == '/' || s[1] == '\\')) { s += 2; }
2460 else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') { s += 2; }
2461 else if (s[0] == '.' && s[1] == '.' && (s[2] == '/' || s[2] == '\\')) { s += 3; }
2469 int mg_url_decode(const char *src, size_t src_len, char *dst,
2470 size_t dst_len, int is_form_url_encoded) {
2473 #define HEXTOI(x) (isdigit(x) ? (x) - '0' : (x) - 'W')
2475 for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
2476 if (src[i] == '%' && i + 2 < src_len &&
2477 isxdigit(* (const unsigned char *) (src + i + 1)) &&
2478 isxdigit(* (const unsigned char *) (src + i + 2))) {
2479 a = tolower(* (const unsigned char *) (src + i + 1));
2480 b = tolower(* (const unsigned char *) (src + i + 2));
2481 dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
2483 } else if (is_form_url_encoded && src[i] == '+') {
2490 dst[j] = '\0'; // Null-terminate the destination
2492 return i >= src_len ? j : -1;
2495 static int is_valid_http_method(const char *s) {
2496 return !strcmp(s, "GET") || !strcmp(s, "POST") || !strcmp(s, "HEAD") ||
2497 !strcmp(s, "CONNECT") || !strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
2498 !strcmp(s, "OPTIONS") || !strcmp(s, "PROPFIND") || !strcmp(s, "MKCOL") ||
2499 !strcmp(s, "PATCH");
2502 // Parse HTTP request, fill in mg_request structure.
2503 // This function modifies the buffer by NUL-terminating
2504 // HTTP request components, header names and header values.
2505 // Note that len must point to the last \n of HTTP headers.
2506 static size_t parse_http_message(char *buf, size_t len,
2507 struct mg_connection *ri) {
2510 // Reset the connection. Make sure that we don't touch fields that are
2511 // set elsewhere: remote_ip, remote_port, server_param
2512 ri->request_method = ri->uri = ri->http_version = ri->query_string = NULL;
2513 ri->num_headers = ri->status_code = ri->is_websocket = ri->content_len = 0;
2515 if (len < 1) return ~0;
2517 buf[len - 1] = '\0';
2519 // RFC says that all initial whitespaces should be ignored
2520 while (*buf != '\0' && isspace(* (unsigned char *) buf)) {
2523 ri->request_method = skip(&buf, " ");
2524 ri->uri = skip(&buf, " ");
2525 ri->http_version = skip(&buf, "\r\n");
2527 // HTTP message could be either HTTP request or HTTP response, e.g.
2528 // "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..."
2529 is_request = is_valid_http_method(ri->request_method);
2530 if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) ||
2531 (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
2535 ri->http_version += 5;
2537 ri->status_code = atoi(ri->uri);
2539 parse_http_headers(&buf, ri);
2541 if ((ri->query_string = strchr(ri->uri, '?')) != NULL) {
2542 *(char *) ri->query_string++ = '\0';
2544 n = (int) strlen(ri->uri);
2545 mg_url_decode(ri->uri, n, (char *) ri->uri, n + 1, 0);
2546 if (*ri->uri == '/' || *ri->uri == '.') {
2547 remove_double_dots_and_double_slashes((char *) ri->uri);
2554 static int lowercase(const char *s) {
2555 return tolower(* (const unsigned char *) s);
2558 static int mg_strcasecmp(const char *s1, const char *s2) {
2562 diff = lowercase(s1++) - lowercase(s2++);
2563 } while (diff == 0 && s1[-1] != '\0');
2568 static int mg_strncasecmp(const char *s1, const char *s2, size_t len) {
2573 diff = lowercase(s1++) - lowercase(s2++);
2574 } while (diff == 0 && s1[-1] != '\0' && --len > 0);
2579 // Return HTTP header value, or NULL if not found.
2580 const char *mg_get_header(const struct mg_connection *ri, const char *s) {
2583 for (i = 0; i < ri->num_headers; i++)
2584 if (!mg_strcasecmp(s, ri->http_headers[i].name))
2585 return ri->http_headers[i].value;
2590 // Perform case-insensitive match of string against pattern
2591 int mg_match_prefix(const char *pattern, ssize_t pattern_len, const char *str) {
2593 int len, res, i = 0, j = 0;
2595 if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
2596 res = mg_match_prefix(pattern, or_str - pattern, str);
2597 return res > 0 ? res : mg_match_prefix(or_str + 1,
2598 (pattern + pattern_len) - (or_str + 1), str);
2601 for (; i < pattern_len; i++, j++) {
2602 if (pattern[i] == '?' && str[j] != '\0') {
2604 } else if (pattern[i] == '$') {
2605 return str[j] == '\0' ? j : -1;
2606 } else if (pattern[i] == '*') {
2608 if (pattern[i] == '*') {
2610 len = (int) strlen(str + j);
2612 len = (int) strcspn(str + j, "/");
2614 if (i == pattern_len) {
2618 res = mg_match_prefix(pattern + i, pattern_len - i, str + j + len);
2619 } while (res == -1 && len-- > 0);
2620 return res == -1 ? -1 : j + res + len;
2621 } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
2628 // This function prints HTML pages, and expands "{{something}}" blocks
2629 // inside HTML by calling appropriate callback functions.
2630 // Note that {{@path/to/file}} construct outputs embedded file's contents,
2631 // which provides SSI-like functionality.
2632 void mg_template(struct mg_connection *conn, const char *s,
2633 struct mg_expansion *expansions) {
2634 int i, j, pos = 0, inside_marker = 0;
2636 for (i = 0; s[i] != '\0'; i++) {
2637 if (inside_marker == 0 && !memcmp(&s[i], "{{", 2)) {
2639 mg_send_data(conn, &s[pos], i - pos);
2644 if (inside_marker == 1 && !memcmp(&s[i], "}}", 2)) {
2645 for (j = 0; expansions[j].keyword != NULL; j++) {
2646 const char *kw = expansions[j].keyword;
2647 if ((int) strlen(kw) == i - (pos + 2) &&
2648 memcmp(kw, &s[pos + 2], i - (pos + 2)) == 0) {
2649 expansions[j].handler(conn);
2658 mg_send_data(conn, &s[pos], i - pos);
2662 #ifndef MONGOOSE_NO_FILESYSTEM
2663 static int is_dav_request(const struct connection *conn) {
2664 const char *s = conn->mg_conn.request_method;
2665 return !strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
2666 !strcmp(s, "MKCOL") || !strcmp(s, "PROPFIND");
2669 static int must_hide_file(struct connection *conn, const char *path) {
2670 const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
2671 const char *pattern = conn->server->config_options[HIDE_FILES_PATTERN];
2672 return mg_match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 ||
2673 (pattern != NULL && mg_match_prefix(pattern, strlen(pattern), path) > 0);
2676 // Return 1 if real file has been found, 0 otherwise
2677 static int convert_uri_to_file_name(struct connection *conn, char *buf,
2678 size_t buf_len, file_stat_t *st) {
2680 const char *rewrites = conn->server->config_options[URL_REWRITES];
2682 #ifndef MONGOOSE_NO_DAV
2683 is_dav_request(conn) && conn->server->config_options[DAV_ROOT] != NULL ?
2684 conn->server->config_options[DAV_ROOT] :
2686 conn->server->config_options[DOCUMENT_ROOT];
2687 #ifndef MONGOOSE_NO_CGI
2688 const char *cgi_pat = conn->server->config_options[CGI_PATTERN];
2691 const char *uri = conn->mg_conn.uri;
2692 const char *domain = mg_get_header(&conn->mg_conn, "Host");
2693 // Important: match_len has to be declared as int, unless rewrites break.
2694 int match_len, root_len = root == NULL ? 0 : strlen(root);
2696 // Perform virtual hosting rewrites
2697 if (rewrites != NULL && domain != NULL) {
2698 const char *colon = strchr(domain, ':');
2699 size_t domain_len = colon == NULL ? strlen(domain) : colon - domain;
2701 while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
2702 if (a.len > 1 && a.ptr[0] == '@' && a.len == domain_len + 1 &&
2703 mg_strncasecmp(a.ptr + 1, domain, domain_len) == 0) {
2711 // No filesystem access
2712 if (root == NULL || root_len == 0) return 0;
2714 // Handle URL rewrites
2715 mg_snprintf(buf, buf_len, "%.*s%s", root_len, root, uri);
2716 rewrites = conn->server->config_options[URL_REWRITES]; // Re-initialize!
2717 while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
2718 if ((match_len = mg_match_prefix(a.ptr, a.len, uri)) > 0) {
2719 mg_snprintf(buf, buf_len, "%.*s%s", (int) b.len, b.ptr, uri + match_len);
2724 if (stat(buf, st) == 0) return 1;
2726 #ifndef MONGOOSE_NO_CGI
2727 // Support PATH_INFO for CGI scripts.
2728 for (p = buf + strlen(root) + 2; *p != '\0'; p++) {
2731 if (mg_match_prefix(cgi_pat, strlen(cgi_pat), buf) > 0 &&
2733 DBG(("!!!! [%s]", buf));
2735 conn->path_info = mg_strdup(p);
2746 #endif // MONGOOSE_NO_FILESYSTEM
2748 static int should_keep_alive(const struct mg_connection *conn) {
2749 struct connection *c = MG_CONN_2_CONN(conn);
2750 const char *method = conn->request_method;
2751 const char *http_version = conn->http_version;
2752 const char *header = mg_get_header(conn, "Connection");
2753 return method != NULL &&
2754 (!strcmp(method, "GET") || c->endpoint_type == EP_USER) &&
2755 ((header != NULL && !mg_strcasecmp(header, "keep-alive")) ||
2756 (header == NULL && http_version && !strcmp(http_version, "1.1")));
2759 size_t mg_write(struct mg_connection *c, const void *buf, size_t len) {
2760 struct connection *conn = MG_CONN_2_CONN(c);
2761 ns_send(conn->ns_conn, buf, len);
2762 return conn->ns_conn->send_iobuf.len;
2765 void mg_send_status(struct mg_connection *c, int status) {
2766 struct connection *conn = MG_CONN_2_CONN(c);
2767 if (c->status_code == 0) {
2768 c->status_code = status;
2769 mg_printf(c, "HTTP/1.1 %d %s\r\n", status, status_code_to_str(status));
2771 conn->ns_conn->flags |= MG_USING_CHUNKED_API;
2774 void mg_send_header(struct mg_connection *c, const char *name, const char *v) {
2775 struct connection *conn = MG_CONN_2_CONN(c);
2776 if (c->status_code == 0) {
2777 c->status_code = 200;
2778 mg_printf(c, "HTTP/1.1 %d %s\r\n", 200, status_code_to_str(200));
2780 mg_printf(c, "%s: %s\r\n", name, v);
2781 conn->ns_conn->flags |= MG_USING_CHUNKED_API;
2784 static void terminate_headers(struct mg_connection *c) {
2785 struct connection *conn = MG_CONN_2_CONN(c);
2786 if (!(conn->ns_conn->flags & MG_HEADERS_SENT)) {
2787 mg_send_header(c, "Transfer-Encoding", "chunked");
2788 mg_write(c, "\r\n", 2);
2789 conn->ns_conn->flags |= MG_HEADERS_SENT;
2793 size_t mg_send_data(struct mg_connection *c, const void *data, int data_len) {
2794 struct connection *conn = MG_CONN_2_CONN(c);
2795 terminate_headers(c);
2796 write_chunk(MG_CONN_2_CONN(c), (const char *) data, data_len);
2797 return conn->ns_conn->send_iobuf.len;
2800 size_t mg_printf_data(struct mg_connection *c, const char *fmt, ...) {
2805 ret = mg_vprintf_data(c, fmt, ap);
2811 size_t mg_vprintf_data(struct mg_connection *c, const char *fmt, va_list ap) {
2812 struct connection *conn = MG_CONN_2_CONN(c);
2814 char mem[IOBUF_SIZE], *buf = mem;
2816 terminate_headers(c);
2818 len = ns_avprintf(&buf, sizeof(mem), fmt, ap);
2821 write_chunk((struct connection *) conn, buf, len);
2823 if (buf != mem && buf != NULL) {
2826 return conn->ns_conn->send_iobuf.len;
2829 #if !defined(MONGOOSE_NO_WEBSOCKET) || !defined(MONGOOSE_NO_AUTH)
2830 static int is_big_endian(void) {
2831 static const int n = 1;
2832 return ((char *) &n)[0] == 0;
2836 #ifndef MONGOOSE_NO_WEBSOCKET
2837 // START OF SHA-1 code
2838 // Copyright(c) By Steve Reid <steve@edmweb.com>
2839 #define SHA1HANDSOFF
2841 #include "solarisfixes.h"
2844 union char64long16 { unsigned char c[64]; uint32_t l[16]; };
2846 #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
2848 static uint32_t blk0(union char64long16 *block, int i) {
2849 // Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN
2850 if (!is_big_endian()) {
2851 block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
2852 (rol(block->l[i], 8) & 0x00FF00FF);
2857 /* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
2865 #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
2866 ^block->l[(i+2)&15]^block->l[i&15],1))
2867 #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30);
2868 #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
2869 #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
2870 #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
2871 #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
2876 unsigned char buffer[64];
2879 static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) {
2880 uint32_t a, b, c, d, e;
2881 union char64long16 block[1];
2883 memcpy(block, buffer, 64);
2889 R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3);
2890 R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7);
2891 R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11);
2892 R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15);
2893 R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
2894 R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
2895 R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
2896 R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
2897 R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
2898 R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
2899 R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
2900 R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
2901 R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
2902 R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
2903 R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
2904 R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
2905 R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
2906 R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
2907 R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
2908 R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
2914 // Erase working structures. The order of operations is important,
2915 // used to ensure that compiler doesn't optimize those out.
2916 memset(block, 0, sizeof(block));
2917 a = b = c = d = e = 0;
2918 (void) a; (void) b; (void) c; (void) d; (void) e;
2921 static void SHA1Init(SHA1_CTX *context) {
2922 context->state[0] = 0x67452301;
2923 context->state[1] = 0xEFCDAB89;
2924 context->state[2] = 0x98BADCFE;
2925 context->state[3] = 0x10325476;
2926 context->state[4] = 0xC3D2E1F0;
2927 context->count[0] = context->count[1] = 0;
2930 static void SHA1Update(SHA1_CTX *context, const unsigned char *data,
2934 j = context->count[0];
2935 if ((context->count[0] += len << 3) < j)
2936 context->count[1]++;
2937 context->count[1] += (len>>29);
2939 if ((j + len) > 63) {
2940 memcpy(&context->buffer[j], data, (i = 64-j));
2941 SHA1Transform(context->state, context->buffer);
2942 for ( ; i + 63 < len; i += 64) {
2943 SHA1Transform(context->state, &data[i]);
2948 memcpy(&context->buffer[j], &data[i], len - i);
2951 static void SHA1Final(unsigned char digest[20], SHA1_CTX *context) {
2953 unsigned char finalcount[8], c;
2955 for (i = 0; i < 8; i++) {
2956 finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
2957 >> ((3-(i & 3)) * 8) ) & 255);
2960 SHA1Update(context, &c, 1);
2961 while ((context->count[0] & 504) != 448) {
2963 SHA1Update(context, &c, 1);
2965 SHA1Update(context, finalcount, 8);
2966 for (i = 0; i < 20; i++) {
2967 digest[i] = (unsigned char)
2968 ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
2970 memset(context, '\0', sizeof(*context));
2971 memset(&finalcount, '\0', sizeof(finalcount));
2975 static void base64_encode(const unsigned char *src, int src_len, char *dst) {
2976 static const char *b64 =
2977 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2980 for (i = j = 0; i < src_len; i += 3) {
2982 b = i + 1 >= src_len ? 0 : src[i + 1];
2983 c = i + 2 >= src_len ? 0 : src[i + 2];
2985 dst[j++] = b64[a >> 2];
2986 dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
2987 if (i + 1 < src_len) {
2988 dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
2990 if (i + 2 < src_len) {
2991 dst[j++] = b64[c & 63];
2994 while (j % 4 != 0) {
3000 static void send_websocket_handshake(struct mg_connection *conn,
3002 static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
3003 char buf[500], sha[20], b64_sha[sizeof(sha) * 2];
3006 mg_snprintf(buf, sizeof(buf), "%s%s", key, magic);
3008 SHA1Update(&sha_ctx, (unsigned char *) buf, strlen(buf));
3009 SHA1Final((unsigned char *) sha, &sha_ctx);
3010 base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
3011 mg_snprintf(buf, sizeof(buf), "%s%s%s",
3012 "HTTP/1.1 101 Switching Protocols\r\n"
3013 "Upgrade: websocket\r\n"
3014 "Connection: Upgrade\r\n"
3015 "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n");
3017 mg_write(conn, buf, strlen(buf));
3020 static size_t deliver_websocket_frame(struct connection *conn) {
3021 // Having buf unsigned char * is important, as it is used below in arithmetic
3022 unsigned char *buf = (unsigned char *) conn->ns_conn->recv_iobuf.buf;
3023 size_t i, len, buf_len = conn->ns_conn->recv_iobuf.len, frame_len = 0,
3024 mask_len = 0, header_len = 0, data_len = 0, buffered = 0;
3028 mask_len = buf[1] & 128 ? 4 : 0;
3029 if (len < 126 && buf_len >= mask_len) {
3031 header_len = 2 + mask_len;
3032 } else if (len == 126 && buf_len >= 4 + mask_len) {
3033 header_len = 4 + mask_len;
3034 data_len = ((((size_t) buf[2]) << 8) + buf[3]);
3035 } else if (buf_len >= 10 + mask_len) {
3036 header_len = 10 + mask_len;
3037 data_len = (size_t) (((uint64_t) htonl(* (uint32_t *) &buf[2])) << 32) +
3038 htonl(* (uint32_t *) &buf[6]);
3042 frame_len = header_len + data_len;
3043 buffered = frame_len > 0 && frame_len <= buf_len;
3046 conn->mg_conn.content_len = data_len;
3047 conn->mg_conn.content = (char *) buf + header_len;
3048 conn->mg_conn.wsbits = buf[0];
3050 // Apply mask if necessary
3052 for (i = 0; i < data_len; i++) {
3053 buf[i + header_len] ^= (buf + header_len - mask_len)[i % 4];
3057 // Call the handler and remove frame from the iobuf
3058 if (call_user(conn, MG_REQUEST) == MG_FALSE ||
3059 (buf[0] & 0x0f) == WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
3060 conn->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
3062 iobuf_remove(&conn->ns_conn->recv_iobuf, frame_len);
3068 size_t mg_websocket_write(struct mg_connection *conn, int opcode,
3069 const char *data, size_t data_len) {
3070 unsigned char mem[4192], *copy = mem;
3071 size_t copy_len = 0;
3073 /* Check overflow */
3074 if (data_len > ~(size_t)0 - (size_t)10) {
3078 if (data_len + 10 > sizeof(mem) &&
3079 (copy = (unsigned char *) NS_MALLOC(data_len + 10)) == NULL) {
3083 copy[0] = 0x80 + (opcode & 0x0f);
3085 // Frame format: http://tools.ietf.org/html/rfc6455#section-5.2
3086 if (data_len < 126) {
3087 // Inline 7-bit length field
3089 memcpy(copy + 2, data, data_len);
3090 copy_len = 2 + data_len;
3091 } else if (data_len <= 0xFFFF) {
3092 // 16-bit length field
3094 * (uint16_t *) (copy + 2) = (uint16_t) htons((uint16_t) data_len);
3095 memcpy(copy + 4, data, data_len);
3096 copy_len = 4 + data_len;
3098 // 64-bit length field
3099 const uint32_t hi = htonl((uint32_t) ((uint64_t) data_len >> 32));
3100 const uint32_t lo = htonl(data_len & 0xffffffff);
3102 memcpy(copy+2,&hi,sizeof(hi));
3103 memcpy(copy+6,&lo,sizeof(lo));
3104 memcpy(copy + 10, data, data_len);
3105 copy_len = 10 + data_len;
3109 mg_write(conn, copy, copy_len);
3115 // If we send closing frame, schedule a connection to be closed after
3116 // data is drained to the client.
3117 if (opcode == WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
3118 MG_CONN_2_CONN(conn)->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
3121 return MG_CONN_2_CONN(conn)->ns_conn->send_iobuf.len;
3124 size_t mg_websocket_printf(struct mg_connection *conn, int opcode,
3125 const char *fmt, ...) {
3126 char mem[4192], *buf = mem;
3131 if ((len = ns_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
3132 mg_websocket_write(conn, opcode, buf, len);
3136 if (buf != mem && buf != NULL) {
3140 return MG_CONN_2_CONN(conn)->ns_conn->send_iobuf.len;
3143 static void send_websocket_handshake_if_requested(struct mg_connection *conn) {
3144 const char *ver = mg_get_header(conn, "Sec-WebSocket-Version"),
3145 *key = mg_get_header(conn, "Sec-WebSocket-Key");
3146 if (ver != NULL && key != NULL) {
3147 conn->is_websocket = 1;
3148 if (call_user(MG_CONN_2_CONN(conn), MG_WS_HANDSHAKE) == MG_FALSE) {
3149 send_websocket_handshake(conn, key);
3151 call_user(MG_CONN_2_CONN(conn), MG_WS_CONNECT);
3155 static void ping_idle_websocket_connection(struct connection *conn, time_t t) {
3156 if (t - conn->ns_conn->last_io_time > MONGOOSE_USE_WEBSOCKET_PING_INTERVAL) {
3157 mg_websocket_write(&conn->mg_conn, WEBSOCKET_OPCODE_PING, "", 0);
3161 #define ping_idle_websocket_connection(conn, t)
3162 #endif // !MONGOOSE_NO_WEBSOCKET
3164 static void write_terminating_chunk(struct connection *conn) {
3165 mg_write(&conn->mg_conn, "0\r\n\r\n", 5);
3168 static int call_request_handler(struct connection *conn) {
3170 conn->mg_conn.content = conn->ns_conn->recv_iobuf.buf;
3171 if ((result = call_user(conn, MG_REQUEST)) == MG_TRUE) {
3172 if (conn->ns_conn->flags & MG_USING_CHUNKED_API) {
3173 terminate_headers(&conn->mg_conn);
3174 write_terminating_chunk(conn);
3176 close_local_endpoint(conn);
3181 const char *mg_get_mime_type(const char *path, const char *default_mime_type) {
3185 path_len = strlen(path);
3187 for (i = 0; static_builtin_mime_types[i].extension != NULL; i++) {
3188 ext = path + (path_len - static_builtin_mime_types[i].ext_len);
3189 if (path_len > static_builtin_mime_types[i].ext_len &&
3190 mg_strcasecmp(ext, static_builtin_mime_types[i].extension) == 0) {
3191 return static_builtin_mime_types[i].mime_type;
3195 return default_mime_type;
3198 #ifndef MONGOOSE_NO_FILESYSTEM
3199 // Convert month to the month number. Return -1 on error, or month number
3200 static int get_month_index(const char *s) {
3201 static const char *month_names[] = {
3202 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3203 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3207 for (i = 0; i < (int) ARRAY_SIZE(month_names); i++)
3208 if (!strcmp(s, month_names[i]))
3214 static int num_leap_years(int year) {
3215 return year / 4 - year / 100 + year / 400;
3218 // Parse UTC date-time string, and return the corresponding time_t value.
3219 static time_t parse_date_string(const char *datetime) {
3220 static const unsigned short days_before_month[] = {
3221 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
3224 int second, minute, hour, day, month, year, leap_days, days;
3225 time_t result = (time_t) 0;
3227 if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d",
3228 &day, month_str, &year, &hour, &minute, &second) == 6) ||
3229 (sscanf(datetime, "%d %3s %d %d:%d:%d",
3230 &day, month_str, &year, &hour, &minute, &second) == 6) ||
3231 (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",
3232 &day, month_str, &year, &hour, &minute, &second) == 6) ||
3233 (sscanf(datetime, "%d-%3s-%d %d:%d:%d",
3234 &day, month_str, &year, &hour, &minute, &second) == 6)) &&
3236 (month = get_month_index(month_str)) != -1) {
3237 leap_days = num_leap_years(year) - num_leap_years(1970);
3239 days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
3240 result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
3246 // Look at the "path" extension and figure what mime type it has.
3247 // Store mime type in the vector.
3248 static void get_mime_type(const struct mg_server *server, const char *path,
3250 struct vec ext_vec, mime_vec;
3251 const char *list, *ext;
3254 path_len = strlen(path);
3256 // Scan user-defined mime types first, in case user wants to
3257 // override default mime types.
3258 list = server->config_options[EXTRA_MIME_TYPES];
3259 while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
3260 // ext now points to the path suffix
3261 ext = path + path_len - ext_vec.len;
3262 if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
3268 vec->ptr = mg_get_mime_type(path, "text/plain");
3269 vec->len = strlen(vec->ptr);
3272 static const char *suggest_connection_header(const struct mg_connection *conn) {
3273 return should_keep_alive(conn) ? "keep-alive" : "close";
3276 static void construct_etag(char *buf, size_t buf_len, const file_stat_t *st) {
3277 mg_snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"",
3278 (unsigned long) st->st_mtime, (int64_t) st->st_size);
3281 // Return True if we should reply 304 Not Modified.
3282 static int is_not_modified(const struct connection *conn,
3283 const file_stat_t *stp) {
3285 const char *ims = mg_get_header(&conn->mg_conn, "If-Modified-Since");
3286 const char *inm = mg_get_header(&conn->mg_conn, "If-None-Match");
3287 construct_etag(etag, sizeof(etag), stp);
3288 return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
3289 (ims != NULL && stp->st_mtime <= parse_date_string(ims));
3292 // For given directory path, substitute it to valid index file.
3293 // Return 0 if index file has been found, -1 if not found.
3294 // If the file is found, it's stats is returned in stp.
3295 static int find_index_file(struct connection *conn, char *path,
3296 size_t path_len, file_stat_t *stp) {
3297 const char *list = conn->server->config_options[INDEX_FILES];
3299 struct vec filename_vec;
3300 size_t n = strlen(path);
3303 // The 'path' given to us points to the directory. Remove all trailing
3304 // directory separator characters from the end of the path, and
3305 // then append single directory separator character.
3306 while (n > 0 && path[n - 1] == '/') {
3311 // Traverse index files list. For each entry, append it to the given
3312 // path and see if the file exists. If it exists, break the loop
3313 while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
3315 if (path_len <= n + 2) {
3319 // Ignore too long entries that may overflow path buffer
3320 if (filename_vec.len > (path_len - (n + 2)))
3323 // Prepare full path to the index file
3324 strncpy(path + n + 1, filename_vec.ptr, filename_vec.len);
3325 path[n + 1 + filename_vec.len] = '\0';
3327 //DBG(("[%s]", path));
3330 if (!stat(path, &st)) {
3331 // Yes it does, break the loop
3338 // If no index file exists, restore directory path
3347 static int parse_range_header(const char *header, int64_t *a, int64_t *b) {
3348 return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
3351 static void gmt_time_string(char *buf, size_t buf_len, time_t *t) {
3352 strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
3355 static void open_file_endpoint(struct connection *conn, const char *path,
3356 file_stat_t *st, const char *extra_headers) {
3357 char date[64], lm[64], etag[64], range[64], headers[1000];
3358 const char *msg = "OK", *hdr;
3359 time_t t, curtime = time(NULL);
3361 struct vec mime_vec;
3364 conn->endpoint_type = EP_FILE;
3365 ns_set_close_on_exec(conn->endpoint.fd);
3366 conn->mg_conn.status_code = 200;
3368 get_mime_type(conn->server, path, &mime_vec);
3369 conn->cl = st->st_size;
3372 // If Range: header specified, act accordingly
3374 hdr = mg_get_header(&conn->mg_conn, "Range");
3375 if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 &&
3376 r1 >= 0 && r2 >= 0) {
3377 conn->mg_conn.status_code = 206;
3378 conn->cl = n == 2 ? (r2 > conn->cl ? conn->cl : r2) - r1 + 1: conn->cl - r1;
3379 mg_snprintf(range, sizeof(range), "Content-Range: bytes "
3380 "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
3381 r1, r1 + conn->cl - 1, (int64_t) st->st_size);
3382 msg = "Partial Content";
3383 lseek(conn->endpoint.fd, r1, SEEK_SET);
3386 // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
3387 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
3388 gmt_time_string(date, sizeof(date), &curtime);
3389 t = st->st_mtime; // store in local variable for NDK compile
3390 gmt_time_string(lm, sizeof(lm), &t);
3391 construct_etag(etag, sizeof(etag), st);
3393 n = mg_snprintf(headers, sizeof(headers),
3394 "HTTP/1.1 %d %s\r\n"
3396 "Last-Modified: %s\r\n"
3398 "Content-Type: %.*s\r\n"
3399 "Content-Length: %" INT64_FMT "\r\n"
3400 "Connection: %s\r\n"
3401 "Accept-Ranges: bytes\r\n"
3403 conn->mg_conn.status_code, msg, date, lm, etag,
3404 (int) mime_vec.len, mime_vec.ptr, conn->cl,
3405 suggest_connection_header(&conn->mg_conn),
3406 range, extra_headers == NULL ? "" : extra_headers,
3407 MONGOOSE_USE_EXTRA_HTTP_HEADERS);
3408 ns_send(conn->ns_conn, headers, n);
3410 if (!strcmp(conn->mg_conn.request_method, "HEAD")) {
3411 conn->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
3412 close(conn->endpoint.fd);
3413 conn->endpoint_type = EP_NONE;
3417 void mg_send_file_data(struct mg_connection *c, int fd) {
3418 struct connection *conn = MG_CONN_2_CONN(c);
3419 conn->endpoint_type = EP_FILE;
3420 conn->endpoint.fd = fd;
3421 ns_set_close_on_exec(conn->endpoint.fd);
3423 #endif // MONGOOSE_NO_FILESYSTEM
3425 static void call_request_handler_if_data_is_buffered(struct connection *conn) {
3426 #ifndef MONGOOSE_NO_WEBSOCKET
3427 if (conn->mg_conn.is_websocket) {
3428 do { } while (deliver_websocket_frame(conn));
3431 if (conn->num_bytes_recv >= (conn->cl + conn->request_len) &&
3432 call_request_handler(conn) == MG_FALSE) {
3433 open_local_endpoint(conn, 1);
3437 #if !defined(MONGOOSE_NO_DIRECTORY_LISTING) || !defined(MONGOOSE_NO_DAV)
3441 char d_name[MAX_PATH_SIZE];
3444 typedef struct DIR {
3446 WIN32_FIND_DATAW info;
3447 struct dirent result;
3450 // Implementation of POSIX opendir/closedir/readdir for Windows.
3451 static DIR *opendir(const char *name) {
3453 wchar_t wpath[MAX_PATH_SIZE];
3457 SetLastError(ERROR_BAD_ARGUMENTS);
3458 } else if ((dir = (DIR *) NS_MALLOC(sizeof(*dir))) == NULL) {
3459 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
3461 to_wchar(name, wpath, ARRAY_SIZE(wpath));
3462 attrs = GetFileAttributesW(wpath);
3463 if (attrs != 0xFFFFFFFF &&
3464 ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
3465 (void) wcscat(wpath, L"\\*");
3466 dir->handle = FindFirstFileW(wpath, &dir->info);
3467 dir->result.d_name[0] = '\0';
3477 static int closedir(DIR *dir) {
3481 if (dir->handle != INVALID_HANDLE_VALUE)
3482 result = FindClose(dir->handle) ? 0 : -1;
3487 SetLastError(ERROR_BAD_ARGUMENTS);
3493 static struct dirent *readdir(DIR *dir) {
3494 struct dirent *result = 0;
3497 if (dir->handle != INVALID_HANDLE_VALUE) {
3498 result = &dir->result;
3499 (void) WideCharToMultiByte(CP_UTF8, 0,
3500 dir->info.cFileName, -1, result->d_name,
3501 sizeof(result->d_name), NULL, NULL);
3503 if (!FindNextFileW(dir->handle, &dir->info)) {
3504 (void) FindClose(dir->handle);
3505 dir->handle = INVALID_HANDLE_VALUE;
3509 SetLastError(ERROR_FILE_NOT_FOUND);
3512 SetLastError(ERROR_BAD_ARGUMENTS);
3517 #endif // _WIN32 POSIX opendir/closedir/readdir implementation
3519 static int scan_directory(struct connection *conn, const char *dir,
3520 struct dir_entry **arr) {
3521 char path[MAX_PATH_SIZE];
3522 struct dir_entry *p;
3524 int arr_size = 0, arr_ind = 0, inc = 100;
3528 if ((dirp = (opendir(dir))) == NULL) return 0;
3530 while ((dp = readdir(dirp)) != NULL) {
3531 // Do not show current dir and hidden files
3532 if (!strcmp(dp->d_name, ".") ||
3533 !strcmp(dp->d_name, "..") ||
3534 must_hide_file(conn, dp->d_name)) {
3537 mg_snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
3539 // Resize the array if necessary
3540 if (arr_ind >= arr_size) {
3541 if ((p = (struct dir_entry *)
3542 NS_REALLOC(*arr, (inc + arr_size) * sizeof(**arr))) != NULL) {
3543 // Memset new chunk to zero, otherwise st_mtime will have garbage which
3544 // can make strftime() segfault, see
3545 // http://code.google.com/p/mongoose/issues/detail?id=79
3546 memset(p + arr_size, 0, sizeof(**arr) * inc);
3553 if (arr_ind < arr_size) {
3554 (*arr)[arr_ind].conn = conn;
3555 (*arr)[arr_ind].file_name = strdup(dp->d_name);
3556 stat(path, &(*arr)[arr_ind].st);
3565 size_t mg_url_encode(const char *src, size_t s_len, char *dst, size_t dst_len) {
3566 static const char *dont_escape = "._-$,;~()";
3567 static const char *hex = "0123456789abcdef";
3568 size_t i = 0, j = 0;
3570 for (i = j = 0; dst_len > 0 && i < s_len && j + 2 < dst_len - 1; i++, j++) {
3571 if (isalnum(* (const unsigned char *) (src + i)) ||
3572 strchr(dont_escape, * (const unsigned char *) (src + i)) != NULL) {
3574 } else if (j + 3 < dst_len) {
3576 dst[j + 1] = hex[(* (const unsigned char *) (src + i)) >> 4];
3577 dst[j + 2] = hex[(* (const unsigned char *) (src + i)) & 0xf];
3585 #endif // !NO_DIRECTORY_LISTING || !MONGOOSE_NO_DAV
3587 #ifndef MONGOOSE_NO_DIRECTORY_LISTING
3589 static void print_dir_entry(const struct dir_entry *de) {
3590 char size[64], mod[64], href[MAX_PATH_SIZE * 3];
3591 int64_t fsize = de->st.st_size;
3592 int is_dir = S_ISDIR(de->st.st_mode);
3593 const char *slash = is_dir ? "/" : "";
3597 mg_snprintf(size, sizeof(size), "%s", "[DIRECTORY]");
3599 // We use (signed) cast below because MSVC 6 compiler cannot
3600 // convert unsigned __int64 to double.
3602 mg_snprintf(size, sizeof(size), "%d", (int) fsize);
3603 } else if (fsize < 0x100000) {
3604 mg_snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0);
3605 } else if (fsize < 0x40000000) {
3606 mg_snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576);
3608 mg_snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824);
3611 t = de->st.st_mtime; // store in local variable for NDK compile
3612 strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&t));
3613 mg_url_encode(de->file_name, strlen(de->file_name), href, sizeof(href));
3614 mg_printf_data(&de->conn->mg_conn,
3615 "<tr><td><a href=\"%s%s\">%s%s</a></td>"
3616 "<td> %s</td><td> %s</td></tr>\n",
3617 href, slash, de->file_name, slash, mod, size);
3620 // Sort directory entries by size, or name, or modification time.
3621 // On windows, __cdecl specification is needed in case if project is built
3622 // with __stdcall convention. qsort always requires __cdels callback.
3623 static int __cdecl compare_dir_entries(const void *p1, const void *p2) {
3624 const struct dir_entry *a = (const struct dir_entry *) p1,
3625 *b = (const struct dir_entry *) p2;
3626 const char *qs = a->conn->mg_conn.query_string ?
3627 a->conn->mg_conn.query_string : "na";
3630 if (S_ISDIR(a->st.st_mode) && !S_ISDIR(b->st.st_mode)) {
3631 return -1; // Always put directories on top
3632 } else if (!S_ISDIR(a->st.st_mode) && S_ISDIR(b->st.st_mode)) {
3633 return 1; // Always put directories on top
3634 } else if (*qs == 'n') {
3635 cmp_result = strcmp(a->file_name, b->file_name);
3636 } else if (*qs == 's') {
3637 cmp_result = a->st.st_size == b->st.st_size ? 0 :
3638 a->st.st_size > b->st.st_size ? 1 : -1;
3639 } else if (*qs == 'd') {
3640 cmp_result = a->st.st_mtime == b->st.st_mtime ? 0 :
3641 a->st.st_mtime > b->st.st_mtime ? 1 : -1;
3644 return qs[1] == 'd' ? -cmp_result : cmp_result;
3647 static void send_directory_listing(struct connection *conn, const char *dir) {
3648 struct dir_entry *arr = NULL;
3649 int i, num_entries, sort_direction = conn->mg_conn.query_string != NULL &&
3650 conn->mg_conn.query_string[1] == 'd' ? 'a' : 'd';
3652 mg_send_header(&conn->mg_conn, "Transfer-Encoding", "chunked");
3653 mg_send_header(&conn->mg_conn, "Content-Type", "text/html; charset=utf-8");
3655 mg_printf_data(&conn->mg_conn,
3656 "<html><head><title>Index of %s</title>"
3657 "<style>th {text-align: left;}</style></head>"
3658 "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
3659 "<tr><th><a href=\"?n%c\">Name</a></th>"
3660 "<th><a href=\"?d%c\">Modified</a></th>"
3661 "<th><a href=\"?s%c\">Size</a></th></tr>"
3662 "<tr><td colspan=\"3\"><hr></td></tr>",
3663 conn->mg_conn.uri, conn->mg_conn.uri,
3664 sort_direction, sort_direction, sort_direction);
3666 num_entries = scan_directory(conn, dir, &arr);
3668 qsort(arr, num_entries, sizeof(arr[0]), compare_dir_entries);
3669 for (i = 0; i < num_entries; i++) {
3670 print_dir_entry(&arr[i]);
3671 NS_FREE(arr[i].file_name);
3676 write_terminating_chunk(conn);
3677 close_local_endpoint(conn);
3679 #endif // MONGOOSE_NO_DIRECTORY_LISTING
3681 #ifndef MONGOOSE_NO_DAV
3682 static void print_props(struct connection *conn, const char *uri,
3685 time_t t = stp->st_mtime; // store in local variable for NDK compile
3686 gmt_time_string(mtime, sizeof(mtime), &t);
3687 mg_printf(&conn->mg_conn,
3689 "<d:href>%s</d:href>"
3692 "<d:resourcetype>%s</d:resourcetype>"
3693 "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
3694 "<d:getlastmodified>%s</d:getlastmodified>"
3696 "<d:status>HTTP/1.1 200 OK</d:status>"
3699 uri, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "",
3700 (int64_t) stp->st_size, mtime);
3703 static void handle_propfind(struct connection *conn, const char *path,
3704 file_stat_t *stp, int exists) {
3705 static const char header[] = "HTTP/1.1 207 Multi-Status\r\n"
3706 "Connection: close\r\n"
3707 "Content-Type: text/xml; charset=utf-8\r\n\r\n"
3708 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
3709 "<d:multistatus xmlns:d='DAV:'>\n";
3710 static const char footer[] = "</d:multistatus>";
3711 const char *depth = mg_get_header(&conn->mg_conn, "Depth");
3712 #ifdef MONGOOSE_NO_DIRECTORY_LISTING
3713 const char *list_dir = "no";
3715 const char *list_dir = conn->server->config_options[ENABLE_DIRECTORY_LISTING];
3718 conn->mg_conn.status_code = 207;
3720 // Print properties for the requested resource itself
3722 conn->mg_conn.status_code = 404;
3723 mg_printf(&conn->mg_conn, "%s", "HTTP/1.1 404 Not Found\r\n\r\n");
3724 } else if (S_ISDIR(stp->st_mode) && mg_strcasecmp(list_dir, "yes") != 0) {
3725 conn->mg_conn.status_code = 403;
3726 mg_printf(&conn->mg_conn, "%s",
3727 "HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
3729 ns_send(conn->ns_conn, header, sizeof(header) - 1);
3730 print_props(conn, conn->mg_conn.uri, stp);
3732 if (S_ISDIR(stp->st_mode) &&
3733 (depth == NULL || strcmp(depth, "0") != 0)) {
3734 struct dir_entry *arr = NULL;
3735 int i, num_entries = scan_directory(conn, path, &arr);
3737 for (i = 0; i < num_entries; i++) {
3738 char buf[MAX_PATH_SIZE * 3];
3739 struct dir_entry *de = &arr[i];
3740 mg_url_encode(de->file_name, strlen(de->file_name), buf, sizeof(buf));
3741 print_props(conn, buf, &de->st);
3742 NS_FREE(de->file_name);
3746 ns_send(conn->ns_conn, footer, sizeof(footer) - 1);
3749 close_local_endpoint(conn);
3752 static void handle_mkcol(struct connection *conn, const char *path) {
3753 int status_code = 500;
3755 if (conn->mg_conn.content_len > 0) {
3757 } else if (!mkdir(path, 0755)) {
3759 } else if (errno == EEXIST) {
3761 } else if (errno == EACCES) {
3763 } else if (errno == ENOENT) {
3766 send_http_error(conn, status_code, NULL);
3769 static int remove_directory(const char *dir) {
3770 char path[MAX_PATH_SIZE];
3775 if ((dirp = opendir(dir)) == NULL) return 0;
3777 while ((dp = readdir(dirp)) != NULL) {
3778 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue;
3779 mg_snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
3781 if (S_ISDIR(st.st_mode)) {
3782 remove_directory(path);
3793 static void handle_delete(struct connection *conn, const char *path) {
3796 if (stat(path, &st) != 0) {
3797 send_http_error(conn, 404, NULL);
3798 } else if (S_ISDIR(st.st_mode)) {
3799 remove_directory(path);
3800 send_http_error(conn, 204, NULL);
3801 } else if (remove(path) == 0) {
3802 send_http_error(conn, 204, NULL);
3804 send_http_error(conn, 423, NULL);
3808 // For a given PUT path, create all intermediate subdirectories
3809 // for given path. Return 0 if the path itself is a directory,
3810 // or -1 on error, 1 if OK.
3811 static int put_dir(const char *path) {
3812 char buf[MAX_PATH_SIZE];
3816 // Create intermediate directories if they do not exist
3817 for (s = p = path + 1; (p = strchr(s, '/')) != NULL; s = ++p) {
3818 if (p - path >= (int) sizeof(buf)) return -1; // Buffer overflow
3819 memcpy(buf, path, p - path);
3820 buf[p - path] = '\0';
3821 if (stat(buf, &st) != 0 && mkdir(buf, 0755) != 0) return -1;
3822 if (p[1] == '\0') return 0; // Path is a directory itself
3828 static void handle_put(struct connection *conn, const char *path) {
3830 const char *range, *cl_hdr = mg_get_header(&conn->mg_conn, "Content-Length");
3834 conn->mg_conn.status_code = !stat(path, &st) ? 200 : 201;
3835 if ((rc = put_dir(path)) == 0) {
3836 mg_printf(&conn->mg_conn, "HTTP/1.1 %d OK\r\n\r\n",
3837 conn->mg_conn.status_code);
3838 close_local_endpoint(conn);
3839 } else if (rc == -1) {
3840 send_http_error(conn, 500, "put_dir: %s", strerror(errno));
3841 } else if (cl_hdr == NULL) {
3842 send_http_error(conn, 411, NULL);
3843 } else if ((conn->endpoint.fd =
3844 open(path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0644)) < 0) {
3845 send_http_error(conn, 500, "open(%s): %s", path, strerror(errno));
3847 DBG(("PUT [%s] %lu", path, (unsigned long) conn->ns_conn->recv_iobuf.len));
3848 conn->endpoint_type = EP_PUT;
3849 ns_set_close_on_exec(conn->endpoint.fd);
3850 range = mg_get_header(&conn->mg_conn, "Content-Range");
3851 conn->cl = to64(cl_hdr);
3853 if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
3854 conn->mg_conn.status_code = 206;
3855 lseek(conn->endpoint.fd, r1, SEEK_SET);
3856 conn->cl = r2 > r1 ? r2 - r1 + 1: conn->cl - r1;
3858 mg_printf(&conn->mg_conn, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n",
3859 conn->mg_conn.status_code);
3863 static void forward_put_data(struct connection *conn) {
3864 struct iobuf *io = &conn->ns_conn->recv_iobuf;
3865 size_t k = conn->cl < (int64_t) io->len ? conn->cl : (int64_t) io->len; // To write
3866 size_t n = write(conn->endpoint.fd, io->buf, k); // Write them!
3868 iobuf_remove(io, n);
3871 if (conn->cl <= 0) {
3872 close_local_endpoint(conn);
3875 #endif // MONGOOSE_NO_DAV
3877 static void send_options(struct connection *conn) {
3878 conn->mg_conn.status_code = 200;
3879 mg_printf(&conn->mg_conn, "%s",
3880 "HTTP/1.1 200 OK\r\nAllow: GET, POST, HEAD, CONNECT, PUT, "
3881 "DELETE, OPTIONS, PROPFIND, MKCOL\r\nDAV: 1\r\n\r\n");
3882 close_local_endpoint(conn);
3885 #ifndef MONGOOSE_NO_AUTH
3886 void mg_send_digest_auth_request(struct mg_connection *c) {
3887 struct connection *conn = MG_CONN_2_CONN(c);
3888 c->status_code = 401;
3890 "HTTP/1.1 401 Unauthorized\r\n"
3891 "Content-Length: 0\r\n"
3892 "WWW-Authenticate: Digest qop=\"auth\", "
3893 "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
3894 conn->server->config_options[AUTH_DOMAIN],
3895 (unsigned long) time(NULL));
3896 close_local_endpoint(conn);
3899 // Use the global passwords file, if specified by auth_gpass option,
3900 // or search for .htpasswd in the requested directory.
3901 static FILE *open_auth_file(struct connection *conn, const char *path,
3903 char name[MAX_PATH_SIZE];
3904 const char *p, *gpass = conn->server->config_options[GLOBAL_AUTH_FILE];
3907 if (gpass != NULL) {
3908 // Use global passwords file
3909 fp = fopen(gpass, "r");
3910 } else if (is_directory) {
3911 mg_snprintf(name, sizeof(name), "%s%c%s", path, '/', PASSWORDS_FILE_NAME);
3912 fp = fopen(name, "r");
3914 // Try to find .htpasswd in requested directory.
3915 if ((p = strrchr(path, '/')) == NULL) p = path;
3916 mg_snprintf(name, sizeof(name), "%.*s%c%s",
3917 (int) (p - path), path, '/', PASSWORDS_FILE_NAME);
3918 fp = fopen(name, "r");
3924 #if !defined(HAVE_MD5) && !defined(MONGOOSE_NO_AUTH)
3926 * This code implements the MD5 message-digest algorithm.
3927 * The algorithm is due to Ron Rivest. This code was
3928 * written by Colin Plumb in 1993, no copyright is claimed.
3929 * This code is in the public domain; do with it what you wish.
3931 * Equivalent code is available from RSA Data Security, Inc.
3932 * This code has been tested against that, and is equivalent,
3933 * except that you don't need to include two pages of legalese
3936 * To compute the message digest of a chunk of bytes, declare an
3937 * MD5Context structure, pass it to MD5Init, call MD5Update as
3938 * needed on buffers full of bytes, and then call MD5Final, which
3939 * will fill a supplied 16-byte array with the digest.
3942 typedef struct MD5Context {
3945 unsigned char in[64];
3948 static void byteReverse(unsigned char *buf, unsigned longs) {
3951 // Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN
3952 if (is_big_endian()) {
3954 t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
3955 ((unsigned) buf[1] << 8 | buf[0]);
3956 * (uint32_t *) buf = t;
3962 #define F1(x, y, z) (z ^ (x & (y ^ z)))
3963 #define F2(x, y, z) F1(z, x, y)
3964 #define F3(x, y, z) (x ^ y ^ z)
3965 #define F4(x, y, z) (y ^ (x | ~z))
3967 #define MD5STEP(f, w, x, y, z, data, s) \
3968 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3970 // Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3971 // initialization constants.
3972 static void MD5Init(MD5_CTX *ctx) {
3973 ctx->buf[0] = 0x67452301;
3974 ctx->buf[1] = 0xefcdab89;
3975 ctx->buf[2] = 0x98badcfe;
3976 ctx->buf[3] = 0x10325476;
3982 static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
3983 register uint32_t a, b, c, d;
3990 MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
3991 MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
3992 MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
3993 MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
3994 MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
3995 MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
3996 MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
3997 MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
3998 MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
3999 MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
4000 MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
4001 MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
4002 MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
4003 MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
4004 MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
4005 MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
4007 MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
4008 MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
4009 MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
4010 MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
4011 MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
4012 MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
4013 MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
4014 MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
4015 MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
4016 MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
4017 MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
4018 MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
4019 MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
4020 MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
4021 MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
4022 MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
4024 MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
4025 MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
4026 MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
4027 MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
4028 MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
4029 MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
4030 MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
4031 MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
4032 MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
4033 MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
4034 MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
4035 MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
4036 MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
4037 MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
4038 MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
4039 MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
4041 MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
4042 MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
4043 MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
4044 MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
4045 MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
4046 MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
4047 MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
4048 MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
4049 MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
4050 MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
4051 MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
4052 MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
4053 MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
4054 MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
4055 MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
4056 MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
4064 static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) {
4068 if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
4070 ctx->bits[1] += len >> 29;
4072 t = (t >> 3) & 0x3f;
4075 unsigned char *p = (unsigned char *) ctx->in + t;
4079 memcpy(p, buf, len);
4083 byteReverse(ctx->in, 16);
4084 MD5Transform(ctx->buf, (uint32_t *) ctx->in);
4090 memcpy(ctx->in, buf, 64);
4091 byteReverse(ctx->in, 16);
4092 MD5Transform(ctx->buf, (uint32_t *) ctx->in);
4097 memcpy(ctx->in, buf, len);
4100 static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) {
4105 count = (ctx->bits[0] >> 3) & 0x3F;
4107 p = ctx->in + count;
4109 count = 64 - 1 - count;
4111 memset(p, 0, count);
4112 byteReverse(ctx->in, 16);
4113 MD5Transform(ctx->buf, (uint32_t *) ctx->in);
4114 memset(ctx->in, 0, 56);
4116 memset(p, 0, count - 8);
4118 byteReverse(ctx->in, 14);
4120 a = (uint32_t *)ctx->in;
4121 a[14] = ctx->bits[0];
4122 a[15] = ctx->bits[1];
4124 MD5Transform(ctx->buf, (uint32_t *) ctx->in);
4125 byteReverse((unsigned char *) ctx->buf, 4);
4126 memcpy(digest, ctx->buf, 16);
4127 memset((char *) ctx, 0, sizeof(*ctx));
4133 // Stringify binary data. Output buffer must be twice as big as input,
4134 // because each byte takes 2 bytes in string representation
4135 static void bin2str(char *to, const unsigned char *p, size_t len) {
4136 static const char *hex = "0123456789abcdef";
4138 for (; len--; p++) {
4139 *to++ = hex[p[0] >> 4];
4140 *to++ = hex[p[0] & 0x0f];
4145 // Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
4146 char *mg_md5(char buf[33], ...) {
4147 unsigned char hash[16];
4155 while ((p = va_arg(ap, const char *)) != NULL) {
4156 MD5Update(&ctx, (const unsigned char *) p, (unsigned) strlen(p));
4160 MD5Final(hash, &ctx);
4161 bin2str(buf, hash, sizeof(hash));
4165 // Check the user's password, return 1 if OK
4166 static int check_password(const char *method, const char *ha1, const char *uri,
4167 const char *nonce, const char *nc, const char *cnonce,
4168 const char *qop, const char *response) {
4169 char ha2[32 + 1], expected_response[32 + 1];
4172 // Check for authentication timeout
4173 if ((unsigned long) time(NULL) - (unsigned long) to64(nonce) > 3600 * 2) {
4178 mg_md5(ha2, method, ":", uri, NULL);
4179 mg_md5(expected_response, ha1, ":", nonce, ":", nc,
4180 ":", cnonce, ":", qop, ":", ha2, NULL);
4182 return mg_strcasecmp(response, expected_response) == 0 ? MG_TRUE : MG_FALSE;
4186 // Authorize against the opened passwords file. Return 1 if authorized.
4187 int mg_authorize_digest(struct mg_connection *c, FILE *fp) {
4188 struct connection *conn = MG_CONN_2_CONN(c);
4190 char line[256], f_user[256], ha1[256], f_domain[256], user[100], nonce[100],
4191 uri[MAX_REQUEST_SIZE], cnonce[100], resp[100], qop[100], nc[100];
4193 if (c == NULL || fp == NULL) return 0;
4194 if ((hdr = mg_get_header(c, "Authorization")) == NULL ||
4195 mg_strncasecmp(hdr, "Digest ", 7) != 0) return 0;
4196 if (!mg_parse_header(hdr, "username", user, sizeof(user))) return 0;
4197 if (!mg_parse_header(hdr, "cnonce", cnonce, sizeof(cnonce))) return 0;
4198 if (!mg_parse_header(hdr, "response", resp, sizeof(resp))) return 0;
4199 if (!mg_parse_header(hdr, "uri", uri, sizeof(uri))) return 0;
4200 if (!mg_parse_header(hdr, "qop", qop, sizeof(qop))) return 0;
4201 if (!mg_parse_header(hdr, "nc", nc, sizeof(nc))) return 0;
4202 if (!mg_parse_header(hdr, "nonce", nonce, sizeof(nonce))) return 0;
4204 while (fgets(line, sizeof(line), fp) != NULL) {
4205 if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) == 3 &&
4206 !strcmp(user, f_user) &&
4207 // NOTE(lsm): due to a bug in MSIE, we do not compare URIs
4208 !strcmp(conn->server->config_options[AUTH_DOMAIN], f_domain))
4209 return check_password(c->request_method, ha1, uri,
4210 nonce, nc, cnonce, qop, resp);
4216 // Return 1 if request is authorised, 0 otherwise.
4217 static int is_authorized(struct connection *conn, const char *path,
4220 int authorized = MG_TRUE;
4222 if ((fp = open_auth_file(conn, path, is_directory)) != NULL) {
4223 authorized = mg_authorize_digest(&conn->mg_conn, fp);
4230 static int is_authorized_for_dav(struct connection *conn) {
4231 const char *auth_file = conn->server->config_options[DAV_AUTH_FILE];
4232 const char *method = conn->mg_conn.request_method;
4234 int authorized = MG_FALSE;
4236 // If dav_auth_file is not set, allow non-authorized PROPFIND
4237 if (method != NULL && !strcmp(method, "PROPFIND") && auth_file == NULL) {
4238 authorized = MG_TRUE;
4239 } else if (auth_file != NULL && (fp = fopen(auth_file, "r")) != NULL) {
4240 authorized = mg_authorize_digest(&conn->mg_conn, fp);
4246 #endif // MONGOOSE_NO_AUTH
4248 static int parse_header(const char *str, size_t str_len, const char *var_name,
4249 char *buf, size_t buf_size) {
4250 int ch = ' ', ch1 = ',', len = 0;
4251 size_t n = strlen(var_name);
4252 const char *p, *end = str + str_len, *s = NULL;
4254 if (buf != NULL && buf_size > 0) buf[0] = '\0';
4256 // Find where variable starts
4257 for (s = str; s != NULL && s + n < end; s++) {
4258 if ((s == str || s[-1] == ch || s[-1] == ch1) && s[n] == '=' &&
4259 !memcmp(s, var_name, n)) break;
4262 if (s != NULL && &s[n + 1] < end) {
4264 if (*s == '"' || *s == '\'') ch = ch1 = *s++;
4266 while (p < end && p[0] != ch && p[0] != ch1 && len < (int) buf_size) {
4267 if (ch == ch1 && p[0] == '\\' && p[1] == ch) p++;
4270 if (len >= (int) buf_size || (ch != ' ' && *p != ch)) {
4273 if (len > 0 && s[len - 1] == ',') len--;
4274 if (len > 0 && s[len - 1] == ';') len--;
4282 int mg_parse_header(const char *s, const char *var_name, char *buf,
4284 return parse_header(s, s == NULL ? 0 : strlen(s), var_name, buf, buf_size);
4287 #ifndef MONGOOSE_NO_SSI
4288 static void send_ssi_file(struct mg_connection *, const char *, FILE *, int);
4290 static void send_file_data(struct mg_connection *conn, FILE *fp) {
4291 char buf[IOBUF_SIZE];
4293 while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
4294 mg_write(conn, buf, n);
4298 static void do_ssi_include(struct mg_connection *conn, const char *ssi,
4299 char *tag, int include_level) {
4300 char file_name[IOBUF_SIZE], path[MAX_PATH_SIZE], *p;
4301 char **opts = (MG_CONN_2_CONN(conn))->server->config_options;
4304 // sscanf() is safe here, since send_ssi_file() also uses buffer
4305 // of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
4306 if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
4307 // File name is relative to the webserver root
4308 mg_snprintf(path, sizeof(path), "%s%c%s",
4309 opts[DOCUMENT_ROOT], '/', file_name);
4310 } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
4311 // File name is relative to the webserver working directory
4312 // or it is absolute system path
4313 mg_snprintf(path, sizeof(path), "%s", file_name);
4314 } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
4315 sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
4316 // File name is relative to the current document
4317 mg_snprintf(path, sizeof(path), "%s", ssi);
4318 if ((p = strrchr(path, '/')) != NULL) {
4321 mg_snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s",
4324 mg_printf(conn, "Bad SSI #include: [%s]", tag);
4328 if ((fp = fopen(path, "rb")) == NULL) {
4329 mg_printf(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",
4330 tag, path, strerror(errno));
4332 ns_set_close_on_exec(fileno(fp));
4333 if (mg_match_prefix(opts[SSI_PATTERN], strlen(opts[SSI_PATTERN]),
4335 send_ssi_file(conn, path, fp, include_level + 1);
4337 send_file_data(conn, fp);
4343 #ifndef MONGOOSE_NO_POPEN
4344 static void do_ssi_exec(struct mg_connection *conn, char *tag) {
4345 char cmd[IOBUF_SIZE];
4348 if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
4349 mg_printf(conn, "Bad SSI #exec: [%s]", tag);
4350 } else if ((fp = popen(cmd, "r")) == NULL) {
4351 mg_printf(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(errno));
4353 send_file_data(conn, fp);
4357 #endif // !MONGOOSE_NO_POPEN
4359 static void send_ssi_file(struct mg_connection *conn, const char *path,
4360 FILE *fp, int include_level) {
4361 char buf[IOBUF_SIZE];
4362 int ch, offset, len, in_ssi_tag;
4364 if (include_level > 10) {
4365 mg_printf(conn, "SSI #include level is too deep (%s)", path);
4369 in_ssi_tag = len = offset = 0;
4370 while ((ch = fgetc(fp)) != EOF) {
4371 if (in_ssi_tag && ch == '>') {
4373 buf[len++] = (char) ch;
4375 assert(len <= (int) sizeof(buf));
4376 if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
4377 // Not an SSI tag, pass it
4378 (void) mg_write(conn, buf, (size_t) len);
4380 if (!memcmp(buf + 5, "include", 7)) {
4381 do_ssi_include(conn, path, buf + 12, include_level);
4382 #if !defined(MONGOOSE_NO_POPEN)
4383 } else if (!memcmp(buf + 5, "exec", 4)) {
4384 do_ssi_exec(conn, buf + 9);
4387 mg_printf(conn, "%s: unknown SSI " "command: \"%s\"", path, buf);
4391 } else if (in_ssi_tag) {
4392 if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
4395 } else if (len == (int) sizeof(buf) - 2) {
4396 mg_printf(conn, "%s: SSI tag is too large", path);
4399 buf[len++] = ch & 0xff;
4400 } else if (ch == '<') {
4403 mg_write(conn, buf, (size_t) len);
4406 buf[len++] = ch & 0xff;
4408 buf[len++] = ch & 0xff;
4409 if (len == (int) sizeof(buf)) {
4410 mg_write(conn, buf, (size_t) len);
4416 // Send the rest of buffered data
4418 mg_write(conn, buf, (size_t) len);
4422 static void handle_ssi_request(struct connection *conn, const char *path) {
4424 struct vec mime_vec;
4426 if ((fp = fopen(path, "rb")) == NULL) {
4427 send_http_error(conn, 500, "fopen(%s): %s", path, strerror(errno));
4429 ns_set_close_on_exec(fileno(fp));
4430 get_mime_type(conn->server, path, &mime_vec);
4431 conn->mg_conn.status_code = 200;
4432 mg_printf(&conn->mg_conn,
4433 "HTTP/1.1 %d OK\r\n"
4434 "Content-Type: %.*s\r\n"
4435 "Connection: close\r\n\r\n",
4436 conn->mg_conn.status_code, (int) mime_vec.len, mime_vec.ptr);
4437 send_ssi_file(&conn->mg_conn, path, fp, 0);
4439 close_local_endpoint(conn);
4444 static void proxy_request(struct ns_connection *pc, struct mg_connection *c) {
4445 int i, sent_close_header = 0;
4447 ns_printf(pc, "%s %s%s%s HTTP/%s\r\n", c->request_method, c->uri,
4448 c->query_string ? "?" : "",
4449 c->query_string ? c->query_string : "",
4451 for (i = 0; i < c->num_headers; i++) {
4452 if (mg_strcasecmp(c->http_headers[i].name, "Connection") == 0) {
4453 // Force connection close, cause we don't parse proxy replies
4454 // therefore we don't know message boundaries
4455 ns_printf(pc, "%s: %s\r\n", "Connection", "close");
4456 sent_close_header = 1;
4458 ns_printf(pc, "%s: %s\r\n", c->http_headers[i].name,
4459 c->http_headers[i].value);
4462 if (!sent_close_header) {
4463 ns_printf(pc, "%s: %s\r\n", "Connection", "close");
4465 ns_printf(pc, "%s", "\r\n");
4466 ns_send(pc, c->content, c->content_len);
4470 #ifdef NS_ENABLE_SSL
4471 int mg_terminate_ssl(struct mg_connection *c, const char *cert) {
4472 static const char ok[] = "HTTP/1.0 200 OK\r\n\r\n";
4473 struct connection *conn = MG_CONN_2_CONN(c);
4476 DBG(("%p MITM", conn));
4477 if ((ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) return 0;
4479 SSL_CTX_use_certificate_file(ctx, cert, 1);
4480 SSL_CTX_use_PrivateKey_file(ctx, cert, 1);
4481 SSL_CTX_use_certificate_chain_file(ctx, cert);
4483 // When clear-text reply is pushed to client, switch to SSL mode.
4484 // TODO(lsm): check for send() failure
4485 send(conn->ns_conn->sock, ok, sizeof(ok) - 1, 0);
4486 //DBG(("%p %lu %d SEND", c, (unsigned long) sizeof(ok) - 1, n));
4487 conn->ns_conn->send_iobuf.len = 0;
4488 conn->endpoint_type = EP_USER; // To keep-alive in close_local_endpoint()
4489 close_local_endpoint(conn); // Clean up current CONNECT request
4490 if ((conn->ns_conn->ssl = SSL_new(ctx)) != NULL) {
4491 SSL_set_fd(conn->ns_conn->ssl, conn->ns_conn->sock);
4498 int mg_forward(struct mg_connection *c, const char *addr) {
4499 static const char ok[] = "HTTP/1.1 200 OK\r\n\r\n";
4500 struct connection *conn = MG_CONN_2_CONN(c);
4501 struct ns_connection *pc;
4503 if ((pc = ns_connect(&conn->server->ns_mgr, addr,
4504 mg_ev_handler, conn)) == NULL) {
4505 conn->ns_conn->flags |= NSF_CLOSE_IMMEDIATELY;
4509 // Interlink two connections
4510 pc->flags |= MG_PROXY_CONN;
4511 conn->endpoint_type = EP_PROXY;
4512 conn->endpoint.nc = pc;
4513 DBG(("%p [%s] [%s] -> %p %p", conn, c->uri, addr, pc, conn->ns_conn->ssl));
4515 if (strcmp(c->request_method, "CONNECT") == 0) {
4516 // For CONNECT request, reply with 200 OK. Tunnel is established.
4517 // TODO(lsm): check for send() failure
4518 (void) send(conn->ns_conn->sock, ok, sizeof(ok) - 1, 0);
4520 // Strip "http://host:port" part from the URI
4521 if (memcmp(c->uri, "http://", 7) == 0) c->uri += 7;
4522 while (*c->uri != '\0' && *c->uri != '/') c->uri++;
4523 proxy_request(pc, c);
4528 static void proxify_connection(struct connection *conn) {
4529 char proto[10], host[500], cert[500], addr[1000];
4530 unsigned short port = 80;
4531 struct mg_connection *c = &conn->mg_conn;
4533 const char *url = c->uri;
4535 proto[0] = host[0] = cert[0] = '\0';
4536 if (sscanf(url, "%499[^: ]:%hu%n", host, &port, &n) != 2 &&
4537 sscanf(url, "%9[a-z]://%499[^: ]:%hu%n", proto, host, &port, &n) != 3 &&
4538 sscanf(url, "%9[a-z]://%499[^/ ]%n", proto, host, &n) != 2) {
4542 snprintf(addr, sizeof(addr), "%s://%s:%hu",
4543 conn->ns_conn->ssl != NULL ? "ssl" : "tcp", host, port);
4544 if (n <= 0 || !mg_forward(c, addr)) {
4545 conn->ns_conn->flags |= NSF_CLOSE_IMMEDIATELY;
4549 #ifndef MONGOOSE_NO_FILESYSTEM
4550 void mg_send_file_internal(struct mg_connection *c, const char *file_name,
4551 file_stat_t *st, int exists,
4552 const char *extra_headers) {
4553 struct connection *conn = MG_CONN_2_CONN(c);
4554 char path[MAX_PATH_SIZE];
4555 const int is_directory = S_ISDIR(st->st_mode);
4556 #ifndef MONGOOSE_NO_CGI
4557 const char *cgi_pat = conn->server->config_options[CGI_PATTERN];
4559 const char *cgi_pat = DEFAULT_CGI_PATTERN;
4561 #ifndef MONGOOSE_NO_DIRECTORY_LISTING
4562 const char *dir_lst = conn->server->config_options[ENABLE_DIRECTORY_LISTING];
4564 const char *dir_lst = "yes";
4567 mg_snprintf(path, sizeof(path), "%s", file_name);
4569 if (!exists || must_hide_file(conn, path)) {
4570 send_http_error(conn, 404, NULL);
4571 } else if (is_directory &&
4572 conn->mg_conn.uri[strlen(conn->mg_conn.uri) - 1] != '/') {
4573 conn->mg_conn.status_code = 301;
4574 mg_printf(&conn->mg_conn, "HTTP/1.1 301 Moved Permanently\r\n"
4575 "Location: %s/\r\n\r\n", conn->mg_conn.uri);
4576 close_local_endpoint(conn);
4577 } else if (is_directory && !find_index_file(conn, path, sizeof(path), st)) {
4578 if (!mg_strcasecmp(dir_lst, "yes")) {
4579 #ifndef MONGOOSE_NO_DIRECTORY_LISTING
4580 send_directory_listing(conn, path);
4582 send_http_error(conn, 501, NULL);
4585 send_http_error(conn, 403, NULL);
4587 } else if (mg_match_prefix(cgi_pat, strlen(cgi_pat), path) > 0) {
4588 #if !defined(MONGOOSE_NO_CGI)
4589 open_cgi_endpoint(conn, path);
4591 send_http_error(conn, 501, NULL);
4592 #endif // !MONGOOSE_NO_CGI
4593 #ifndef MONGOOSE_NO_SSI
4594 } else if (mg_match_prefix(conn->server->config_options[SSI_PATTERN],
4595 strlen(conn->server->config_options[SSI_PATTERN]),
4597 handle_ssi_request(conn, path);
4599 } else if (is_not_modified(conn, st)) {
4600 send_http_error(conn, 304, NULL);
4601 } else if ((conn->endpoint.fd = open(path, O_RDONLY | O_BINARY, 0)) != -1) {
4602 // O_BINARY is required for Windows, otherwise in default text mode
4603 // two bytes \r\n will be read as one.
4604 open_file_endpoint(conn, path, st, extra_headers);
4606 send_http_error(conn, 404, NULL);
4609 void mg_send_file(struct mg_connection *c, const char *file_name,
4610 const char *extra_headers) {
4612 const int exists = stat(file_name, &st) == 0;
4613 mg_send_file_internal(c, file_name, &st, exists, extra_headers);
4615 #endif // !MONGOOSE_NO_FILESYSTEM
4617 static void open_local_endpoint(struct connection *conn, int skip_user) {
4618 #ifndef MONGOOSE_NO_FILESYSTEM
4619 char path[MAX_PATH_SIZE];
4624 // If EP_USER was set in a prev call, reset it
4625 conn->endpoint_type = EP_NONE;
4627 #ifndef MONGOOSE_NO_AUTH
4628 if (conn->server->event_handler && call_user(conn, MG_AUTH) == MG_FALSE) {
4629 mg_send_digest_auth_request(&conn->mg_conn);
4634 // Call URI handler if one is registered for this URI
4635 if (skip_user == 0 && conn->server->event_handler != NULL) {
4636 conn->endpoint_type = EP_USER;
4637 #if MONGOOSE_POST_SIZE_LIMIT > 1
4639 const char *cl = mg_get_header(&conn->mg_conn, "Content-Length");
4640 if ((strcmp(conn->mg_conn.request_method, "POST") == 0 ||
4641 strcmp(conn->mg_conn.request_method, "PUT") == 0) &&
4642 (cl == NULL || to64(cl) > MONGOOSE_POST_SIZE_LIMIT)) {
4643 send_http_error(conn, 500, "POST size > %lu",
4644 (unsigned long) MONGOOSE_POST_SIZE_LIMIT);
4651 if (strcmp(conn->mg_conn.request_method, "CONNECT") == 0 ||
4652 mg_strncasecmp(conn->mg_conn.uri, "http", 4) == 0) {
4653 const char *enp = conn->server->config_options[ENABLE_PROXY];
4654 if (enp == NULL || strcmp(enp, "yes") != 0) {
4655 send_http_error(conn, 405, NULL);
4657 proxify_connection(conn);
4662 if (!strcmp(conn->mg_conn.request_method, "OPTIONS")) {
4667 #ifdef MONGOOSE_NO_FILESYSTEM
4668 send_http_error(conn, 404, NULL);
4670 exists = convert_uri_to_file_name(conn, path, sizeof(path), &st);
4672 if (!strcmp(conn->mg_conn.request_method, "OPTIONS")) {
4674 } else if (conn->server->config_options[DOCUMENT_ROOT] == NULL) {
4675 send_http_error(conn, 404, NULL);
4676 #ifndef MONGOOSE_NO_AUTH
4677 } else if ((!is_dav_request(conn) && !is_authorized(conn, path,
4678 exists && S_ISDIR(st.st_mode))) ||
4679 (is_dav_request(conn) && !is_authorized_for_dav(conn))) {
4680 mg_send_digest_auth_request(&conn->mg_conn);
4681 close_local_endpoint(conn);
4683 #ifndef MONGOOSE_NO_DAV
4684 } else if (must_hide_file(conn, path)) {
4685 send_http_error(conn, 404, NULL);
4686 } else if (!strcmp(conn->mg_conn.request_method, "PROPFIND")) {
4687 handle_propfind(conn, path, &st, exists);
4688 } else if (!strcmp(conn->mg_conn.request_method, "MKCOL")) {
4689 handle_mkcol(conn, path);
4690 } else if (!strcmp(conn->mg_conn.request_method, "DELETE")) {
4691 handle_delete(conn, path);
4692 } else if (!strcmp(conn->mg_conn.request_method, "PUT")) {
4693 handle_put(conn, path);
4696 mg_send_file_internal(&conn->mg_conn, path, &st, exists, NULL);
4698 #endif // MONGOOSE_NO_FILESYSTEM
4701 static void send_continue_if_expected(struct connection *conn) {
4702 static const char expect_response[] = "HTTP/1.1 100 Continue\r\n\r\n";
4703 const char *expect_hdr = mg_get_header(&conn->mg_conn, "Expect");
4705 if (expect_hdr != NULL && !mg_strcasecmp(expect_hdr, "100-continue")) {
4706 ns_send(conn->ns_conn, expect_response, sizeof(expect_response) - 1);
4710 // Conform to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
4711 static int is_valid_uri(const char *uri) {
4713 return uri[0] == '/' ||
4714 strcmp(uri, "*") == 0 || // OPTIONS method can use asterisk URI
4715 mg_strncasecmp(uri, "http", 4) == 0 || // Naive check for the absolute URI
4716 sscanf(uri, "%*[^ :]:%hu", &n) > 0; // CONNECT method can use host:port
4719 static void try_parse(struct connection *conn) {
4720 struct iobuf *io = &conn->ns_conn->recv_iobuf;
4722 if (conn->request_len == 0 &&
4723 (conn->request_len = get_request_len(io->buf, io->len)) > 0) {
4724 // If request is buffered in, remove it from the iobuf. This is because
4725 // iobuf could be reallocated, and pointers in parsed request could
4727 conn->request = (char *) NS_MALLOC(conn->request_len);
4728 if (conn->request == NULL) {
4729 conn->ns_conn->flags |= NSF_CLOSE_IMMEDIATELY;
4732 memcpy(conn->request, io->buf, conn->request_len);
4733 //DBG(("%p [%.*s]", conn, conn->request_len, conn->request));
4734 iobuf_remove(io, conn->request_len);
4735 conn->request_len = parse_http_message(conn->request, conn->request_len,
4737 if (conn->request_len > 0) {
4738 const char *cl_hdr = mg_get_header(&conn->mg_conn, "Content-Length");
4739 conn->cl = cl_hdr == NULL ? 0 : to64(cl_hdr);
4740 conn->mg_conn.content_len = (size_t) conn->cl;
4745 static void do_proxy(struct connection *conn) {
4746 if (0 && conn->request_len == 0) {
4748 DBG(("%p parsing -> %d", conn, conn->request_len));
4749 if (conn->request_len > 0 && call_user(conn, MG_REQUEST) == MG_FALSE) {
4750 proxy_request(conn->endpoint.nc, &conn->mg_conn);
4751 } else if (conn->request_len < 0) {
4752 ns_forward(conn->ns_conn, conn->endpoint.nc);
4755 DBG(("%p forwarding", conn));
4756 ns_forward(conn->ns_conn, conn->endpoint.nc);
4760 static void on_recv_data(struct connection *conn) {
4761 struct iobuf *io = &conn->ns_conn->recv_iobuf;
4764 if (conn->endpoint_type == EP_PROXY) {
4765 if (conn->endpoint.nc != NULL) do_proxy(conn);
4770 DBG(("%p %d %lu %d", conn, conn->request_len, (unsigned long)io->len,
4771 conn->ns_conn->flags));
4772 if (conn->request_len < 0 ||
4773 (conn->request_len > 0 && !is_valid_uri(conn->mg_conn.uri))) {
4774 send_http_error(conn, 400, NULL);
4775 } else if (conn->request_len == 0 && io->len > MAX_REQUEST_SIZE) {
4776 send_http_error(conn, 413, NULL);
4777 } else if (conn->request_len > 0 &&
4778 strcmp(conn->mg_conn.http_version, "1.0") != 0 &&
4779 strcmp(conn->mg_conn.http_version, "1.1") != 0) {
4780 send_http_error(conn, 505, NULL);
4781 } else if (conn->request_len > 0 && conn->endpoint_type == EP_NONE) {
4782 #ifndef MONGOOSE_NO_WEBSOCKET
4783 send_websocket_handshake_if_requested(&conn->mg_conn);
4785 send_continue_if_expected(conn);
4786 open_local_endpoint(conn, 0);
4789 #ifndef MONGOOSE_NO_CGI
4790 if (conn->endpoint_type == EP_CGI && conn->endpoint.nc != NULL) {
4791 ns_forward(conn->ns_conn, conn->endpoint.nc);
4794 if (conn->endpoint_type == EP_USER) {
4795 conn->mg_conn.content = io->buf;
4796 conn->mg_conn.content_len = io->len;
4797 n = call_user(conn, MG_RECV);
4799 conn->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
4800 } else if ((size_t) n <= io->len) {
4801 iobuf_remove(io, n);
4803 call_request_handler_if_data_is_buffered(conn);
4805 #ifndef MONGOOSE_NO_DAV
4806 if (conn->endpoint_type == EP_PUT && io->len > 0) {
4807 forward_put_data(conn);
4812 static void call_http_client_handler(struct connection *conn) {
4813 //conn->mg_conn.status_code = code;
4814 // For responses without Content-Lengh, use the whole buffer
4815 if (conn->cl == 0) {
4816 conn->mg_conn.content_len = conn->ns_conn->recv_iobuf.len;
4818 conn->mg_conn.content = conn->ns_conn->recv_iobuf.buf;
4819 if (call_user(conn, MG_REPLY) == MG_FALSE) {
4820 conn->ns_conn->flags |= NSF_CLOSE_IMMEDIATELY;
4822 iobuf_remove(&conn->ns_conn->recv_iobuf, conn->mg_conn.content_len);
4823 conn->mg_conn.status_code = 0;
4824 conn->cl = conn->num_bytes_recv = conn->request_len = 0;
4825 NS_FREE(conn->request);
4826 conn->request = NULL;
4829 static void process_response(struct connection *conn) {
4830 struct iobuf *io = &conn->ns_conn->recv_iobuf;
4833 DBG(("%p %d %lu", conn, conn->request_len, (unsigned long)io->len));
4834 if (conn->request_len < 0 ||
4835 (conn->request_len == 0 && io->len > MAX_REQUEST_SIZE)) {
4836 call_http_client_handler(conn);
4837 } else if ((int64_t) io->len >= conn->cl) {
4838 call_http_client_handler(conn);
4842 struct mg_connection *mg_connect(struct mg_server *server, const char *addr) {
4843 struct ns_connection *nsconn;
4844 struct connection *conn;
4846 nsconn = ns_connect(&server->ns_mgr, addr, mg_ev_handler, NULL);
4847 if (nsconn == NULL) return 0;
4849 if ((conn = (struct connection *) NS_CALLOC(1, sizeof(*conn))) == NULL) {
4850 nsconn->flags |= NSF_CLOSE_IMMEDIATELY;
4854 // Interlink two structs
4855 conn->ns_conn = nsconn;
4856 nsconn->user_data = conn;
4858 conn->server = server;
4859 conn->endpoint_type = EP_CLIENT;
4860 //conn->handler = handler;
4861 conn->mg_conn.server_param = server->ns_mgr.user_data;
4862 conn->ns_conn->flags = NSF_CONNECTING;
4864 return &conn->mg_conn;
4867 #ifndef MONGOOSE_NO_LOGGING
4868 static void log_header(const struct mg_connection *conn, const char *header,
4870 const char *header_value;
4872 if ((header_value = mg_get_header(conn, header)) == NULL) {
4873 (void) fprintf(fp, "%s", " -");
4875 (void) fprintf(fp, " \"%s\"", header_value);
4879 static void log_access(const struct connection *conn, const char *path) {
4880 const struct mg_connection *c = &conn->mg_conn;
4881 FILE *fp = (path == NULL) ? NULL : fopen(path, "a+");
4882 char date[64], user[100];
4885 if (fp == NULL) return;
4887 strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", localtime(&now));
4890 mg_parse_header(mg_get_header(&conn->mg_conn, "Authorization"), "username",
4891 user, sizeof(user));
4892 fprintf(fp, "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d 0",
4893 c->remote_ip, user[0] == '\0' ? "-" : user, date,
4894 c->request_method ? c->request_method : "-",
4895 c->uri ? c->uri : "-", c->query_string ? "?" : "",
4896 c->query_string ? c->query_string : "",
4897 c->http_version, c->status_code);
4898 log_header(c, "Referer", fp);
4899 log_header(c, "User-Agent", fp);
4908 static void close_local_endpoint(struct connection *conn) {
4909 struct mg_connection *c = &conn->mg_conn;
4910 // Must be done before free()
4911 int keep_alive = should_keep_alive(&conn->mg_conn) &&
4912 (conn->endpoint_type == EP_FILE || conn->endpoint_type == EP_USER);
4913 DBG(("%p %d %d %d", conn, conn->endpoint_type, keep_alive,
4914 conn->ns_conn->flags));
4916 switch (conn->endpoint_type) {
4919 close(conn->endpoint.fd);
4923 if (conn->endpoint.nc != NULL) {
4924 DBG(("%p %p %p :-)", conn, conn->ns_conn, conn->endpoint.nc));
4925 conn->endpoint.nc->flags |= NSF_CLOSE_IMMEDIATELY;
4926 conn->endpoint.nc->user_data = NULL;
4932 #ifndef MONGOOSE_NO_LOGGING
4933 if (c->status_code > 0 && conn->endpoint_type != EP_CLIENT &&
4934 c->status_code != 400) {
4935 log_access(conn, conn->server->config_options[ACCESS_LOG_FILE]);
4939 // Gobble possible POST data sent to the URI handler
4940 iobuf_free(&conn->ns_conn->recv_iobuf);
4941 NS_FREE(conn->request);
4942 NS_FREE(conn->path_info);
4943 conn->endpoint.nc = NULL;
4944 conn->request = conn->path_info = NULL;
4946 conn->endpoint_type = EP_NONE;
4947 conn->cl = conn->num_bytes_recv = conn->request_len = 0;
4948 conn->ns_conn->flags &= ~(NSF_FINISHED_SENDING_DATA |
4949 NSF_BUFFER_BUT_DONT_SEND | NSF_CLOSE_IMMEDIATELY |
4950 MG_HEADERS_SENT | MG_USING_CHUNKED_API);
4952 // Do not memset() the whole structure, as some of the fields
4953 // (IP addresses & ports, server_param) must survive. Nullify the rest.
4954 c->request_method = c->uri = c->http_version = c->query_string = NULL;
4955 c->num_headers = c->status_code = c->is_websocket = c->content_len = 0;
4956 c->connection_param = c->callback_param = NULL;
4959 on_recv_data(conn); // Can call us recursively if pipelining is used
4961 conn->ns_conn->flags |= conn->ns_conn->send_iobuf.len == 0 ?
4962 NSF_CLOSE_IMMEDIATELY : NSF_FINISHED_SENDING_DATA;
4966 static void transfer_file_data(struct connection *conn) {
4967 char buf[IOBUF_SIZE];
4970 // If output buffer is too big, don't send anything. Wait until
4971 // mongoose drains already buffered data to the client.
4972 if (conn->ns_conn->send_iobuf.len > sizeof(buf) * 2) return;
4975 n = read(conn->endpoint.fd, buf, conn->cl < (int64_t) sizeof(buf) ?
4976 (int) conn->cl : (int) sizeof(buf));
4979 close_local_endpoint(conn);
4982 ns_send(conn->ns_conn, buf, n);
4983 if (conn->cl <= 0) {
4984 close_local_endpoint(conn);
4989 time_t mg_poll_server(struct mg_server *server, int milliseconds) {
4990 return ns_mgr_poll(&server->ns_mgr, milliseconds);
4993 void mg_destroy_server(struct mg_server **server) {
4994 if (server != NULL && *server != NULL) {
4995 struct mg_server *s = *server;
4998 ns_mgr_free(&s->ns_mgr);
4999 for (i = 0; i < (int) ARRAY_SIZE(s->config_options); i++) {
5000 NS_FREE(s->config_options[i]); // It is OK to free(NULL)
5007 struct mg_connection *mg_next(struct mg_server *s, struct mg_connection *c) {
5008 struct ns_connection *nc = ns_next(&s->ns_mgr, c == NULL ? NULL :
5009 MG_CONN_2_CONN(c)->ns_conn);
5010 if (nc != NULL && nc->user_data != NULL) {
5011 return & ((struct connection *) nc->user_data)->mg_conn;
5017 static int get_var(const char *data, size_t data_len, const char *name,
5018 char *dst, size_t dst_len, int n) {
5019 const char *p, *e = data + data_len, *s;
5021 int i = 0, len = -1;
5023 if (dst == NULL || dst_len == 0) {
5025 } else if (data == NULL || name == NULL || data_len == 0) {
5028 name_len = strlen(name);
5031 // data is "var1=val1&var2=val2...". Find variable first
5032 for (p = data; p + name_len < e; p++) {
5033 if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
5034 !mg_strncasecmp(name, p, name_len)) {
5036 if (n != i++) continue;
5038 // Point p to variable value
5041 // Point s to the end of the value
5042 s = (const char *) memchr(p, '&', (size_t)(e - p));
5048 // Decode variable into destination buffer
5049 len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
5051 // Redirect error code from -1 to -2 (destination buffer too small).
5063 int mg_get_var_n(const struct mg_connection *conn, const char *name,
5064 char *dst, size_t dst_len, int n) {
5065 int len = get_var(conn->query_string, conn->query_string == NULL ? 0 :
5066 strlen(conn->query_string), name, dst, dst_len, n);
5068 len = get_var(conn->content, conn->content_len, name, dst, dst_len, n);
5073 int mg_get_var(const struct mg_connection *conn, const char *name,
5074 char *dst, size_t dst_len) {
5075 return mg_get_var_n(conn, name, dst, dst_len, 0);
5078 static int get_line_len(const char *buf, int buf_len) {
5080 while (len < buf_len && buf[len] != '\n') len++;
5081 return buf[len] == '\n' ? len + 1: -1;
5084 int mg_parse_multipart(const char *buf, int buf_len,
5085 char *var_name, int var_name_len,
5086 char *file_name, int file_name_len,
5087 const char **data, int *data_len) {
5088 static const char cd[] = "Content-Disposition: ";
5089 //struct mg_connection c;
5090 int hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
5093 if (buf == NULL || buf_len <= 0) return 0;
5094 if ((hl = get_request_len(buf, buf_len)) <= 0) return 0;
5095 if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
5097 // Get boundary length
5098 bl = get_line_len(buf, buf_len);
5100 // Loop through headers, fetch variable name and file name
5101 var_name[0] = file_name[0] = '\0';
5102 for (n = bl; (ll = get_line_len(buf + n, hl - n)) > 0; n += ll) {
5103 if (mg_strncasecmp(cd, buf + n, cdl) == 0) {
5104 parse_header(buf + n + cdl, ll - (cdl + 2), "name",
5105 var_name, var_name_len);
5106 parse_header(buf + n + cdl, ll - (cdl + 2), "filename",
5107 file_name, file_name_len);
5111 // Scan body, search for terminating boundary
5112 for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
5113 if (buf[pos] == '-' && !memcmp(buf, &buf[pos], bl - 2)) {
5114 if (data_len != NULL) *data_len = (pos - 2) - hl;
5115 if (data != NULL) *data = buf + hl;
5123 const char **mg_get_valid_option_names(void) {
5124 return static_config_options;
5127 void mg_copy_listeners(struct mg_server *s, struct mg_server *to) {
5128 struct ns_connection *c;
5129 for (c = ns_next(&s->ns_mgr, NULL); c != NULL; c = ns_next(&s->ns_mgr, c)) {
5130 struct ns_connection *tmp;
5131 if ((c->flags & NSF_LISTENING) &&
5132 (tmp = (struct ns_connection *) NS_MALLOC(sizeof(*tmp))) != NULL) {
5133 memcpy(tmp, c, sizeof(*tmp));
5135 #if defined(NS_ENABLE_SSL) && defined(HEADER_SSL_H)
5136 /* OpenSSL only. See https://github.com/cesanta/mongoose/issues/441 */
5137 if (tmp->ssl_ctx != NULL) {
5138 tmp->ssl_ctx->references++;
5142 tmp->mgr = &to->ns_mgr;
5143 ns_add_conn(tmp->mgr, tmp);
5148 static int get_option_index(const char *name) {
5151 for (i = 0; static_config_options[i * 2] != NULL; i++) {
5152 if (strcmp(static_config_options[i * 2], name) == 0) {
5159 static void set_default_option_values(char **opts) {
5160 const char *value, **all_opts = mg_get_valid_option_names();
5163 for (i = 0; all_opts[i * 2] != NULL; i++) {
5164 value = all_opts[i * 2 + 1];
5165 if (opts[i] == NULL && value != NULL) {
5166 opts[i] = mg_strdup(value);
5171 const char *mg_set_option(struct mg_server *server, const char *name,
5172 const char *value) {
5173 int ind = get_option_index(name);
5174 const char *error_msg = NULL;
5177 if (ind < 0) return "No such option";
5178 v = &server->config_options[ind];
5180 // Return success immediately if setting to the same value
5181 if ((*v == NULL && value == NULL) ||
5182 (value != NULL && *v != NULL && !strcmp(value, *v))) {
5191 if (value == NULL || value[0] == '\0') return NULL;
5193 *v = mg_strdup(value);
5194 DBG(("%s [%s]", name, *v));
5196 if (ind == LISTENING_PORT) {
5202 * Ports can be specified as 0, meaning that OS has to choose any
5203 * free port that is available. In order to pass chosen port number to
5204 * the user, we rewrite all 0 port to chosen values.
5206 while ((value = next_option(value, &vec, NULL)) != NULL) {
5207 struct ns_connection *c = ns_bind(&server->ns_mgr, vec.ptr,
5208 mg_ev_handler, NULL);
5210 error_msg = "Cannot bind to port";
5213 char buf2[50], cert[100], ca[100];
5214 union socket_address sa;
5217 ns_parse_address(vec.ptr, &sa, &proto, &use_ssl, cert, ca);
5218 ns_sock_to_str(c->sock, buf2, sizeof(buf2),
5219 memchr(vec.ptr, ':', vec.len) == NULL ? 2 : 3);
5221 n += snprintf(buf + n, sizeof(buf) - n, "%s%s%s%s%s%s%s",
5223 use_ssl ? "ssl://" : "",
5224 buf2, cert[0] ? ":" : "", cert, ca[0] ? ":" : "", ca);
5227 buf[sizeof(buf) - 1] = '\0';
5229 *v = mg_strdup(buf);
5230 #ifndef MONGOOSE_NO_FILESYSTEM
5231 } else if (ind == HEXDUMP_FILE) {
5232 server->ns_mgr.hexdump_file = *v;
5234 #if !defined(_WIN32) && !defined(MONGOOSE_NO_USER)
5235 } else if (ind == RUN_AS_USER) {
5237 if ((pw = getpwnam(value)) == NULL) {
5238 error_msg = "Unknown user";
5239 } else if (setgid(pw->pw_gid) != 0) {
5240 error_msg = "setgid() failed";
5241 } else if (setuid(pw->pw_uid) != 0) {
5242 error_msg = "setuid() failed";
5250 static void set_ips(struct ns_connection *nc, int is_rem) {
5251 struct connection *conn = (struct connection *) nc->user_data;
5252 struct mg_connection *c = &conn->mg_conn;
5255 ns_sock_to_str(nc->sock, buf, sizeof(buf), is_rem ? 7 : 3);
5256 sscanf(buf, "%47[^:]:%hu",
5257 is_rem ? c->remote_ip : c->local_ip,
5258 is_rem ? &c->remote_port : &c->local_port);
5259 //DBG(("%p %s %s", conn, is_rem ? "rem" : "loc", buf));
5262 static void on_accept(struct ns_connection *nc, union socket_address *sa) {
5263 struct mg_server *server = (struct mg_server *) nc->mgr;
5264 struct connection *conn;
5266 if (!check_acl(server->config_options[ACCESS_CONTROL_LIST],
5267 ntohl(* (uint32_t *) &sa->sin.sin_addr)) ||
5268 (conn = (struct connection *) NS_CALLOC(1, sizeof(*conn))) == NULL) {
5269 nc->flags |= NSF_CLOSE_IMMEDIATELY;
5271 // Circularly link two connection structures
5272 nc->user_data = conn;
5275 // Initialize the rest of connection attributes
5276 conn->server = server;
5277 conn->mg_conn.server_param = nc->mgr->user_data;
5283 static void process_udp(struct ns_connection *nc) {
5284 struct iobuf *io = &nc->recv_iobuf;
5285 struct connection conn;
5287 memset(&conn, 0, sizeof(conn));
5289 conn.server = (struct mg_server *) nc->mgr;
5290 conn.request_len = parse_http_message(io->buf, io->len, &conn.mg_conn);
5291 on_recv_data(&conn);
5292 //ns_printf(nc, "%s", "HTTP/1.0 200 OK\r\n\r\n");
5295 #ifdef MONGOOSE_SEND_NS_EVENTS
5296 static void send_ns_event(struct ns_connection *nc, int ev, void *p) {
5297 struct connection *conn = (struct connection *) nc->user_data;
5299 void *param[2] = { nc, p };
5300 conn->mg_conn.callback_param = param;
5301 call_user(conn, (enum mg_event) ev);
5305 static void send_ns_event(struct ns_connection *nc, int ev, void *p) {
5306 (void) nc; (void) p; (void) ev;
5310 static void mg_ev_handler(struct ns_connection *nc, int ev, void *p) {
5311 struct connection *conn = (struct connection *) nc->user_data;
5313 // Send NS event to the handler. Note that call_user won't send an event
5314 // if conn == NULL. Therefore, repeat this for NS_ACCEPT event as well.
5315 send_ns_event(nc, ev, p);
5319 on_accept(nc, (union socket_address *) p);
5320 send_ns_event(nc, ev, p);
5324 if (nc->user_data != NULL) {
5328 conn->mg_conn.status_code = * (int *) p;
5329 if (conn->mg_conn.status_code != 0 ||
5330 (!(nc->flags & MG_PROXY_CONN) &&
5331 call_user(conn, MG_CONNECT) == MG_FALSE)) {
5332 nc->flags |= NSF_CLOSE_IMMEDIATELY;
5338 conn->num_bytes_recv += * (int *) p;
5341 if (nc->flags & NSF_UDP) {
5343 } else if (nc->listener != NULL) {
5345 #ifndef MONGOOSE_NO_CGI
5346 } else if (nc->flags & MG_CGI_CONN) {
5349 } else if (nc->flags & MG_PROXY_CONN) {
5351 ns_forward(nc, conn->ns_conn);
5354 process_response(conn);
5362 nc->user_data = NULL;
5363 if (nc->flags & (MG_CGI_CONN | MG_PROXY_CONN)) {
5364 DBG(("%p %p closing cgi/proxy conn", conn, nc));
5365 if (conn && conn->ns_conn) {
5366 conn->ns_conn->flags &= ~NSF_BUFFER_BUT_DONT_SEND;
5367 conn->ns_conn->flags |= conn->ns_conn->send_iobuf.len > 0 ?
5368 NSF_FINISHED_SENDING_DATA : NSF_CLOSE_IMMEDIATELY;
5369 conn->endpoint.nc = NULL;
5371 } else if (conn != NULL) {
5372 DBG(("%p %p %d closing", conn, nc, conn->endpoint_type));
5374 if (conn->endpoint_type == EP_CLIENT && nc->recv_iobuf.len > 0) {
5375 call_http_client_handler(conn);
5378 call_user(conn, MG_CLOSE);
5379 close_local_endpoint(conn);
5380 conn->ns_conn = NULL;
5387 if (call_user(conn, MG_POLL) == MG_TRUE) {
5388 if (conn->ns_conn->flags & MG_HEADERS_SENT) {
5389 write_terminating_chunk(conn);
5391 close_local_endpoint(conn);
5393 * MG_POLL callback returned MG_TRUE,
5394 * i.e. data is sent, set corresponding flag
5396 conn->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
5399 if (conn->endpoint_type == EP_FILE) {
5400 transfer_file_data(conn);
5404 // Expire idle connections
5406 time_t current_time = * (time_t *) p;
5408 if (conn != NULL && conn->mg_conn.is_websocket) {
5409 ping_idle_websocket_connection(conn, current_time);
5412 if (nc->listener != NULL &&
5413 nc->last_io_time + MONGOOSE_IDLE_TIMEOUT_SECONDS < current_time) {
5414 mg_ev_handler(nc, NS_CLOSE, NULL);
5415 nc->flags |= NSF_CLOSE_IMMEDIATELY;
5425 static void iter2(struct ns_connection *nc, int ev, void *param) {
5426 mg_handler_t func = NULL;
5427 struct connection *conn = (struct connection *) nc->user_data;
5428 const char *msg = (const char *) param;
5432 //DBG(("%p [%s]", conn, msg));
5433 if (sscanf(msg, "%p %n", &func, &n) && func != NULL && conn != NULL) {
5434 conn->mg_conn.callback_param = (void *) (msg + n);
5435 func(&conn->mg_conn, MG_POLL);
5439 void mg_wakeup_server_ex(struct mg_server *server, mg_handler_t cb,
5440 const char *fmt, ...) {
5445 // Encode callback (cb) into a buffer
5446 len = snprintf(buf, sizeof(buf), "%p ", cb);
5448 len += vsnprintf(buf + len, sizeof(buf) - len, fmt, ap);
5451 // "len + 1" is to include terminating \0 in the message
5452 ns_broadcast(&server->ns_mgr, iter2, buf, len + 1);
5455 void mg_wakeup_server(struct mg_server *server) {
5456 ns_broadcast(&server->ns_mgr, NULL, (void *) "", 0);
5459 const char *mg_get_option(const struct mg_server *server, const char *name) {
5460 const char **opts = (const char **) server->config_options;
5461 int i = get_option_index(name);
5462 return i == -1 ? NULL : opts[i] == NULL ? "" : opts[i];
5465 struct mg_server *mg_create_server(void *server_data, mg_handler_t handler) {
5466 struct mg_server *server = (struct mg_server *) NS_CALLOC(1, sizeof(*server));
5467 ns_mgr_init(&server->ns_mgr, server_data);
5468 set_default_option_values(server->config_options);
5469 server->event_handler = handler;