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 // $Date: 2014-09-16 06:47:40 UTC $
20 #ifdef NOEMBED_NET_SKELETON
21 #include "net_skeleton.h"
24 // Copyright (c) 2014 Cesanta Software Limited
25 // All rights reserved
27 // This software is dual-licensed: you can redistribute it and/or modify
28 // it under the terms of the GNU General Public License version 2 as
29 // published by the Free Software Foundation. For the terms of this
30 // license, see <http://www.gnu.org/licenses/>.
32 // You are free to use this software under the terms of the GNU General
33 // Public License, but WITHOUT ANY WARRANTY; without even the implied
34 // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
35 // See the GNU General Public License for more details.
37 // Alternatively, you can license this software under a commercial
38 // license, as set out in <http://cesanta.com/>.
40 // $Date: 2014-09-28 05:04:41 UTC $
42 #ifndef NS_SKELETON_HEADER_INCLUDED
43 #define NS_SKELETON_HEADER_INCLUDED
45 #define NS_SKELETON_VERSION "2.1.0"
47 #undef UNICODE // Use ANSI WinAPI functions
48 #undef _UNICODE // Use multibyte encoding on Windows
49 #define _MBCS // Use multibyte encoding on Windows
50 #define _INTEGRAL_MAX_BITS 64 // Enable _stati64() on Windows
51 #define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005+
52 #undef WIN32_LEAN_AND_MEAN // Let windows.h always include winsock2.h
53 #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 #include <sys/types.h>
82 #pragma comment(lib, "ws2_32.lib") // Linking with winsock library
87 #define EINPROGRESS WSAEINPROGRESS
90 #define EWOULDBLOCK WSAEWOULDBLOCK
94 #define STR(x) STRX(x)
95 #define __func__ __FILE__ ":" STR(__LINE__)
98 #define va_copy(x,y) x = y
99 #endif // MINGW #defines va_copy
100 #define snprintf _snprintf
101 #define vsnprintf _vsnprintf
102 #define sleep(x) Sleep((x) * 1000)
103 #define to64(x) _atoi64(x)
104 typedef int socklen_t;
105 typedef unsigned char uint8_t;
106 typedef unsigned int uint32_t;
107 typedef unsigned short uint16_t;
108 typedef unsigned __int64 uint64_t;
109 typedef __int64 int64_t;
110 typedef SOCKET sock_t;
111 typedef struct _stati64 ns_stat_t;
113 #define S_ISDIR(x) ((x) & _S_IFDIR)
122 #include <arpa/inet.h> // For inet_pton() when NS_ENABLE_IPV6 is defined
123 #include <netinet/in.h>
124 #include <sys/socket.h>
125 #include <sys/select.h>
126 #define closesocket(x) close(x)
128 #define INVALID_SOCKET (-1)
129 #define to64(x) strtoll(x, NULL, 10)
131 typedef struct stat ns_stat_t;
134 #ifdef NS_ENABLE_DEBUG
135 #define DBG(x) do { printf("%-20s ", __func__); printf x; putchar('\n'); \
136 fflush(stdout); } while(0)
142 #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
147 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
149 #include <openssl/ssl.h>
152 typedef void *SSL_CTX;
157 #endif // __cplusplus
159 union socket_address {
161 struct sockaddr_in sin;
162 #ifdef NS_ENABLE_IPV6
163 struct sockaddr_in6 sin6;
165 struct sockaddr sin6;
169 // Describes chunk of memory
175 // IO buffers interface
182 void iobuf_init(struct iobuf *, size_t initial_size);
183 void iobuf_free(struct iobuf *);
184 size_t iobuf_append(struct iobuf *, const void *data, size_t data_size);
185 void iobuf_remove(struct iobuf *, size_t data_size);
186 void iobuf_resize(struct iobuf *, size_t new_size);
188 // Callback function (event handler) prototype, must be defined by user.
189 // Net skeleton will call event handler, passing events defined above.
190 struct ns_connection;
191 typedef void (*ns_callback_t)(struct ns_connection *, int event_num, void *evp);
193 // Events. Meaning of event parameter (evp) is given in the comment.
194 #define NS_POLL 0 // Sent to each connection on each call to ns_mgr_poll()
195 #define NS_ACCEPT 1 // New connection accept()-ed. union socket_address *addr
196 #define NS_CONNECT 2 // connect() succeeded or failed. int *success_status
197 #define NS_RECV 3 // Data has benn received. int *num_bytes
198 #define NS_SEND 4 // Data has been written to a socket. int *num_bytes
199 #define NS_CLOSE 5 // Connection is closed. NULL
203 struct ns_connection *active_connections;
204 const char *hexdump_file; // Debug hexdump file path
205 sock_t ctl[2]; // Socketpair for mg_wakeup()
206 void *user_data; // User data
210 struct ns_connection {
211 struct ns_connection *next, *prev; // ns_mgr::active_connections linkage
212 struct ns_connection *listener; // Set only for accept()-ed connections
215 sock_t sock; // Socket
216 union socket_address sa; // Peer address
217 struct iobuf recv_iobuf; // Received data
218 struct iobuf send_iobuf; // Data scheduled for sending
221 void *user_data; // User-specific data
222 void *proto_data; // Application protocol-specific data
223 time_t last_io_time; // Timestamp of the last socket IO
224 ns_callback_t callback; // Event handler function
227 #define NSF_FINISHED_SENDING_DATA (1 << 0)
228 #define NSF_BUFFER_BUT_DONT_SEND (1 << 1)
229 #define NSF_SSL_HANDSHAKE_DONE (1 << 2)
230 #define NSF_CONNECTING (1 << 3)
231 #define NSF_CLOSE_IMMEDIATELY (1 << 4)
232 #define NSF_WANT_READ (1 << 5)
233 #define NSF_WANT_WRITE (1 << 6)
234 #define NSF_LISTENING (1 << 7)
235 #define NSF_UDP (1 << 8)
237 #define NSF_USER_1 (1 << 20)
238 #define NSF_USER_2 (1 << 21)
239 #define NSF_USER_3 (1 << 22)
240 #define NSF_USER_4 (1 << 23)
241 #define NSF_USER_5 (1 << 24)
242 #define NSF_USER_6 (1 << 25)
245 void ns_mgr_init(struct ns_mgr *, void *user_data);
246 void ns_mgr_free(struct ns_mgr *);
247 time_t ns_mgr_poll(struct ns_mgr *, int milli);
248 void ns_broadcast(struct ns_mgr *, ns_callback_t, void *, size_t);
250 struct ns_connection *ns_next(struct ns_mgr *, struct ns_connection *);
251 struct ns_connection *ns_add_sock(struct ns_mgr *, sock_t,
252 ns_callback_t, void *);
253 struct ns_connection *ns_bind(struct ns_mgr *, const char *,
254 ns_callback_t, void *);
255 struct ns_connection *ns_connect(struct ns_mgr *, const char *,
256 ns_callback_t, void *);
258 int ns_send(struct ns_connection *, const void *buf, int len);
259 int ns_printf(struct ns_connection *, const char *fmt, ...);
260 int ns_vprintf(struct ns_connection *, const char *fmt, va_list ap);
263 void *ns_start_thread(void *(*f)(void *), void *p);
264 int ns_socketpair(sock_t [2]);
265 int ns_socketpair2(sock_t [2], int sock_type); // SOCK_STREAM or SOCK_DGRAM
266 void ns_set_close_on_exec(sock_t);
267 void ns_sock_to_str(sock_t sock, char *buf, size_t len, int flags);
268 int ns_hexdump(const void *buf, int len, char *dst, int dst_len);
269 int ns_avprintf(char **buf, size_t size, const char *fmt, va_list ap);
270 int ns_resolve(const char *domain_name, char *ip_addr_buf, size_t buf_len);
274 #endif // __cplusplus
276 #endif // NS_SKELETON_HEADER_INCLUDED
277 // Copyright (c) 2014 Cesanta Software Limited
278 // All rights reserved
280 // This software is dual-licensed: you can redistribute it and/or modify
281 // it under the terms of the GNU General Public License version 2 as
282 // published by the Free Software Foundation. For the terms of this
283 // license, see <http://www.gnu.org/licenses/>.
285 // You are free to use this software under the terms of the GNU General
286 // Public License, but WITHOUT ANY WARRANTY; without even the implied
287 // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
288 // See the GNU General Public License for more details.
290 // Alternatively, you can license this software under a commercial
291 // license, as set out in <http://cesanta.com/>.
293 // $Date: 2014-09-28 05:04:41 UTC $
297 #define NS_MALLOC malloc
301 #define NS_REALLOC realloc
308 #define NS_UDP_RECEIVE_BUFFER_SIZE 2000
309 #define NS_VPRINTF_BUFFER_SIZE 500
312 ns_callback_t callback;
313 char message[1024 * 8];
316 void iobuf_resize(struct iobuf *io, size_t new_size) {
318 if ((new_size > io->size || (new_size < io->size && new_size >= io->len)) &&
319 (p = (char *) NS_REALLOC(io->buf, new_size)) != NULL) {
325 void iobuf_init(struct iobuf *iobuf, size_t initial_size) {
326 iobuf->len = iobuf->size = 0;
328 iobuf_resize(iobuf, initial_size);
331 void iobuf_free(struct iobuf *iobuf) {
333 if (iobuf->buf != NULL) NS_FREE(iobuf->buf);
334 iobuf_init(iobuf, 0);
338 size_t iobuf_append(struct iobuf *io, const void *buf, size_t len) {
342 assert(io->len <= io->size);
345 } else if (io->len + len <= io->size) {
346 memcpy(io->buf + io->len, buf, len);
348 } else if ((p = (char *) NS_REALLOC(io->buf, io->len + len)) != NULL) {
350 memcpy(io->buf + io->len, buf, len);
360 void iobuf_remove(struct iobuf *io, size_t n) {
361 if (n > 0 && n <= io->len) {
362 memmove(io->buf, io->buf + n, io->len - n);
367 static size_t ns_out(struct ns_connection *nc, const void *buf, size_t len) {
368 if (nc->flags & NSF_UDP) {
369 long n = sendto(nc->sock, buf, len, 0, &nc->sa.sa, sizeof(nc->sa.sin));
370 DBG(("%p %d send %ld (%d %s)", nc, nc->sock, n, errno, strerror(errno)));
371 return n < 0 ? 0 : n;
373 return iobuf_append(&nc->send_iobuf, buf, len);
377 #ifndef NS_DISABLE_THREADS
378 void *ns_start_thread(void *(*f)(void *), void *p) {
380 return (void *) _beginthread((void (__cdecl *)(void *)) f, 0, p);
382 pthread_t thread_id = (pthread_t) 0;
385 (void) pthread_attr_init(&attr);
386 (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
388 #if defined(NS_STACK_SIZE) && NS_STACK_SIZE > 1
389 (void) pthread_attr_setstacksize(&attr, NS_STACK_SIZE);
392 pthread_create(&thread_id, &attr, f, p);
393 pthread_attr_destroy(&attr);
395 return (void *) thread_id;
398 #endif // NS_DISABLE_THREADS
400 static void ns_add_conn(struct ns_mgr *mgr, struct ns_connection *c) {
401 c->next = mgr->active_connections;
402 mgr->active_connections = c;
404 if (c->next != NULL) c->next->prev = c;
407 static void ns_remove_conn(struct ns_connection *conn) {
408 if (conn->prev == NULL) conn->mgr->active_connections = conn->next;
409 if (conn->prev) conn->prev->next = conn->next;
410 if (conn->next) conn->next->prev = conn->prev;
413 // Print message to buffer. If buffer is large enough to hold the message,
414 // return buffer. If buffer is to small, allocate large enough buffer on heap,
415 // and return allocated buffer.
416 int ns_avprintf(char **buf, size_t size, const char *fmt, va_list ap) {
420 va_copy(ap_copy, ap);
421 len = vsnprintf(*buf, size, fmt, ap_copy);
425 // eCos and Windows are not standard-compliant and return -1 when
426 // the buffer is too small. Keep allocating larger buffers until we
427 // succeed or out of memory.
430 if (*buf) free(*buf);
432 if ((*buf = (char *) NS_MALLOC(size)) == NULL) break;
433 va_copy(ap_copy, ap);
434 len = vsnprintf(*buf, size, fmt, ap_copy);
437 } else if (len > (int) size) {
438 // Standard-compliant code path. Allocate a buffer that is large enough.
439 if ((*buf = (char *) NS_MALLOC(len + 1)) == NULL) {
442 va_copy(ap_copy, ap);
443 len = vsnprintf(*buf, len + 1, fmt, ap_copy);
451 int ns_vprintf(struct ns_connection *nc, const char *fmt, va_list ap) {
452 char mem[NS_VPRINTF_BUFFER_SIZE], *buf = mem;
455 if ((len = ns_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
456 ns_out(nc, buf, len);
458 if (buf != mem && buf != NULL) {
465 int ns_printf(struct ns_connection *conn, const char *fmt, ...) {
469 len = ns_vprintf(conn, fmt, ap);
474 static void hexdump(struct ns_connection *nc, const char *path,
475 int num_bytes, int ev) {
476 const struct iobuf *io = ev == NS_SEND ? &nc->send_iobuf : &nc->recv_iobuf;
478 char *buf, src[60], dst[60];
479 int buf_size = num_bytes * 5 + 100;
481 if ((fp = fopen(path, "a")) != NULL) {
482 ns_sock_to_str(nc->sock, src, sizeof(src), 3);
483 ns_sock_to_str(nc->sock, dst, sizeof(dst), 7);
484 fprintf(fp, "%lu %p %s %s %s %d\n", (unsigned long) time(NULL),
486 ev == NS_RECV ? "<-" : ev == NS_SEND ? "->" :
487 ev == NS_ACCEPT ? "<A" : ev == NS_CONNECT ? "C>" : "XX",
489 if (num_bytes > 0 && (buf = (char *) NS_MALLOC(buf_size)) != NULL) {
490 ns_hexdump(io->buf + (ev == NS_SEND ? 0 : io->len) -
491 (ev == NS_SEND ? 0 : num_bytes), num_bytes, buf, buf_size);
492 fprintf(fp, "%s", buf);
499 static void ns_call(struct ns_connection *nc, int ev, void *p) {
500 if (nc->mgr->hexdump_file != NULL && ev != NS_POLL) {
501 int len = (ev == NS_RECV || ev == NS_SEND) ? * (int *) p : 0;
502 hexdump(nc, nc->mgr->hexdump_file, len, ev);
505 nc->callback(nc, ev, p);
508 static void ns_destroy_conn(struct ns_connection *conn) {
509 closesocket(conn->sock);
510 iobuf_free(&conn->recv_iobuf);
511 iobuf_free(&conn->send_iobuf);
513 if (conn->ssl != NULL) {
516 if (conn->ssl_ctx != NULL) {
517 SSL_CTX_free(conn->ssl_ctx);
523 static void ns_close_conn(struct ns_connection *conn) {
524 DBG(("%p %d", conn, conn->flags));
525 ns_call(conn, NS_CLOSE, NULL);
526 ns_remove_conn(conn);
527 ns_destroy_conn(conn);
530 void ns_set_close_on_exec(sock_t sock) {
532 (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
534 fcntl(sock, F_SETFD, FD_CLOEXEC);
538 static void ns_set_non_blocking_mode(sock_t sock) {
540 unsigned long on = 1;
541 ioctlsocket(sock, FIONBIO, &on);
543 int flags = fcntl(sock, F_GETFL, 0);
544 fcntl(sock, F_SETFL, flags | O_NONBLOCK);
548 #ifndef NS_DISABLE_SOCKETPAIR
549 int ns_socketpair2(sock_t sp[2], int sock_type) {
550 union socket_address sa;
552 socklen_t len = sizeof(sa.sin);
555 sp[0] = sp[1] = INVALID_SOCKET;
557 (void) memset(&sa, 0, sizeof(sa));
558 sa.sin.sin_family = AF_INET;
559 sa.sin.sin_port = htons(0);
560 sa.sin.sin_addr.s_addr = htonl(0x7f000001);
562 if ((sock = socket(AF_INET, sock_type, 0)) != INVALID_SOCKET &&
563 !bind(sock, &sa.sa, len) &&
564 (sock_type == SOCK_DGRAM || !listen(sock, 1)) &&
565 !getsockname(sock, &sa.sa, &len) &&
566 (sp[0] = socket(AF_INET, sock_type, 0)) != INVALID_SOCKET &&
567 !connect(sp[0], &sa.sa, len) &&
568 (sock_type == SOCK_STREAM ||
569 (!getsockname(sp[0], &sa.sa, &len) && !connect(sock, &sa.sa, len))) &&
570 (sp[1] = (sock_type == SOCK_DGRAM ? sock :
571 accept(sock, &sa.sa, &len))) != INVALID_SOCKET) {
572 ns_set_close_on_exec(sp[0]);
573 ns_set_close_on_exec(sp[1]);
576 if (sp[0] != INVALID_SOCKET) closesocket(sp[0]);
577 if (sp[1] != INVALID_SOCKET) closesocket(sp[1]);
578 sp[0] = sp[1] = INVALID_SOCKET;
580 if (sock_type != SOCK_DGRAM) closesocket(sock);
585 int ns_socketpair(sock_t sp[2]) {
586 return ns_socketpair2(sp, SOCK_STREAM);
588 #endif // NS_DISABLE_SOCKETPAIR
590 // TODO(lsm): use non-blocking resolver
591 static int ns_resolve2(const char *host, struct in_addr *ina) {
593 if ((he = gethostbyname(host)) == NULL) {
594 DBG(("gethostbyname(%s) failed: %s", host, strerror(errno)));
596 memcpy(ina, he->h_addr_list[0], sizeof(*ina));
602 // Resolve FDQN "host", store IP address in the "ip".
603 // Return > 0 (IP address length) on success.
604 int ns_resolve(const char *host, char *buf, size_t n) {
606 return ns_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0;
609 // Address format: [PROTO://][IP_ADDRESS:]PORT[:CERT][:CA_CERT]
610 static int ns_parse_address(const char *str, union socket_address *sa,
611 int *proto, int *use_ssl, char *cert, char *ca) {
612 unsigned int a, b, c, d, port;
615 #ifdef NS_ENABLE_IPV6
619 // MacOS needs that. If we do not zero it, subsequent bind() will fail.
620 // Also, all-zeroes in the socket address means binding to all addresses
621 // for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
622 memset(sa, 0, sizeof(*sa));
623 sa->sin.sin_family = AF_INET;
625 *proto = SOCK_STREAM;
627 cert[0] = ca[0] = '\0';
629 if (memcmp(str, "ssl://", 6) == 0) {
632 } else if (memcmp(str, "udp://", 6) == 0) {
635 } else if (memcmp(str, "tcp://", 6) == 0) {
639 if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
640 // Bind to a specific IPv4 address, e.g. 192.168.1.5:8080
641 sa->sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
642 sa->sin.sin_port = htons((uint16_t) port);
643 #ifdef NS_ENABLE_IPV6
644 } else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 &&
645 inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
646 // IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080
647 sa->sin6.sin6_family = AF_INET6;
648 sa->sin6.sin6_port = htons((uint16_t) port);
650 } else if (sscanf(str, "%199[^ :]:%u%n", host, &port, &len) == 2) {
651 sa->sin.sin_port = htons((uint16_t) port);
652 ns_resolve2(host, &sa->sin.sin_addr);
653 } else if (sscanf(str, "%u%n", &port, &len) == 1) {
654 // If only port is specified, bind to IPv4, INADDR_ANY
655 sa->sin.sin_port = htons((uint16_t) port);
658 if (*use_ssl && (sscanf(str + len, ":%99[^:]:%99[^:]%n", cert, ca, &n) == 2 ||
659 sscanf(str + len, ":%99[^:]%n", cert, &n) == 1)) {
663 return port < 0xffff && str[len] == '\0' ? len : 0;
666 // 'sa' must be an initialized address to bind to
667 static sock_t ns_open_listening_socket(union socket_address *sa, int proto) {
668 socklen_t sa_len = (sa->sa.sa_family == AF_INET) ?
669 sizeof(sa->sin) : sizeof(sa->sin6);
670 sock_t sock = INVALID_SOCKET;
675 if ((sock = socket(sa->sa.sa_family, proto, 0)) != INVALID_SOCKET &&
677 // SO_RESUSEADDR is not enabled on Windows because the semantics of
678 // SO_REUSEADDR on UNIX and Windows is different. On Windows,
679 // SO_REUSEADDR allows to bind a socket to a port without error even if
680 // the port is already open by another program. This is not the behavior
681 // SO_REUSEADDR was designed for, and leads to hard-to-track failure
682 // scenarios. Therefore, SO_REUSEADDR was disabled on Windows.
683 !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) &&
685 !bind(sock, &sa->sa, sa_len) &&
686 (proto == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) {
687 ns_set_non_blocking_mode(sock);
688 // In case port was set to 0, get the real port number
689 (void) getsockname(sock, &sa->sa, &sa_len);
690 } else if (sock != INVALID_SOCKET) {
692 sock = INVALID_SOCKET;
699 // Certificate generation script is at
700 // https://github.com/cesanta/net_skeleton/blob/master/scripts/gen_certs.sh
702 static int ns_use_ca_cert(SSL_CTX *ctx, const char *cert) {
705 } else if (cert == NULL || cert[0] == '\0') {
708 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
709 return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? 0 : -2;
712 static int ns_use_cert(SSL_CTX *ctx, const char *pem_file) {
715 } else if (pem_file == NULL || pem_file[0] == '\0') {
717 } else if (SSL_CTX_use_certificate_file(ctx, pem_file, 1) == 0 ||
718 SSL_CTX_use_PrivateKey_file(ctx, pem_file, 1) == 0) {
721 SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
722 SSL_CTX_use_certificate_chain_file(ctx, pem_file);
726 #endif // NS_ENABLE_SSL
728 struct ns_connection *ns_bind(struct ns_mgr *srv, const char *str,
729 ns_callback_t callback, void *user_data) {
730 union socket_address sa;
731 struct ns_connection *nc = NULL;
733 char cert[100], ca_cert[100];
736 ns_parse_address(str, &sa, &proto, &use_ssl, cert, ca_cert);
737 if (use_ssl && cert[0] == '\0') return NULL;
739 if ((sock = ns_open_listening_socket(&sa, proto)) == INVALID_SOCKET) {
740 } else if ((nc = ns_add_sock(srv, sock, callback, NULL)) == NULL) {
744 nc->flags |= NSF_LISTENING;
745 nc->user_data = user_data;
746 nc->callback = callback;
748 if (proto == SOCK_DGRAM) {
749 nc->flags |= NSF_UDP;
754 nc->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
755 if (ns_use_cert(nc->ssl_ctx, cert) != 0 ||
756 ns_use_ca_cert(nc->ssl_ctx, ca_cert) != 0) {
763 DBG(("%p sock %d/%d ssl %p %p", nc, sock, proto, nc->ssl_ctx, nc->ssl));
769 static struct ns_connection *accept_conn(struct ns_connection *ls) {
770 struct ns_connection *c = NULL;
771 union socket_address sa;
772 socklen_t len = sizeof(sa);
773 sock_t sock = INVALID_SOCKET;
775 // NOTE(lsm): on Windows, sock is always > FD_SETSIZE
776 if ((sock = accept(ls->sock, &sa.sa, &len)) == INVALID_SOCKET) {
777 } else if ((c = ns_add_sock(ls->mgr, sock, ls->callback,
778 ls->user_data)) == NULL) {
781 } else if (ls->ssl_ctx != NULL &&
782 ((c->ssl = SSL_new(ls->ssl_ctx)) == NULL ||
783 SSL_set_fd(c->ssl, sock) != 1)) {
790 c->proto_data = ls->proto_data;
791 ns_call(c, NS_ACCEPT, &sa);
792 DBG(("%p %d %p %p", c, c->sock, c->ssl_ctx, c->ssl));
798 static int ns_is_error(int n) {
800 (n < 0 && errno != EINTR && errno != EINPROGRESS &&
801 errno != EAGAIN && errno != EWOULDBLOCK
803 && WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK
808 void ns_sock_to_str(sock_t sock, char *buf, size_t len, int flags) {
809 union socket_address sa;
810 socklen_t slen = sizeof(sa);
812 if (buf != NULL && len > 0) {
814 memset(&sa, 0, sizeof(sa));
816 getpeername(sock, &sa.sa, &slen);
818 getsockname(sock, &sa.sa, &slen);
821 #if defined(NS_ENABLE_IPV6)
822 inet_ntop(sa.sa.sa_family, sa.sa.sa_family == AF_INET ?
823 (void *) &sa.sin.sin_addr :
824 (void *) &sa.sin6.sin6_addr, buf, len);
825 #elif defined(_WIN32)
826 // Only Windoze Vista (and newer) have inet_ntop()
827 strncpy(buf, inet_ntoa(sa.sin.sin_addr), len);
829 inet_ntop(sa.sa.sa_family, (void *) &sa.sin.sin_addr, buf,(socklen_t)len);
833 snprintf(buf + strlen(buf), len - (strlen(buf) + 1), "%s%d",
834 flags & 1 ? ":" : "", (int) ntohs(sa.sin.sin_port));
839 int ns_hexdump(const void *buf, int len, char *dst, int dst_len) {
840 const unsigned char *p = (const unsigned char *) buf;
844 for (i = 0; i < len; i++) {
847 if (i > 0) n += snprintf(dst + n, dst_len - n, " %s\n", ascii);
848 n += snprintf(dst + n, dst_len - n, "%04x ", i);
850 n += snprintf(dst + n, dst_len - n, " %02x", p[i]);
851 ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i];
852 ascii[idx + 1] = '\0';
855 while (i++ % 16) n += snprintf(dst + n, dst_len - n, "%s", " ");
856 n += snprintf(dst + n, dst_len - n, " %s\n\n", ascii);
862 static int ns_ssl_err(struct ns_connection *conn, int res) {
863 int ssl_err = SSL_get_error(conn->ssl, res);
864 if (ssl_err == SSL_ERROR_WANT_READ) conn->flags |= NSF_WANT_READ;
865 if (ssl_err == SSL_ERROR_WANT_WRITE) conn->flags |= NSF_WANT_WRITE;
870 static void ns_read_from_socket(struct ns_connection *conn) {
874 if (conn->flags & NSF_CONNECTING) {
876 socklen_t len = sizeof(ok);
878 ret = getsockopt(conn->sock, SOL_SOCKET, SO_ERROR, (char *) &ok, &len);
881 if (ret == 0 && ok == 0 && conn->ssl != NULL) {
882 int res = SSL_connect(conn->ssl);
883 int ssl_err = ns_ssl_err(conn, res);
885 conn->flags |= NSF_SSL_HANDSHAKE_DONE;
886 } else if (ssl_err == SSL_ERROR_WANT_READ ||
887 ssl_err == SSL_ERROR_WANT_WRITE) {
888 return; // Call us again
894 conn->flags &= ~NSF_CONNECTING;
895 DBG(("%p ok=%d", conn, ok));
897 conn->flags |= NSF_CLOSE_IMMEDIATELY;
899 ns_call(conn, NS_CONNECT, &ok);
904 if (conn->ssl != NULL) {
905 if (conn->flags & NSF_SSL_HANDSHAKE_DONE) {
906 // SSL library may have more bytes ready to read then we ask to read.
907 // Therefore, read in a loop until we read everything. Without the loop,
908 // we skip to the next select() cycle which can just timeout.
909 while ((n = SSL_read(conn->ssl, buf, sizeof(buf))) > 0) {
910 DBG(("%p %d <- %d bytes (SSL)", conn, conn->flags, n));
911 iobuf_append(&conn->recv_iobuf, buf, n);
912 ns_call(conn, NS_RECV, &n);
916 int res = SSL_accept(conn->ssl);
917 int ssl_err = ns_ssl_err(conn, res);
919 conn->flags |= NSF_SSL_HANDSHAKE_DONE;
920 } else if (ssl_err == SSL_ERROR_WANT_READ ||
921 ssl_err == SSL_ERROR_WANT_WRITE) {
922 return; // Call us again
924 conn->flags |= NSF_CLOSE_IMMEDIATELY;
931 while ((n = (int) recv(conn->sock, buf, sizeof(buf), 0)) > 0) {
932 DBG(("%p %d <- %d bytes (PLAIN)", conn, conn->flags, n));
933 iobuf_append(&conn->recv_iobuf, buf, n);
934 ns_call(conn, NS_RECV, &n);
938 if (ns_is_error(n)) {
939 conn->flags |= NSF_CLOSE_IMMEDIATELY;
943 static void ns_write_to_socket(struct ns_connection *conn) {
944 struct iobuf *io = &conn->send_iobuf;
948 if (conn->ssl != NULL) {
949 n = SSL_write(conn->ssl, io->buf, io->len);
951 int ssl_err = ns_ssl_err(conn, n);
952 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
953 return; // Call us again
955 conn->flags |= NSF_CLOSE_IMMEDIATELY;
960 { n = (int) send(conn->sock, io->buf, io->len, 0); }
962 DBG(("%p %d -> %d bytes", conn, conn->flags, n));
964 ns_call(conn, NS_SEND, &n);
965 if (ns_is_error(n)) {
966 conn->flags |= NSF_CLOSE_IMMEDIATELY;
972 int ns_send(struct ns_connection *conn, const void *buf, int len) {
973 return (int) ns_out(conn, buf, len);
976 static void ns_handle_udp(struct ns_connection *ls) {
977 struct ns_connection nc;
978 char buf[NS_UDP_RECEIVE_BUFFER_SIZE];
980 socklen_t s_len = sizeof(nc.sa);
982 memset(&nc, 0, sizeof(nc));
983 n = recvfrom(ls->sock, buf, sizeof(buf), 0, &nc.sa.sa, &s_len);
985 DBG(("%p recvfrom: %s", ls, strerror(errno)));
988 nc.recv_iobuf.buf = buf;
989 nc.recv_iobuf.len = nc.recv_iobuf.size = n;
991 nc.callback = ls->callback;
992 nc.user_data = ls->user_data;
993 nc.proto_data = ls->proto_data;
997 DBG(("%p %d bytes received", ls, n));
998 ns_call(&nc, NS_RECV, &n);
1002 static void ns_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) {
1003 if (sock != INVALID_SOCKET) {
1005 if (*max_fd == INVALID_SOCKET || sock > *max_fd) {
1011 time_t ns_mgr_poll(struct ns_mgr *mgr, int milli) {
1012 struct ns_connection *conn, *tmp_conn;
1014 fd_set read_set, write_set;
1015 sock_t max_fd = INVALID_SOCKET;
1016 time_t current_time = time(NULL);
1019 FD_ZERO(&write_set);
1020 ns_add_to_set(mgr->ctl[1], &read_set, &max_fd);
1022 for (conn = mgr->active_connections; conn != NULL; conn = tmp_conn) {
1023 tmp_conn = conn->next;
1024 if (!(conn->flags & (NSF_LISTENING | NSF_CONNECTING))) {
1025 ns_call(conn, NS_POLL, ¤t_time);
1027 if (!(conn->flags & NSF_WANT_WRITE)) {
1028 //DBG(("%p read_set", conn));
1029 ns_add_to_set(conn->sock, &read_set, &max_fd);
1031 if (((conn->flags & NSF_CONNECTING) && !(conn->flags & NSF_WANT_READ)) ||
1032 (conn->send_iobuf.len > 0 && !(conn->flags & NSF_CONNECTING) &&
1033 !(conn->flags & NSF_BUFFER_BUT_DONT_SEND))) {
1034 //DBG(("%p write_set", conn));
1035 ns_add_to_set(conn->sock, &write_set, &max_fd);
1037 if (conn->flags & NSF_CLOSE_IMMEDIATELY) {
1038 ns_close_conn(conn);
1042 tv.tv_sec = milli / 1000;
1043 tv.tv_usec = (milli % 1000) * 1000;
1045 if (select((int) max_fd + 1, &read_set, &write_set, NULL, &tv) > 0) {
1046 // select() might have been waiting for a long time, reset current_time
1047 // now to prevent last_io_time being set to the past.
1048 current_time = time(NULL);
1050 // Read wakeup messages
1051 if (mgr->ctl[1] != INVALID_SOCKET &&
1052 FD_ISSET(mgr->ctl[1], &read_set)) {
1053 struct ctl_msg ctl_msg;
1054 int len = (int) recv(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0);
1055 send(mgr->ctl[1], ctl_msg.message, 1, 0);
1056 if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) {
1057 struct ns_connection *c;
1058 for (c = ns_next(mgr, NULL); c != NULL; c = ns_next(mgr, c)) {
1059 ctl_msg.callback(c, NS_POLL, ctl_msg.message);
1064 for (conn = mgr->active_connections; conn != NULL; conn = tmp_conn) {
1065 tmp_conn = conn->next;
1066 if (FD_ISSET(conn->sock, &read_set)) {
1067 if (conn->flags & NSF_LISTENING) {
1068 if (conn->flags & NSF_UDP) {
1069 ns_handle_udp(conn);
1071 // We're not looping here, and accepting just one connection at
1072 // a time. The reason is that eCos does not respect non-blocking
1073 // flag on a listening socket and hangs in a loop.
1077 conn->last_io_time = current_time;
1078 ns_read_from_socket(conn);
1082 if (FD_ISSET(conn->sock, &write_set)) {
1083 if (conn->flags & NSF_CONNECTING) {
1084 ns_read_from_socket(conn);
1085 } else if (!(conn->flags & NSF_BUFFER_BUT_DONT_SEND)) {
1086 conn->last_io_time = current_time;
1087 ns_write_to_socket(conn);
1093 for (conn = mgr->active_connections; conn != NULL; conn = tmp_conn) {
1094 tmp_conn = conn->next;
1095 if ((conn->flags & NSF_CLOSE_IMMEDIATELY) ||
1096 (conn->send_iobuf.len == 0 &&
1097 (conn->flags & NSF_FINISHED_SENDING_DATA))) {
1098 ns_close_conn(conn);
1102 return current_time;
1105 struct ns_connection *ns_connect(struct ns_mgr *mgr, const char *address,
1106 ns_callback_t callback, void *user_data) {
1107 sock_t sock = INVALID_SOCKET;
1108 struct ns_connection *nc = NULL;
1109 union socket_address sa;
1110 char cert[100], ca_cert[100];
1111 int rc, use_ssl, proto;
1113 ns_parse_address(address, &sa, &proto, &use_ssl, cert, ca_cert);
1114 if ((sock = socket(AF_INET, proto, 0)) == INVALID_SOCKET) {
1117 ns_set_non_blocking_mode(sock);
1118 rc = (proto == SOCK_DGRAM) ? 0 : connect(sock, &sa.sa, sizeof(sa.sin));
1120 if (rc != 0 && ns_is_error(rc)) {
1123 } else if ((nc = ns_add_sock(mgr, sock, callback, user_data)) == NULL) {
1128 nc->sa = sa; // Important, cause UDP conns will use sendto()
1129 nc->flags = (proto == SOCK_DGRAM) ? NSF_UDP : NSF_CONNECTING;
1131 #ifdef NS_ENABLE_SSL
1133 if ((nc->ssl_ctx = SSL_CTX_new(SSLv23_client_method())) == NULL ||
1134 ns_use_cert(nc->ssl_ctx, cert) != 0 ||
1135 ns_use_ca_cert(nc->ssl_ctx, ca_cert) != 0 ||
1136 (nc->ssl = SSL_new(nc->ssl_ctx)) == NULL) {
1140 SSL_set_fd(nc->ssl, sock);
1148 struct ns_connection *ns_add_sock(struct ns_mgr *s, sock_t sock,
1149 ns_callback_t callback, void *user_data) {
1150 struct ns_connection *conn;
1151 if ((conn = (struct ns_connection *) NS_MALLOC(sizeof(*conn))) != NULL) {
1152 memset(conn, 0, sizeof(*conn));
1153 ns_set_non_blocking_mode(sock);
1154 ns_set_close_on_exec(sock);
1156 conn->user_data = user_data;
1157 conn->callback = callback;
1159 conn->last_io_time = time(NULL);
1160 ns_add_conn(s, conn);
1161 DBG(("%p %d", conn, sock));
1166 struct ns_connection *ns_next(struct ns_mgr *s, struct ns_connection *conn) {
1167 return conn == NULL ? s->active_connections : conn->next;
1170 void ns_broadcast(struct ns_mgr *mgr, ns_callback_t cb,void *data, size_t len) {
1171 struct ctl_msg ctl_msg;
1172 if (mgr->ctl[0] != INVALID_SOCKET && data != NULL &&
1173 len < sizeof(ctl_msg.message)) {
1174 ctl_msg.callback = cb;
1175 memcpy(ctl_msg.message, data, len);
1176 send(mgr->ctl[0], (char *) &ctl_msg,
1177 offsetof(struct ctl_msg, message) + len, 0);
1178 recv(mgr->ctl[0], (char *) &len, 1, 0);
1182 void ns_mgr_init(struct ns_mgr *s, void *user_data) {
1183 memset(s, 0, sizeof(*s));
1184 s->ctl[0] = s->ctl[1] = INVALID_SOCKET;
1185 s->user_data = user_data;
1188 { WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); }
1190 // Ignore SIGPIPE signal, so if client cancels the request, it
1191 // won't kill the whole process.
1192 signal(SIGPIPE, SIG_IGN);
1195 #ifndef NS_DISABLE_SOCKETPAIR
1197 ns_socketpair2(s->ctl, SOCK_DGRAM);
1198 } while (s->ctl[0] == INVALID_SOCKET);
1201 #ifdef NS_ENABLE_SSL
1202 {static int init_done; if (!init_done) { SSL_library_init(); init_done++; }}
1206 void ns_mgr_free(struct ns_mgr *s) {
1207 struct ns_connection *conn, *tmp_conn;
1210 if (s == NULL) return;
1211 // Do one last poll, see https://github.com/cesanta/mongoose/issues/286
1214 if (s->ctl[0] != INVALID_SOCKET) closesocket(s->ctl[0]);
1215 if (s->ctl[1] != INVALID_SOCKET) closesocket(s->ctl[1]);
1216 s->ctl[0] = s->ctl[1] = INVALID_SOCKET;
1218 for (conn = s->active_connections; conn != NULL; conn = tmp_conn) {
1219 tmp_conn = conn->next;
1220 ns_close_conn(conn);
1224 #endif // NOEMBED_NET_SKELETON
1228 #ifdef _WIN32 //////////////// Windows specific defines and includes
1229 #include <io.h> // For _lseeki64
1230 #include <direct.h> // For _mkdir
1232 #define S_ISDIR(x) ((x) & _S_IFDIR)
1246 #define stat(x, y) mg_stat((x), (y))
1247 #define fopen(x, y) mg_fopen((x), (y))
1248 #define open(x, y, z) mg_open((x), (y), (z))
1249 #define close(x) _close(x)
1250 #define lseek(x, y, z) _lseeki64((x), (y), (z))
1251 #define popen(x, y) _popen((x), (y))
1252 #define pclose(x) _pclose(x)
1253 #define mkdir(x, y) _mkdir(x)
1256 #define STR(x) STRX(x)
1257 #define __func__ __FILE__ ":" STR(__LINE__)
1259 /* MINGW has adopted the MSVC formatting for 64-bit ints as of gcc 4.4 till 4.8*/
1260 #if (defined(__MINGW32__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4 && __GNUC_MINOR__ < 8))) || defined(_MSC_VER)
1261 #define INT64_FMT "I64d"
1263 #define INT64_FMT "lld"
1265 #define flockfile(x) ((void) (x))
1266 #define funlockfile(x) ((void) (x))
1267 typedef struct _stati64 file_stat_t;
1268 typedef HANDLE process_id_t;
1270 #else ////////////// UNIX specific defines and includes
1274 #include <inttypes.h>
1277 #define INT64_FMT PRId64
1278 typedef struct stat file_stat_t;
1279 typedef pid_t process_id_t;
1280 #endif //////// End of platform-specific defines and includes
1282 #include "mongoose.h"
1284 #define MAX_REQUEST_SIZE 16384
1285 #define IOBUF_SIZE 8192
1286 #define MAX_PATH_SIZE 8192
1287 #define DEFAULT_CGI_PATTERN "**.cgi$|**.pl$|**.php$"
1288 #define CGI_ENVIRONMENT_SIZE 8192
1289 #define MAX_CGI_ENVIR_VARS 64
1290 #define ENV_EXPORT_TO_CGI "MONGOOSE_CGI"
1291 #define PASSWORDS_FILE_NAME ".htpasswd"
1293 #ifndef MONGOOSE_USE_WEBSOCKET_PING_INTERVAL
1294 #define MONGOOSE_USE_WEBSOCKET_PING_INTERVAL 5
1297 // Extra HTTP headers to send in every static file reply
1298 #if !defined(MONGOOSE_USE_EXTRA_HTTP_HEADERS)
1299 #define MONGOOSE_USE_EXTRA_HTTP_HEADERS ""
1302 #ifndef MONGOOSE_POST_SIZE_LIMIT
1303 #define MONGOOSE_POST_SIZE_LIMIT 0
1306 #ifndef MONGOOSE_IDLE_TIMEOUT_SECONDS
1307 #define MONGOOSE_IDLE_TIMEOUT_SECONDS 300
1310 #ifdef NS_DISABLE_SOCKETPAIR
1311 #define MONGOOSE_NO_CGI
1314 #ifdef MONGOOSE_NO_FILESYSTEM
1315 #define MONGOOSE_NO_AUTH
1316 #define MONGOOSE_NO_CGI
1317 #define MONGOOSE_NO_DAV
1318 #define MONGOOSE_NO_DIRECTORY_LISTING
1319 #define MONGOOSE_NO_LOGGING
1320 #define MONGOOSE_NO_SSI
1321 #define MONGOOSE_NO_DL
1329 // For directory listing and WevDAV support
1331 struct connection *conn;
1336 // NOTE(lsm): this enum shoulds be in sync with the config_options.
1338 ACCESS_CONTROL_LIST,
1339 #ifndef MONGOOSE_NO_FILESYSTEM
1341 #ifndef MONGOOSE_NO_AUTH
1344 #ifndef MONGOOSE_NO_CGI
1350 #ifndef MONGOOSE_NO_DIRECTORY_LISTING
1351 ENABLE_DIRECTORY_LISTING,
1356 #if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_AUTH)
1359 #ifndef MONGOOSE_NO_FILESYSTEM
1368 #ifndef MONGOOSE_NO_SSI
1375 static const char *static_config_options[] = {
1376 "access_control_list", NULL,
1377 #ifndef MONGOOSE_NO_FILESYSTEM
1378 "access_log_file", NULL,
1379 #ifndef MONGOOSE_NO_AUTH
1380 "auth_domain", "mydomain.com",
1382 #ifndef MONGOOSE_NO_CGI
1383 "cgi_interpreter", NULL,
1384 "cgi_pattern", DEFAULT_CGI_PATTERN,
1386 "dav_auth_file", NULL,
1387 "document_root", NULL,
1388 #ifndef MONGOOSE_NO_DIRECTORY_LISTING
1389 "enable_directory_listing", "yes",
1392 "enable_proxy", NULL,
1393 "extra_mime_types", NULL,
1394 #if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_AUTH)
1395 "global_auth_file", NULL,
1397 #ifndef MONGOOSE_NO_FILESYSTEM
1398 "hide_files_patterns", NULL,
1399 "hexdump_file", NULL,
1400 "index_files","index.html,index.htm,index.shtml,index.cgi,index.php",
1402 "listening_port", NULL,
1404 "run_as_user", NULL,
1406 #ifndef MONGOOSE_NO_SSI
1407 "ssi_pattern", "**.shtml$|**.shtm$",
1409 "url_rewrites", NULL,
1414 struct ns_mgr ns_mgr;
1415 union socket_address lsa; // Listening socket address
1416 mg_handler_t event_handler;
1417 char *config_options[NUM_OPTIONS];
1420 // Local endpoint representation
1422 int fd; // Opened regular local file
1423 struct ns_connection *nc; // CGI or proxy->target connection
1426 enum endpoint_type {
1427 EP_NONE, EP_FILE, EP_CGI, EP_USER, EP_PUT, EP_CLIENT, EP_PROXY
1430 #define MG_HEADERS_SENT NSF_USER_1
1431 #define MG_LONG_RUNNING NSF_USER_2
1432 #define MG_CGI_CONN NSF_USER_3
1433 #define MG_PROXY_CONN NSF_USER_4
1434 #define MG_PROXY_DONT_PARSE NSF_USER_5
1437 struct ns_connection *ns_conn; // NOTE(lsm): main.c depends on this order
1438 struct mg_connection mg_conn;
1439 struct mg_server *server;
1440 union endpoint endpoint;
1441 enum endpoint_type endpoint_type;
1444 int64_t num_bytes_recv; // Total number of bytes received
1445 int64_t cl; // Reply content length, for Range support
1446 int request_len; // Request length, including last \r\n after last header
1449 #define MG_CONN_2_CONN(c) ((struct connection *) ((char *) (c) - \
1450 offsetof(struct connection, mg_conn)))
1452 static void open_local_endpoint(struct connection *conn, int skip_user);
1453 static void close_local_endpoint(struct connection *conn);
1454 static void mg_ev_handler(struct ns_connection *nc, int ev, void *p);
1456 static const struct {
1457 const char *extension;
1459 const char *mime_type;
1460 } static_builtin_mime_types[] = {
1461 {".html", 5, "text/html"},
1462 {".htm", 4, "text/html"},
1463 {".shtm", 5, "text/html"},
1464 {".shtml", 6, "text/html"},
1465 {".css", 4, "text/css"},
1466 {".js", 3, "application/x-javascript"},
1467 {".ico", 4, "image/x-icon"},
1468 {".gif", 4, "image/gif"},
1469 {".jpg", 4, "image/jpeg"},
1470 {".jpeg", 5, "image/jpeg"},
1471 {".png", 4, "image/png"},
1472 {".svg", 4, "image/svg+xml"},
1473 {".txt", 4, "text/plain"},
1474 {".torrent", 8, "application/x-bittorrent"},
1475 {".wav", 4, "audio/x-wav"},
1476 {".mp3", 4, "audio/x-mp3"},
1477 {".mid", 4, "audio/mid"},
1478 {".m3u", 4, "audio/x-mpegurl"},
1479 {".ogg", 4, "application/ogg"},
1480 {".ram", 4, "audio/x-pn-realaudio"},
1481 {".xml", 4, "text/xml"},
1482 {".json", 5, "application/json"},
1483 {".xslt", 5, "application/xml"},
1484 {".xsl", 4, "application/xml"},
1485 {".ra", 3, "audio/x-pn-realaudio"},
1486 {".doc", 4, "application/msword"},
1487 {".exe", 4, "application/octet-stream"},
1488 {".zip", 4, "application/x-zip-compressed"},
1489 {".xls", 4, "application/excel"},
1490 {".tgz", 4, "application/x-tar-gz"},
1491 {".tar", 4, "application/x-tar"},
1492 {".gz", 3, "application/x-gunzip"},
1493 {".arj", 4, "application/x-arj-compressed"},
1494 {".rar", 4, "application/x-rar-compressed"},
1495 {".rtf", 4, "application/rtf"},
1496 {".pdf", 4, "application/pdf"},
1497 {".swf", 4, "application/x-shockwave-flash"},
1498 {".mpg", 4, "video/mpeg"},
1499 {".webm", 5, "video/webm"},
1500 {".mpeg", 5, "video/mpeg"},
1501 {".mov", 4, "video/quicktime"},
1502 {".mp4", 4, "video/mp4"},
1503 {".m4v", 4, "video/x-m4v"},
1504 {".asf", 4, "video/x-ms-asf"},
1505 {".avi", 4, "video/x-msvideo"},
1506 {".bmp", 4, "image/bmp"},
1507 {".ttf", 4, "application/x-font-ttf"},
1511 #ifndef MONGOOSE_NO_THREADS
1512 void *mg_start_thread(void *(*f)(void *), void *p) {
1513 return ns_start_thread(f, p);
1515 #endif // MONGOOSE_NO_THREADS
1517 #ifndef MONGOOSE_NO_MMAP
1519 static void *mmap(void *addr, int64_t len, int prot, int flags, int fd,
1521 HANDLE fh = (HANDLE) _get_osfhandle(fd);
1522 HANDLE mh = CreateFileMapping(fh, 0, PAGE_READONLY, 0, 0, 0);
1523 void *p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, (size_t) len);
1527 #define munmap(x, y) UnmapViewOfFile(x)
1528 #define MAP_FAILED NULL
1529 #define MAP_PRIVATE 0
1532 #include <sys/mman.h>
1535 void *mg_mmap(FILE *fp, size_t size) {
1536 void *p = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fileno(fp), 0);
1537 return p == MAP_FAILED ? NULL : p;
1540 void mg_munmap(void *p, size_t size) {
1543 #endif // MONGOOSE_NO_MMAP
1545 #if defined(_WIN32) && !defined(MONGOOSE_NO_FILESYSTEM)
1546 // Encode 'path' which is assumed UTF-8 string, into UNICODE string.
1547 // wbuf and wbuf_len is a target buffer and its length.
1548 static void to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
1549 char buf[MAX_PATH_SIZE * 2], buf2[MAX_PATH_SIZE * 2], *p;
1551 strncpy(buf, path, sizeof(buf));
1552 buf[sizeof(buf) - 1] = '\0';
1554 // Trim trailing slashes. Leave backslash for paths like "X:\"
1555 p = buf + strlen(buf) - 1;
1556 while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
1558 // Convert to Unicode and back. If doubly-converted string does not
1559 // match the original, something is fishy, reject.
1560 memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
1561 MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
1562 WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
1564 if (strcmp(buf, buf2) != 0) {
1569 static int mg_stat(const char *path, file_stat_t *st) {
1570 wchar_t wpath[MAX_PATH_SIZE];
1571 to_wchar(path, wpath, ARRAY_SIZE(wpath));
1572 DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
1573 return _wstati64(wpath, st);
1576 static FILE *mg_fopen(const char *path, const char *mode) {
1577 wchar_t wpath[MAX_PATH_SIZE], wmode[10];
1578 to_wchar(path, wpath, ARRAY_SIZE(wpath));
1579 to_wchar(mode, wmode, ARRAY_SIZE(wmode));
1580 return _wfopen(wpath, wmode);
1583 static int mg_open(const char *path, int flag, int mode) {
1584 wchar_t wpath[MAX_PATH_SIZE];
1585 to_wchar(path, wpath, ARRAY_SIZE(wpath));
1586 return _wopen(wpath, flag, mode);
1588 #endif // _WIN32 && !MONGOOSE_NO_FILESYSTEM
1590 // A helper function for traversing a comma separated list of values.
1591 // It returns a list pointer shifted to the next value, or NULL if the end
1592 // of the list found.
1593 // Value is stored in val vector. If value has form "x=y", then eq_val
1594 // vector is initialized to point to the "y" part, and val vector length
1595 // is adjusted to point only to "x".
1596 static const char *next_option(const char *list, struct vec *val,
1597 struct vec *eq_val) {
1598 if (list == NULL || *list == '\0') {
1603 if ((list = strchr(val->ptr, ',')) != NULL) {
1604 // Comma found. Store length and shift the list ptr
1605 val->len = list - val->ptr;
1608 // This value is the last one
1609 list = val->ptr + strlen(val->ptr);
1610 val->len = list - val->ptr;
1613 if (eq_val != NULL) {
1614 // Value has form "x=y", adjust pointers and lengths
1615 // so that val points to "x", and eq_val points to "y".
1617 eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);
1618 if (eq_val->ptr != NULL) {
1619 eq_val->ptr++; // Skip over '=' character
1620 eq_val->len = val->ptr + val->len - eq_val->ptr;
1621 val->len = (eq_val->ptr - val->ptr) - 1;
1629 // Like snprintf(), but never returns negative value, or a value
1630 // that is larger than a supplied buffer.
1631 static int mg_vsnprintf(char *buf, size_t buflen, const char *fmt, va_list ap) {
1633 if (buflen < 1) return 0;
1634 n = vsnprintf(buf, buflen, fmt, ap);
1637 } else if (n >= (int) buflen) {
1638 n = (int) buflen - 1;
1644 static int mg_snprintf(char *buf, size_t buflen, const char *fmt, ...) {
1648 n = mg_vsnprintf(buf, buflen, fmt, ap);
1653 // Check whether full request is buffered. Return:
1654 // -1 if request is malformed
1655 // 0 if request is not yet fully buffered
1656 // >0 actual request length, including last \r\n\r\n
1657 static int get_request_len(const char *s, int buf_len) {
1658 const unsigned char *buf = (unsigned char *) s;
1661 for (i = 0; i < buf_len; i++) {
1662 // Control characters are not allowed but >=128 are.
1663 // Abort scan as soon as one malformed character is found.
1664 if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
1666 } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
1668 } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
1669 buf[i + 2] == '\n') {
1677 // Skip the characters until one of the delimiters characters found.
1678 // 0-terminate resulting word. Skip the rest of the delimiters if any.
1679 // Advance pointer to buffer to the next word. Return found 0-terminated word.
1680 static char *skip(char **buf, const char *delimiters) {
1681 char *p, *begin_word, *end_word, *end_delimiters;
1684 end_word = begin_word + strcspn(begin_word, delimiters);
1685 end_delimiters = end_word + strspn(end_word, delimiters);
1687 for (p = end_word; p < end_delimiters; p++) {
1691 *buf = end_delimiters;
1696 // Parse HTTP headers from the given buffer, advance buffer to the point
1697 // where parsing stopped.
1698 static void parse_http_headers(char **buf, struct mg_connection *ri) {
1701 for (i = 0; i < ARRAY_SIZE(ri->http_headers); i++) {
1702 ri->http_headers[i].name = skip(buf, ": ");
1703 ri->http_headers[i].value = skip(buf, "\r\n");
1704 if (ri->http_headers[i].name[0] == '\0')
1706 ri->num_headers = i + 1;
1710 static const char *status_code_to_str(int status_code) {
1711 switch (status_code) {
1713 case 100: return "Continue";
1714 case 101: return "Switching Protocols";
1715 case 102: return "Processing";
1717 case 200: return "OK";
1718 case 201: return "Created";
1719 case 202: return "Accepted";
1720 case 203: return "Non-Authoritative Information";
1721 case 204: return "No Content";
1722 case 205: return "Reset Content";
1723 case 206: return "Partial Content";
1724 case 207: return "Multi-Status";
1725 case 208: return "Already Reported";
1726 case 226: return "IM Used";
1728 case 300: return "Multiple Choices";
1729 case 301: return "Moved Permanently";
1730 case 302: return "Found";
1731 case 303: return "See Other";
1732 case 304: return "Not Modified";
1733 case 305: return "Use Proxy";
1734 case 306: return "Switch Proxy";
1735 case 307: return "Temporary Redirect";
1736 case 308: return "Permanent Redirect";
1738 case 400: return "Bad Request";
1739 case 401: return "Unauthorized";
1740 case 402: return "Payment Required";
1741 case 403: return "Forbidden";
1742 case 404: return "Not Found";
1743 case 405: return "Method Not Allowed";
1744 case 406: return "Not Acceptable";
1745 case 407: return "Proxy Authentication Required";
1746 case 408: return "Request Timeout";
1747 case 409: return "Conflict";
1748 case 410: return "Gone";
1749 case 411: return "Length Required";
1750 case 412: return "Precondition Failed";
1751 case 413: return "Payload Too Large";
1752 case 414: return "URI Too Long";
1753 case 415: return "Unsupported Media Type";
1754 case 416: return "Requested Range Not Satisfiable";
1755 case 417: return "Expectation Failed";
1756 case 418: return "I\'m a teapot";
1757 case 422: return "Unprocessable Entity";
1758 case 423: return "Locked";
1759 case 424: return "Failed Dependency";
1760 case 426: return "Upgrade Required";
1761 case 428: return "Precondition Required";
1762 case 429: return "Too Many Requests";
1763 case 431: return "Request Header Fields Too Large";
1764 case 451: return "Unavailable For Legal Reasons";
1766 case 500: return "Internal Server Error";
1767 case 501: return "Not Implemented";
1768 case 502: return "Bad Gateway";
1769 case 503: return "Service Unavailable";
1770 case 504: return "Gateway Timeout";
1771 case 505: return "HTTP Version Not Supported";
1772 case 506: return "Variant Also Negotiates";
1773 case 507: return "Insufficient Storage";
1774 case 508: return "Loop Detected";
1775 case 510: return "Not Extended";
1776 case 511: return "Network Authentication Required";
1778 default: return "Server Error";
1782 static int call_user(struct connection *conn, enum mg_event ev) {
1783 return conn != NULL && conn->server != NULL &&
1784 conn->server->event_handler != NULL ?
1785 conn->server->event_handler(&conn->mg_conn, ev) : MG_FALSE;
1788 static void send_http_error(struct connection *conn, int code,
1789 const char *fmt, ...) {
1790 const char *message = status_code_to_str(code);
1791 const char *rewrites = conn->server->config_options[URL_REWRITES];
1792 char headers[200], body[200];
1795 int body_len, headers_len, match_code;
1797 conn->mg_conn.status_code = code;
1799 // Invoke error handler if it is set
1800 if (call_user(conn, MG_HTTP_ERROR) == MG_TRUE) {
1801 close_local_endpoint(conn);
1805 // Handle error code rewrites
1806 while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
1807 if ((match_code = atoi(a.ptr)) > 0 && match_code == code) {
1808 struct mg_connection *c = &conn->mg_conn;
1809 c->status_code = 302;
1810 mg_printf(c, "HTTP/1.1 %d Moved\r\n"
1811 "Location: %.*s?code=%d&orig_uri=%s&query_string=%s\r\n\r\n",
1812 c->status_code, b.len, b.ptr, code, c->uri,
1813 c->query_string == NULL ? "" : c->query_string);
1814 close_local_endpoint(conn);
1819 body_len = mg_snprintf(body, sizeof(body), "%d %s\n", code, message);
1822 body_len += mg_vsnprintf(body + body_len, sizeof(body) - body_len, fmt, ap);
1825 if ((code >= 300 && code <= 399) || code == 204) {
1826 // 3xx errors do not have body
1829 headers_len = mg_snprintf(headers, sizeof(headers),
1830 "HTTP/1.1 %d %s\r\nContent-Length: %d\r\n"
1831 "Content-Type: text/plain\r\n\r\n",
1832 code, message, body_len);
1833 ns_send(conn->ns_conn, headers, headers_len);
1834 ns_send(conn->ns_conn, body, body_len);
1835 close_local_endpoint(conn); // This will write to the log file
1838 static void write_chunk(struct connection *conn, const char *buf, int len) {
1839 char chunk_size[50];
1840 int n = mg_snprintf(chunk_size, sizeof(chunk_size), "%X\r\n", len);
1841 ns_send(conn->ns_conn, chunk_size, n);
1842 ns_send(conn->ns_conn, buf, len);
1843 ns_send(conn->ns_conn, "\r\n", 2);
1846 size_t mg_printf(struct mg_connection *conn, const char *fmt, ...) {
1847 struct connection *c = MG_CONN_2_CONN(conn);
1851 ns_vprintf(c->ns_conn, fmt, ap);
1854 return c->ns_conn->send_iobuf.len;
1857 static void ns_forward(struct ns_connection *from, struct ns_connection *to) {
1858 DBG(("%p -> %p %lu bytes", from, to, (unsigned long)from->recv_iobuf.len));
1859 ns_send(to, from->recv_iobuf.buf, from->recv_iobuf.len);
1860 iobuf_remove(&from->recv_iobuf, from->recv_iobuf.len);
1863 #ifndef MONGOOSE_NO_CGI
1865 struct threadparam {
1870 static int wait_until_ready(sock_t sock, int for_read) {
1874 select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0);
1878 static void *push_to_stdin(void *arg) {
1879 struct threadparam *tp = (struct threadparam *)arg;
1880 int n, sent, stop = 0;
1882 char buf[IOBUF_SIZE];
1884 while (!stop && wait_until_ready(tp->s, 1) &&
1885 (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
1886 if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
1887 for (sent = 0; !stop && sent < n; sent += k) {
1888 if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
1891 DBG(("%s", "FORWARED EVERYTHING TO CGI"));
1892 CloseHandle(tp->hPipe);
1898 static void *pull_from_stdout(void *arg) {
1899 struct threadparam *tp = (struct threadparam *)arg;
1900 int k = 0, stop = 0;
1902 char buf[IOBUF_SIZE];
1904 while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
1905 for (sent = 0; !stop && sent < n; sent += k) {
1906 if (wait_until_ready(tp->s, 0) &&
1907 (k = send(tp->s, buf + sent, n - sent, 0)) <= 0) stop = 1;
1910 DBG(("%s", "EOF FROM CGI"));
1911 CloseHandle(tp->hPipe);
1912 shutdown(tp->s, 2); // Without this, IO thread may get truncated data
1919 static void spawn_stdio_thread(sock_t sock, HANDLE hPipe,
1920 void *(*func)(void *)) {
1921 struct threadparam *tp = (struct threadparam *)malloc(sizeof(*tp));
1925 mg_start_thread(func, tp);
1929 static void abs_path(const char *utf8_path, char *abs_path, size_t len) {
1930 wchar_t buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE];
1931 to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
1932 GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
1933 WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
1936 static process_id_t start_process(char *interp, const char *cmd,
1937 const char *env, const char *envp[],
1938 const char *dir, sock_t sock) {
1940 PROCESS_INFORMATION pi;
1941 HANDLE a[2], b[2], me = GetCurrentProcess();
1942 wchar_t wcmd[MAX_PATH_SIZE], full_dir[MAX_PATH_SIZE];
1943 char buf[MAX_PATH_SIZE], buf4[MAX_PATH_SIZE], buf5[MAX_PATH_SIZE],
1944 cmdline[MAX_PATH_SIZE], *p;
1945 DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
1948 memset(&si, 0, sizeof(si));
1949 memset(&pi, 0, sizeof(pi));
1952 si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
1953 si.wShowWindow = SW_HIDE;
1954 si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
1956 CreatePipe(&a[0], &a[1], NULL, 0);
1957 CreatePipe(&b[0], &b[1], NULL, 0);
1958 DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
1959 DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
1961 if (interp == NULL && (fp = fopen(cmd, "r")) != NULL) {
1962 buf[0] = buf[1] = '\0';
1963 fgets(buf, sizeof(buf), fp);
1964 buf[sizeof(buf) - 1] = '\0';
1965 if (buf[0] == '#' && buf[1] == '!') {
1967 for (p = interp + strlen(interp) - 1;
1968 isspace(* (uint8_t *) p) && p > interp; p--) *p = '\0';
1973 if (interp != NULL) {
1974 abs_path(interp, buf4, ARRAY_SIZE(buf4));
1977 abs_path(dir, buf5, ARRAY_SIZE(buf5));
1978 to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
1979 mg_snprintf(cmdline, sizeof(cmdline), "%s%s\"%s\"",
1980 interp ? interp : "", interp ? " " : "", cmd);
1981 to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
1983 if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
1984 (void *) env, full_dir, &si, &pi) != 0) {
1985 spawn_stdio_thread(sock, a[1], push_to_stdin);
1986 spawn_stdio_thread(sock, b[0], pull_from_stdout);
1992 DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
1994 // Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE
1995 CloseHandle(si.hStdOutput);
1996 CloseHandle(si.hStdInput);
1997 //CloseHandle(pi.hThread);
1998 //CloseHandle(pi.hProcess);
2003 static process_id_t start_process(const char *interp, const char *cmd,
2004 const char *env, const char *envp[],
2005 const char *dir, sock_t sock) {
2007 process_id_t pid = fork();
2012 (void) dup2(sock, 0);
2013 (void) dup2(sock, 1);
2016 // After exec, all signal handlers are restored to their default values,
2017 // with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
2018 // implementation, SIGCHLD's handler will leave unchanged after exec
2019 // if it was set to be ignored. Restore it to default action.
2020 signal(SIGCHLD, SIG_DFL);
2022 if (interp == NULL) {
2023 execle(cmd, cmd, (char *) 0, envp); // Using (char *) 0 to avoid warning
2025 execle(interp, interp, cmd, (char *) 0, envp);
2027 snprintf(buf, sizeof(buf), "Status: 500\r\n\r\n"
2028 "500 Server Error: %s%s%s: %s", interp == NULL ? "" : interp,
2029 interp == NULL ? "" : " ", cmd, strerror(errno));
2030 send(1, buf, strlen(buf), 0);
2031 exit(EXIT_FAILURE); // exec call failed
2038 // This structure helps to create an environment for the spawned CGI program.
2039 // Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
2040 // last element must be NULL.
2041 // However, on Windows there is a requirement that all these VARIABLE=VALUE\0
2042 // strings must reside in a contiguous buffer. The end of the buffer is
2043 // marked by two '\0' characters.
2044 // We satisfy both worlds: we create an envp array (which is vars), all
2045 // entries are actually pointers inside buf.
2046 struct cgi_env_block {
2047 struct mg_connection *conn;
2048 char buf[CGI_ENVIRONMENT_SIZE]; // Environment buffer
2049 const char *vars[MAX_CGI_ENVIR_VARS]; // char *envp[]
2050 int len; // Space taken
2051 int nvars; // Number of variables in envp[]
2054 // Append VARIABLE=VALUE\0 string to the buffer, and add a respective
2055 // pointer into the vars array.
2056 static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {
2061 // Calculate how much space is left in the buffer
2062 space = sizeof(block->buf) - block->len - 2;
2065 // Make a pointer to the free space int the buffer
2066 added = block->buf + block->len;
2068 // Copy VARIABLE=VALUE\0 string into the free space
2070 n = mg_vsnprintf(added, (size_t) space, fmt, ap);
2073 // Make sure we do not overflow buffer and the envp array
2074 if (n > 0 && n + 1 < space &&
2075 block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
2076 // Append a pointer to the added string into the envp array
2077 block->vars[block->nvars++] = added;
2078 // Bump up used length counter. Include \0 terminator
2079 block->len += n + 1;
2085 static void addenv2(struct cgi_env_block *blk, const char *name) {
2087 if ((s = getenv(name)) != NULL) addenv(blk, "%s=%s", name, s);
2090 static void prepare_cgi_environment(struct connection *conn,
2092 struct cgi_env_block *blk) {
2093 struct mg_connection *ri = &conn->mg_conn;
2094 const char *s, *slash;
2095 char *p, **opts = conn->server->config_options;
2098 blk->len = blk->nvars = 0;
2101 if ((s = getenv("SERVER_NAME")) != NULL) {
2102 addenv(blk, "SERVER_NAME=%s", s);
2104 addenv(blk, "SERVER_NAME=%s", ri->local_ip);
2106 addenv(blk, "SERVER_ROOT=%s", opts[DOCUMENT_ROOT]);
2107 addenv(blk, "DOCUMENT_ROOT=%s", opts[DOCUMENT_ROOT]);
2108 addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MONGOOSE_VERSION);
2110 // Prepare the environment block
2111 addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
2112 addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
2113 addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP
2115 // TODO(lsm): fix this for IPv6 case
2116 //addenv(blk, "SERVER_PORT=%d", ri->remote_port);
2118 addenv(blk, "REQUEST_METHOD=%s", ri->request_method);
2119 addenv(blk, "REMOTE_ADDR=%s", ri->remote_ip);
2120 addenv(blk, "REMOTE_PORT=%d", ri->remote_port);
2121 addenv(blk, "REQUEST_URI=%s%s%s", ri->uri,
2122 ri->query_string == NULL ? "" : "?",
2123 ri->query_string == NULL ? "" : ri->query_string);
2126 if (conn->path_info != NULL) {
2127 addenv(blk, "SCRIPT_NAME=%.*s",
2128 (int) (strlen(ri->uri) - strlen(conn->path_info)), ri->uri);
2129 addenv(blk, "PATH_INFO=%s", conn->path_info);
2131 s = strrchr(prog, '/');
2132 slash = strrchr(ri->uri, '/');
2133 addenv(blk, "SCRIPT_NAME=%.*s%s",
2134 slash == NULL ? 0 : (int) (slash - ri->uri), ri->uri,
2135 s == NULL ? prog : s);
2138 addenv(blk, "SCRIPT_FILENAME=%s", prog);
2139 addenv(blk, "PATH_TRANSLATED=%s", prog);
2140 addenv(blk, "HTTPS=%s", conn->ns_conn->ssl != NULL ? "on" : "off");
2142 if ((s = mg_get_header(ri, "Content-Type")) != NULL)
2143 addenv(blk, "CONTENT_TYPE=%s", s);
2145 if (ri->query_string != NULL)
2146 addenv(blk, "QUERY_STRING=%s", ri->query_string);
2148 if ((s = mg_get_header(ri, "Content-Length")) != NULL)
2149 addenv(blk, "CONTENT_LENGTH=%s", s);
2151 addenv2(blk, "PATH");
2152 addenv2(blk, "TMP");
2153 addenv2(blk, "TEMP");
2154 addenv2(blk, "TMPDIR");
2155 addenv2(blk, "PERLLIB");
2156 addenv2(blk, ENV_EXPORT_TO_CGI);
2159 addenv2(blk, "COMSPEC");
2160 addenv2(blk, "SYSTEMROOT");
2161 addenv2(blk, "SystemDrive");
2162 addenv2(blk, "ProgramFiles");
2163 addenv2(blk, "ProgramFiles(x86)");
2164 addenv2(blk, "CommonProgramFiles(x86)");
2166 addenv2(blk, "LD_LIBRARY_PATH");
2169 // Add all headers as HTTP_* variables
2170 for (i = 0; i < ri->num_headers; i++) {
2171 p = addenv(blk, "HTTP_%s=%s",
2172 ri->http_headers[i].name, ri->http_headers[i].value);
2174 // Convert variable name into uppercase, and change - to _
2175 for (; *p != '=' && *p != '\0'; p++) {
2178 *p = (char) toupper(* (unsigned char *) p);
2182 blk->vars[blk->nvars++] = NULL;
2183 blk->buf[blk->len++] = '\0';
2185 assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
2186 assert(blk->len > 0);
2187 assert(blk->len < (int) sizeof(blk->buf));
2190 static const char cgi_status[] = "HTTP/1.1 200 OK\r\n";
2192 static void open_cgi_endpoint(struct connection *conn, const char *prog) {
2193 struct cgi_env_block blk;
2194 char dir[MAX_PATH_SIZE];
2198 prepare_cgi_environment(conn, prog, &blk);
2199 // CGI must be executed in its own directory. 'dir' must point to the
2200 // directory containing executable program, 'p' must point to the
2201 // executable program name relative to 'dir'.
2202 if ((p = strrchr(prog, '/')) == NULL) {
2203 mg_snprintf(dir, sizeof(dir), "%s", ".");
2205 mg_snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
2208 // Try to create socketpair in a loop until success. ns_socketpair()
2209 // can be interrupted by a signal and fail.
2210 // TODO(lsm): use sigaction to restart interrupted syscall
2213 } while (fds[0] == INVALID_SOCKET);
2215 if (start_process(conn->server->config_options[CGI_INTERPRETER],
2216 prog, blk.buf, blk.vars, dir, fds[1]) != 0) {
2217 conn->endpoint_type = EP_CGI;
2218 conn->endpoint.nc = ns_add_sock(&conn->server->ns_mgr, fds[0],
2219 mg_ev_handler, conn);
2220 conn->endpoint.nc->flags |= MG_CGI_CONN;
2221 ns_send(conn->ns_conn, cgi_status, sizeof(cgi_status) - 1);
2222 conn->mg_conn.status_code = 200;
2223 conn->ns_conn->flags |= NSF_BUFFER_BUT_DONT_SEND;
2224 // Pass POST data to the CGI process
2225 conn->endpoint.nc->send_iobuf = conn->ns_conn->recv_iobuf;
2226 iobuf_init(&conn->ns_conn->recv_iobuf, 0);
2228 closesocket(fds[0]);
2229 send_http_error(conn, 500, "start_process(%s) failed", prog);
2233 closesocket(fds[1]); // On Windows, CGI stdio thread closes that socket
2237 static void on_cgi_data(struct ns_connection *nc) {
2238 struct connection *conn = (struct connection *) nc->user_data;
2239 const char *status = "500";
2240 struct mg_connection c;
2244 // Copy CGI data from CGI socket to the client send buffer
2245 ns_forward(nc, conn->ns_conn);
2247 // If reply has not been parsed yet, parse it
2248 if (conn->ns_conn->flags & NSF_BUFFER_BUT_DONT_SEND) {
2249 struct iobuf *io = &conn->ns_conn->send_iobuf;
2250 int s_len = sizeof(cgi_status) - 1;
2251 int len = get_request_len(io->buf + s_len, io->len - s_len);
2252 char buf[MAX_REQUEST_SIZE], *s = buf;
2254 if (len == 0) return;
2256 if (len < 0 || len > (int) sizeof(buf)) {
2258 iobuf_remove(io, io->len);
2259 send_http_error(conn, 500, "CGI program sent malformed headers: [%.*s]",
2262 memset(&c, 0, sizeof(c));
2263 memcpy(buf, io->buf + s_len, len);
2264 buf[len - 1] = '\0';
2265 parse_http_headers(&s, &c);
2266 if (mg_get_header(&c, "Location") != NULL) {
2268 } else if ((status = (char *) mg_get_header(&c, "Status")) == NULL) {
2271 memcpy(io->buf + 9, status, 3);
2272 conn->mg_conn.status_code = atoi(status);
2274 conn->ns_conn->flags &= ~NSF_BUFFER_BUT_DONT_SEND;
2277 #endif // !MONGOOSE_NO_CGI
2279 static char *mg_strdup(const char *str) {
2280 char *copy = (char *) malloc(strlen(str) + 1);
2287 static int isbyte(int n) {
2288 return n >= 0 && n <= 255;
2291 static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
2292 int n, a, b, c, d, slash = 32, len = 0;
2294 if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
2295 sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
2296 isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&
2297 slash >= 0 && slash < 33) {
2299 *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
2300 *mask = slash ? 0xffffffffU << (32 - slash) : 0;
2306 // Verify given socket address against the ACL.
2307 // Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
2308 static int check_acl(const char *acl, uint32_t remote_ip) {
2313 // If any ACL is set, deny by default
2314 allowed = acl == NULL ? '+' : '-';
2316 while ((acl = next_option(acl, &vec, NULL)) != NULL) {
2318 if ((flag != '+' && flag != '-') ||
2319 parse_net(&vec.ptr[1], &net, &mask) == 0) {
2323 if (net == (remote_ip & mask)) {
2328 return allowed == '+';
2331 // Protect against directory disclosure attack by removing '..',
2332 // excessive '/' and '\' characters
2333 static void remove_double_dots_and_double_slashes(char *s) {
2336 while (*s != '\0') {
2338 if (s[-1] == '/' || s[-1] == '\\') {
2339 // Skip all following slashes, backslashes and double-dots
2340 while (s[0] != '\0') {
2341 if (s[0] == '/' || s[0] == '\\') { s++; }
2342 else if (s[0] == '.' && s[1] == '.') { s += 2; }
2350 int mg_url_decode(const char *src, int src_len, char *dst,
2351 int dst_len, int is_form_url_encoded) {
2353 #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
2355 for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
2356 if (src[i] == '%' && i < src_len - 2 &&
2357 isxdigit(* (const unsigned char *) (src + i + 1)) &&
2358 isxdigit(* (const unsigned char *) (src + i + 2))) {
2359 a = tolower(* (const unsigned char *) (src + i + 1));
2360 b = tolower(* (const unsigned char *) (src + i + 2));
2361 dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
2363 } else if (is_form_url_encoded && src[i] == '+') {
2370 dst[j] = '\0'; // Null-terminate the destination
2372 return i >= src_len ? j : -1;
2375 static int is_valid_http_method(const char *s) {
2376 return !strcmp(s, "GET") || !strcmp(s, "POST") || !strcmp(s, "HEAD") ||
2377 !strcmp(s, "CONNECT") || !strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
2378 !strcmp(s, "OPTIONS") || !strcmp(s, "PROPFIND") || !strcmp(s, "MKCOL");
2381 // Parse HTTP request, fill in mg_request structure.
2382 // This function modifies the buffer by NUL-terminating
2383 // HTTP request components, header names and header values.
2384 // Note that len must point to the last \n of HTTP headers.
2385 static int parse_http_message(char *buf, int len, struct mg_connection *ri) {
2388 // Reset the connection. Make sure that we don't touch fields that are
2389 // set elsewhere: remote_ip, remote_port, server_param
2390 ri->request_method = ri->uri = ri->http_version = ri->query_string = NULL;
2391 ri->num_headers = ri->status_code = ri->is_websocket = ri->content_len = 0;
2393 buf[len - 1] = '\0';
2395 // RFC says that all initial whitespaces should be ingored
2396 while (*buf != '\0' && isspace(* (unsigned char *) buf)) {
2399 ri->request_method = skip(&buf, " ");
2400 ri->uri = skip(&buf, " ");
2401 ri->http_version = skip(&buf, "\r\n");
2403 // HTTP message could be either HTTP request or HTTP response, e.g.
2404 // "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..."
2405 is_request = is_valid_http_method(ri->request_method);
2406 if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) ||
2407 (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
2411 ri->http_version += 5;
2413 ri->status_code = atoi(ri->uri);
2415 parse_http_headers(&buf, ri);
2417 if ((ri->query_string = strchr(ri->uri, '?')) != NULL) {
2418 *(char *) ri->query_string++ = '\0';
2420 n = (int) strlen(ri->uri);
2421 mg_url_decode(ri->uri, n, (char *) ri->uri, n + 1, 0);
2422 if (*ri->uri == '/' || *ri->uri == '.') {
2423 remove_double_dots_and_double_slashes((char *) ri->uri);
2430 static int lowercase(const char *s) {
2431 return tolower(* (const unsigned char *) s);
2434 static int mg_strcasecmp(const char *s1, const char *s2) {
2438 diff = lowercase(s1++) - lowercase(s2++);
2439 } while (diff == 0 && s1[-1] != '\0');
2444 static int mg_strncasecmp(const char *s1, const char *s2, size_t len) {
2449 diff = lowercase(s1++) - lowercase(s2++);
2450 } while (diff == 0 && s1[-1] != '\0' && --len > 0);
2455 // Return HTTP header value, or NULL if not found.
2456 const char *mg_get_header(const struct mg_connection *ri, const char *s) {
2459 for (i = 0; i < ri->num_headers; i++)
2460 if (!mg_strcasecmp(s, ri->http_headers[i].name))
2461 return ri->http_headers[i].value;
2466 // Perform case-insensitive match of string against pattern
2467 int mg_match_prefix(const char *pattern, int pattern_len, const char *str) {
2469 int len, res, i = 0, j = 0;
2471 if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
2472 res = mg_match_prefix(pattern, or_str - pattern, str);
2473 return res > 0 ? res : mg_match_prefix(or_str + 1,
2474 (pattern + pattern_len) - (or_str + 1), str);
2477 for (; i < pattern_len; i++, j++) {
2478 if (pattern[i] == '?' && str[j] != '\0') {
2480 } else if (pattern[i] == '$') {
2481 return str[j] == '\0' ? j : -1;
2482 } else if (pattern[i] == '*') {
2484 if (pattern[i] == '*') {
2486 len = (int) strlen(str + j);
2488 len = (int) strcspn(str + j, "/");
2490 if (i == pattern_len) {
2494 res = mg_match_prefix(pattern + i, pattern_len - i, str + j + len);
2495 } while (res == -1 && len-- > 0);
2496 return res == -1 ? -1 : j + res + len;
2497 } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
2504 // This function prints HTML pages, and expands "{{something}}" blocks
2505 // inside HTML by calling appropriate callback functions.
2506 // Note that {{@path/to/file}} construct outputs embedded file's contents,
2507 // which provides SSI-like functionality.
2508 void mg_template(struct mg_connection *conn, const char *s,
2509 struct mg_expansion *expansions) {
2510 int i, j, pos = 0, inside_marker = 0;
2512 for (i = 0; s[i] != '\0'; i++) {
2513 if (inside_marker == 0 && !memcmp(&s[i], "{{", 2)) {
2515 mg_send_data(conn, &s[pos], i - pos);
2520 if (inside_marker == 1 && !memcmp(&s[i], "}}", 2)) {
2521 for (j = 0; expansions[j].keyword != NULL; j++) {
2522 const char *kw = expansions[j].keyword;
2523 if ((int) strlen(kw) == i - (pos + 2) &&
2524 memcmp(kw, &s[pos + 2], i - (pos + 2)) == 0) {
2525 expansions[j].handler(conn);
2534 mg_send_data(conn, &s[pos], i - pos);
2538 #ifndef MONGOOSE_NO_FILESYSTEM
2539 static int must_hide_file(struct connection *conn, const char *path) {
2540 const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
2541 const char *pattern = conn->server->config_options[HIDE_FILES_PATTERN];
2542 return mg_match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 ||
2543 (pattern != NULL && mg_match_prefix(pattern, strlen(pattern), path) > 0);
2546 // Return 1 if real file has been found, 0 otherwise
2547 static int convert_uri_to_file_name(struct connection *conn, char *buf,
2548 size_t buf_len, file_stat_t *st) {
2550 const char *rewrites = conn->server->config_options[URL_REWRITES];
2551 const char *root = conn->server->config_options[DOCUMENT_ROOT];
2552 #ifndef MONGOOSE_NO_CGI
2553 const char *cgi_pat = conn->server->config_options[CGI_PATTERN];
2556 const char *uri = conn->mg_conn.uri;
2557 const char *domain = mg_get_header(&conn->mg_conn, "Host");
2558 int match_len, root_len = root == NULL ? 0 : strlen(root);
2560 // Perform virtual hosting rewrites
2561 if (rewrites != NULL && domain != NULL) {
2562 const char *colon = strchr(domain, ':');
2563 int domain_len = colon == NULL ? (int) strlen(domain) : colon - domain;
2565 while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
2566 if (a.len > 1 && a.ptr[0] == '@' && a.len == domain_len + 1 &&
2567 mg_strncasecmp(a.ptr + 1, domain, domain_len) == 0) {
2575 // No filesystem access
2576 if (root == NULL || root_len == 0) return 0;
2578 // Handle URL rewrites
2579 mg_snprintf(buf, buf_len, "%.*s%s", root_len, root, uri);
2580 rewrites = conn->server->config_options[URL_REWRITES]; // Re-initialize!
2581 while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
2582 if ((match_len = mg_match_prefix(a.ptr, a.len, uri)) > 0) {
2583 mg_snprintf(buf, buf_len, "%.*s%s", (int) b.len, b.ptr, uri + match_len);
2588 if (stat(buf, st) == 0) return 1;
2590 #ifndef MONGOOSE_NO_CGI
2591 // Support PATH_INFO for CGI scripts.
2592 for (p = buf + strlen(root) + 2; *p != '\0'; p++) {
2595 if (mg_match_prefix(cgi_pat, strlen(cgi_pat), buf) > 0 &&
2597 DBG(("!!!! [%s]", buf));
2599 conn->path_info = mg_strdup(p);
2610 #endif // MONGOOSE_NO_FILESYSTEM
2612 static int should_keep_alive(const struct mg_connection *conn) {
2613 struct connection *c = MG_CONN_2_CONN(conn);
2614 const char *method = conn->request_method;
2615 const char *http_version = conn->http_version;
2616 const char *header = mg_get_header(conn, "Connection");
2617 return method != NULL &&
2618 (!strcmp(method, "GET") || c->endpoint_type == EP_USER) &&
2619 ((header != NULL && !mg_strcasecmp(header, "keep-alive")) ||
2620 (header == NULL && http_version && !strcmp(http_version, "1.1")));
2623 size_t mg_write(struct mg_connection *c, const void *buf, int len) {
2624 struct connection *conn = MG_CONN_2_CONN(c);
2625 ns_send(conn->ns_conn, buf, len);
2626 return conn->ns_conn->send_iobuf.len;
2629 void mg_send_status(struct mg_connection *c, int status) {
2630 if (c->status_code == 0) {
2631 c->status_code = status;
2632 mg_printf(c, "HTTP/1.1 %d %s\r\n", status, status_code_to_str(status));
2636 void mg_send_header(struct mg_connection *c, const char *name, const char *v) {
2637 if (c->status_code == 0) {
2638 c->status_code = 200;
2639 mg_printf(c, "HTTP/1.1 %d %s\r\n", 200, status_code_to_str(200));
2641 mg_printf(c, "%s: %s\r\n", name, v);
2644 static void terminate_headers(struct mg_connection *c) {
2645 struct connection *conn = MG_CONN_2_CONN(c);
2646 if (!(conn->ns_conn->flags & MG_HEADERS_SENT)) {
2647 mg_send_header(c, "Transfer-Encoding", "chunked");
2648 mg_write(c, "\r\n", 2);
2649 conn->ns_conn->flags |= MG_HEADERS_SENT;
2653 size_t mg_send_data(struct mg_connection *c, const void *data, int data_len) {
2654 struct connection *conn = MG_CONN_2_CONN(c);
2655 terminate_headers(c);
2656 write_chunk(MG_CONN_2_CONN(c), (const char *) data, data_len);
2657 return conn->ns_conn->send_iobuf.len;
2660 size_t mg_printf_data(struct mg_connection *c, const char *fmt, ...) {
2661 struct connection *conn = MG_CONN_2_CONN(c);
2664 char mem[IOBUF_SIZE], *buf = mem;
2666 terminate_headers(c);
2669 len = ns_avprintf(&buf, sizeof(mem), fmt, ap);
2673 write_chunk((struct connection *) conn, buf, len);
2675 if (buf != mem && buf != NULL) {
2678 return conn->ns_conn->send_iobuf.len;
2681 #if !defined(MONGOOSE_NO_WEBSOCKET) || !defined(MONGOOSE_NO_AUTH)
2682 static int is_big_endian(void) {
2683 static const int n = 1;
2684 return ((char *) &n)[0] == 0;
2688 #ifndef MONGOOSE_NO_WEBSOCKET
2689 // START OF SHA-1 code
2690 // Copyright(c) By Steve Reid <steve@edmweb.com>
2691 #define SHA1HANDSOFF
2693 #include "solarisfixes.h"
2696 union char64long16 { unsigned char c[64]; uint32_t l[16]; };
2698 #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
2700 static uint32_t blk0(union char64long16 *block, int i) {
2701 // Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN
2702 if (!is_big_endian()) {
2703 block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
2704 (rol(block->l[i], 8) & 0x00FF00FF);
2709 /* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
2717 #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
2718 ^block->l[(i+2)&15]^block->l[i&15],1))
2719 #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30);
2720 #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
2721 #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
2722 #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
2723 #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
2728 unsigned char buffer[64];
2731 static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) {
2732 uint32_t a, b, c, d, e;
2733 union char64long16 block[1];
2735 memcpy(block, buffer, 64);
2741 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);
2742 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);
2743 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);
2744 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);
2745 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);
2746 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);
2747 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);
2748 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);
2749 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);
2750 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);
2751 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);
2752 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);
2753 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);
2754 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);
2755 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);
2756 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);
2757 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);
2758 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);
2759 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);
2760 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);
2766 // Erase working structures. The order of operations is important,
2767 // used to ensure that compiler doesn't optimize those out.
2768 memset(block, 0, sizeof(block));
2769 a = b = c = d = e = 0;
2770 (void) a; (void) b; (void) c; (void) d; (void) e;
2773 static void SHA1Init(SHA1_CTX *context) {
2774 context->state[0] = 0x67452301;
2775 context->state[1] = 0xEFCDAB89;
2776 context->state[2] = 0x98BADCFE;
2777 context->state[3] = 0x10325476;
2778 context->state[4] = 0xC3D2E1F0;
2779 context->count[0] = context->count[1] = 0;
2782 static void SHA1Update(SHA1_CTX *context, const unsigned char *data,
2786 j = context->count[0];
2787 if ((context->count[0] += len << 3) < j)
2788 context->count[1]++;
2789 context->count[1] += (len>>29);
2791 if ((j + len) > 63) {
2792 memcpy(&context->buffer[j], data, (i = 64-j));
2793 SHA1Transform(context->state, context->buffer);
2794 for ( ; i + 63 < len; i += 64) {
2795 SHA1Transform(context->state, &data[i]);
2800 memcpy(&context->buffer[j], &data[i], len - i);
2803 static void SHA1Final(unsigned char digest[20], SHA1_CTX *context) {
2805 unsigned char finalcount[8], c;
2807 for (i = 0; i < 8; i++) {
2808 finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
2809 >> ((3-(i & 3)) * 8) ) & 255);
2812 SHA1Update(context, &c, 1);
2813 while ((context->count[0] & 504) != 448) {
2815 SHA1Update(context, &c, 1);
2817 SHA1Update(context, finalcount, 8);
2818 for (i = 0; i < 20; i++) {
2819 digest[i] = (unsigned char)
2820 ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
2822 memset(context, '\0', sizeof(*context));
2823 memset(&finalcount, '\0', sizeof(finalcount));
2827 static void base64_encode(const unsigned char *src, int src_len, char *dst) {
2828 static const char *b64 =
2829 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2832 for (i = j = 0; i < src_len; i += 3) {
2834 b = i + 1 >= src_len ? 0 : src[i + 1];
2835 c = i + 2 >= src_len ? 0 : src[i + 2];
2837 dst[j++] = b64[a >> 2];
2838 dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
2839 if (i + 1 < src_len) {
2840 dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
2842 if (i + 2 < src_len) {
2843 dst[j++] = b64[c & 63];
2846 while (j % 4 != 0) {
2852 static void send_websocket_handshake(struct mg_connection *conn,
2854 static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
2855 char buf[500], sha[20], b64_sha[sizeof(sha) * 2];
2858 mg_snprintf(buf, sizeof(buf), "%s%s", key, magic);
2860 SHA1Update(&sha_ctx, (unsigned char *) buf, strlen(buf));
2861 SHA1Final((unsigned char *) sha, &sha_ctx);
2862 base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
2863 mg_snprintf(buf, sizeof(buf), "%s%s%s",
2864 "HTTP/1.1 101 Switching Protocols\r\n"
2865 "Upgrade: websocket\r\n"
2866 "Connection: Upgrade\r\n"
2867 "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n");
2869 mg_write(conn, buf, strlen(buf));
2872 static int deliver_websocket_frame(struct connection *conn) {
2873 // Having buf unsigned char * is important, as it is used below in arithmetic
2874 unsigned char *buf = (unsigned char *) conn->ns_conn->recv_iobuf.buf;
2875 int i, len, buf_len = conn->ns_conn->recv_iobuf.len, frame_len = 0,
2876 mask_len = 0, header_len = 0, data_len = 0, buffered = 0;
2880 mask_len = buf[1] & 128 ? 4 : 0;
2881 if (len < 126 && buf_len >= mask_len) {
2883 header_len = 2 + mask_len;
2884 } else if (len == 126 && buf_len >= 4 + mask_len) {
2885 header_len = 4 + mask_len;
2886 data_len = ((((int) buf[2]) << 8) + buf[3]);
2887 } else if (buf_len >= 10 + mask_len) {
2888 header_len = 10 + mask_len;
2889 data_len = (int) (((uint64_t) htonl(* (uint32_t *) &buf[2])) << 32) +
2890 htonl(* (uint32_t *) &buf[6]);
2894 frame_len = header_len + data_len;
2895 buffered = frame_len > 0 && frame_len <= buf_len;
2898 conn->mg_conn.content_len = data_len;
2899 conn->mg_conn.content = (char *) buf + header_len;
2900 conn->mg_conn.wsbits = buf[0];
2902 // Apply mask if necessary
2904 for (i = 0; i < data_len; i++) {
2905 buf[i + header_len] ^= (buf + header_len - mask_len)[i % 4];
2909 // Call the handler and remove frame from the iobuf
2910 if (call_user(conn, MG_REQUEST) == MG_FALSE) {
2911 conn->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
2913 iobuf_remove(&conn->ns_conn->recv_iobuf, frame_len);
2919 size_t mg_websocket_write(struct mg_connection *conn, int opcode,
2920 const char *data, size_t data_len) {
2921 unsigned char mem[4192], *copy = mem;
2922 size_t copy_len = 0;
2924 if (data_len + 10 > sizeof(mem) &&
2925 (copy = (unsigned char *) malloc(data_len + 10)) == NULL) {
2929 copy[0] = 0x80 + (opcode & 0x0f);
2931 // Frame format: http://tools.ietf.org/html/rfc6455#section-5.2
2932 if (data_len < 126) {
2933 // Inline 7-bit length field
2935 memcpy(copy + 2, data, data_len);
2936 copy_len = 2 + data_len;
2937 } else if (data_len <= 0xFFFF) {
2938 // 16-bit length field
2940 * (uint16_t *) (copy + 2) = (uint16_t) htons((uint16_t) data_len);
2941 memcpy(copy + 4, data, data_len);
2942 copy_len = 4 + data_len;
2944 // 64-bit length field
2946 * (uint32_t *) (copy + 2) = (uint32_t)
2947 htonl((uint32_t) ((uint64_t) data_len >> 32));
2948 * (uint32_t *) (copy + 6) = (uint32_t) htonl(data_len & 0xffffffff);
2949 memcpy(copy + 10, data, data_len);
2950 copy_len = 10 + data_len;
2954 mg_write(conn, copy, copy_len);
2960 // If we send closing frame, schedule a connection to be closed after
2961 // data is drained to the client.
2962 if (opcode == WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
2963 MG_CONN_2_CONN(conn)->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
2966 return MG_CONN_2_CONN(conn)->ns_conn->send_iobuf.len;
2969 size_t mg_websocket_printf(struct mg_connection *conn, int opcode,
2970 const char *fmt, ...) {
2971 char mem[4192], *buf = mem;
2976 if ((len = ns_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
2977 mg_websocket_write(conn, opcode, buf, len);
2981 if (buf != mem && buf != NULL) {
2985 return MG_CONN_2_CONN(conn)->ns_conn->send_iobuf.len;
2988 static void send_websocket_handshake_if_requested(struct mg_connection *conn) {
2989 const char *ver = mg_get_header(conn, "Sec-WebSocket-Version"),
2990 *key = mg_get_header(conn, "Sec-WebSocket-Key");
2991 if (ver != NULL && key != NULL) {
2992 conn->is_websocket = 1;
2993 if (call_user(MG_CONN_2_CONN(conn), MG_WS_HANDSHAKE) == MG_FALSE) {
2994 send_websocket_handshake(conn, key);
2996 call_user(MG_CONN_2_CONN(conn), MG_WS_CONNECT);
3000 static void ping_idle_websocket_connection(struct connection *conn, time_t t) {
3001 if (t - conn->ns_conn->last_io_time > MONGOOSE_USE_WEBSOCKET_PING_INTERVAL) {
3002 mg_websocket_write(&conn->mg_conn, WEBSOCKET_OPCODE_PING, "", 0);
3006 #define ping_idle_websocket_connection(conn, t)
3007 #endif // !MONGOOSE_NO_WEBSOCKET
3009 static void write_terminating_chunk(struct connection *conn) {
3010 mg_write(&conn->mg_conn, "0\r\n\r\n", 5);
3013 static int call_request_handler(struct connection *conn) {
3015 conn->mg_conn.content = conn->ns_conn->recv_iobuf.buf;
3016 if ((result = call_user(conn, MG_REQUEST)) == MG_TRUE) {
3017 if (conn->ns_conn->flags & MG_HEADERS_SENT) {
3018 write_terminating_chunk(conn);
3020 close_local_endpoint(conn);
3025 const char *mg_get_mime_type(const char *path, const char *default_mime_type) {
3029 path_len = strlen(path);
3031 for (i = 0; static_builtin_mime_types[i].extension != NULL; i++) {
3032 ext = path + (path_len - static_builtin_mime_types[i].ext_len);
3033 if (path_len > static_builtin_mime_types[i].ext_len &&
3034 mg_strcasecmp(ext, static_builtin_mime_types[i].extension) == 0) {
3035 return static_builtin_mime_types[i].mime_type;
3039 return default_mime_type;
3042 #ifndef MONGOOSE_NO_FILESYSTEM
3043 // Convert month to the month number. Return -1 on error, or month number
3044 static int get_month_index(const char *s) {
3045 static const char *month_names[] = {
3046 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3047 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3051 for (i = 0; i < (int) ARRAY_SIZE(month_names); i++)
3052 if (!strcmp(s, month_names[i]))
3058 static int num_leap_years(int year) {
3059 return year / 4 - year / 100 + year / 400;
3062 // Parse UTC date-time string, and return the corresponding time_t value.
3063 static time_t parse_date_string(const char *datetime) {
3064 static const unsigned short days_before_month[] = {
3065 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
3068 int second, minute, hour, day, month, year, leap_days, days;
3069 time_t result = (time_t) 0;
3071 if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d",
3072 &day, month_str, &year, &hour, &minute, &second) == 6) ||
3073 (sscanf(datetime, "%d %3s %d %d:%d:%d",
3074 &day, month_str, &year, &hour, &minute, &second) == 6) ||
3075 (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",
3076 &day, month_str, &year, &hour, &minute, &second) == 6) ||
3077 (sscanf(datetime, "%d-%3s-%d %d:%d:%d",
3078 &day, month_str, &year, &hour, &minute, &second) == 6)) &&
3080 (month = get_month_index(month_str)) != -1) {
3081 leap_days = num_leap_years(year) - num_leap_years(1970);
3083 days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
3084 result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
3090 // Look at the "path" extension and figure what mime type it has.
3091 // Store mime type in the vector.
3092 static void get_mime_type(const struct mg_server *server, const char *path,
3094 struct vec ext_vec, mime_vec;
3095 const char *list, *ext;
3098 path_len = strlen(path);
3100 // Scan user-defined mime types first, in case user wants to
3101 // override default mime types.
3102 list = server->config_options[EXTRA_MIME_TYPES];
3103 while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
3104 // ext now points to the path suffix
3105 ext = path + path_len - ext_vec.len;
3106 if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
3112 vec->ptr = mg_get_mime_type(path, "text/plain");
3113 vec->len = strlen(vec->ptr);
3116 static const char *suggest_connection_header(const struct mg_connection *conn) {
3117 return should_keep_alive(conn) ? "keep-alive" : "close";
3120 static void construct_etag(char *buf, size_t buf_len, const file_stat_t *st) {
3121 mg_snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"",
3122 (unsigned long) st->st_mtime, (int64_t) st->st_size);
3125 // Return True if we should reply 304 Not Modified.
3126 static int is_not_modified(const struct connection *conn,
3127 const file_stat_t *stp) {
3129 const char *ims = mg_get_header(&conn->mg_conn, "If-Modified-Since");
3130 const char *inm = mg_get_header(&conn->mg_conn, "If-None-Match");
3131 construct_etag(etag, sizeof(etag), stp);
3132 return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
3133 (ims != NULL && stp->st_mtime <= parse_date_string(ims));
3136 // For given directory path, substitute it to valid index file.
3137 // Return 0 if index file has been found, -1 if not found.
3138 // If the file is found, it's stats is returned in stp.
3139 static int find_index_file(struct connection *conn, char *path,
3140 size_t path_len, file_stat_t *stp) {
3141 const char *list = conn->server->config_options[INDEX_FILES];
3143 struct vec filename_vec;
3144 size_t n = strlen(path), found = 0;
3146 // The 'path' given to us points to the directory. Remove all trailing
3147 // directory separator characters from the end of the path, and
3148 // then append single directory separator character.
3149 while (n > 0 && path[n - 1] == '/') {
3154 // Traverse index files list. For each entry, append it to the given
3155 // path and see if the file exists. If it exists, break the loop
3156 while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
3158 // Ignore too long entries that may overflow path buffer
3159 if (filename_vec.len > (int) (path_len - (n + 2)))
3162 // Prepare full path to the index file
3163 strncpy(path + n + 1, filename_vec.ptr, filename_vec.len);
3164 path[n + 1 + filename_vec.len] = '\0';
3166 //DBG(("[%s]", path));
3169 if (!stat(path, &st)) {
3170 // Yes it does, break the loop
3177 // If no index file exists, restore directory path
3185 static int parse_range_header(const char *header, int64_t *a, int64_t *b) {
3186 return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
3189 static void gmt_time_string(char *buf, size_t buf_len, time_t *t) {
3190 strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
3193 static void open_file_endpoint(struct connection *conn, const char *path,
3194 file_stat_t *st, const char *extra_headers) {
3195 char date[64], lm[64], etag[64], range[64], headers[1000];
3196 const char *msg = "OK", *hdr;
3197 time_t curtime = time(NULL);
3199 struct vec mime_vec;
3202 conn->endpoint_type = EP_FILE;
3203 ns_set_close_on_exec(conn->endpoint.fd);
3204 conn->mg_conn.status_code = 200;
3206 get_mime_type(conn->server, path, &mime_vec);
3207 conn->cl = st->st_size;
3210 // If Range: header specified, act accordingly
3212 hdr = mg_get_header(&conn->mg_conn, "Range");
3213 if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 &&
3214 r1 >= 0 && r2 >= 0) {
3215 conn->mg_conn.status_code = 206;
3216 conn->cl = n == 2 ? (r2 > conn->cl ? conn->cl : r2) - r1 + 1: conn->cl - r1;
3217 mg_snprintf(range, sizeof(range), "Content-Range: bytes "
3218 "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
3219 r1, r1 + conn->cl - 1, (int64_t) st->st_size);
3220 msg = "Partial Content";
3221 lseek(conn->endpoint.fd, r1, SEEK_SET);
3224 // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
3225 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
3226 gmt_time_string(date, sizeof(date), &curtime);
3227 gmt_time_string(lm, sizeof(lm), &st->st_mtime);
3228 construct_etag(etag, sizeof(etag), st);
3230 n = mg_snprintf(headers, sizeof(headers),
3231 "HTTP/1.1 %d %s\r\n"
3233 "Last-Modified: %s\r\n"
3235 "Content-Type: %.*s\r\n"
3236 "Content-Length: %" INT64_FMT "\r\n"
3237 "Connection: %s\r\n"
3238 "Accept-Ranges: bytes\r\n"
3240 conn->mg_conn.status_code, msg, date, lm, etag,
3241 (int) mime_vec.len, mime_vec.ptr, conn->cl,
3242 suggest_connection_header(&conn->mg_conn),
3243 range, extra_headers == NULL ? "" : extra_headers,
3244 MONGOOSE_USE_EXTRA_HTTP_HEADERS);
3245 ns_send(conn->ns_conn, headers, n);
3247 if (!strcmp(conn->mg_conn.request_method, "HEAD")) {
3248 conn->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
3249 close(conn->endpoint.fd);
3250 conn->endpoint_type = EP_NONE;
3254 void mg_send_file_data(struct mg_connection *c, int fd) {
3255 struct connection *conn = MG_CONN_2_CONN(c);
3256 conn->endpoint_type = EP_FILE;
3257 conn->endpoint.fd = fd;
3258 ns_set_close_on_exec(conn->endpoint.fd);
3260 #endif // MONGOOSE_NO_FILESYSTEM
3262 static void call_request_handler_if_data_is_buffered(struct connection *conn) {
3263 #ifndef MONGOOSE_NO_WEBSOCKET
3264 if (conn->mg_conn.is_websocket) {
3265 do { } while (deliver_websocket_frame(conn));
3268 if (conn->num_bytes_recv >= (conn->cl + conn->request_len) &&
3269 call_request_handler(conn) == MG_FALSE) {
3270 open_local_endpoint(conn, 1);
3274 #if !defined(MONGOOSE_NO_DIRECTORY_LISTING) || !defined(MONGOOSE_NO_DAV)
3278 char d_name[MAX_PATH_SIZE];
3281 typedef struct DIR {
3283 WIN32_FIND_DATAW info;
3284 struct dirent result;
3287 // Implementation of POSIX opendir/closedir/readdir for Windows.
3288 static DIR *opendir(const char *name) {
3290 wchar_t wpath[MAX_PATH_SIZE];
3294 SetLastError(ERROR_BAD_ARGUMENTS);
3295 } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) {
3296 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
3298 to_wchar(name, wpath, ARRAY_SIZE(wpath));
3299 attrs = GetFileAttributesW(wpath);
3300 if (attrs != 0xFFFFFFFF &&
3301 ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
3302 (void) wcscat(wpath, L"\\*");
3303 dir->handle = FindFirstFileW(wpath, &dir->info);
3304 dir->result.d_name[0] = '\0';
3314 static int closedir(DIR *dir) {
3318 if (dir->handle != INVALID_HANDLE_VALUE)
3319 result = FindClose(dir->handle) ? 0 : -1;
3324 SetLastError(ERROR_BAD_ARGUMENTS);
3330 static struct dirent *readdir(DIR *dir) {
3331 struct dirent *result = 0;
3334 if (dir->handle != INVALID_HANDLE_VALUE) {
3335 result = &dir->result;
3336 (void) WideCharToMultiByte(CP_UTF8, 0,
3337 dir->info.cFileName, -1, result->d_name,
3338 sizeof(result->d_name), NULL, NULL);
3340 if (!FindNextFileW(dir->handle, &dir->info)) {
3341 (void) FindClose(dir->handle);
3342 dir->handle = INVALID_HANDLE_VALUE;
3346 SetLastError(ERROR_FILE_NOT_FOUND);
3349 SetLastError(ERROR_BAD_ARGUMENTS);
3354 #endif // _WIN32 POSIX opendir/closedir/readdir implementation
3356 static int scan_directory(struct connection *conn, const char *dir,
3357 struct dir_entry **arr) {
3358 char path[MAX_PATH_SIZE];
3359 struct dir_entry *p;
3361 int arr_size = 0, arr_ind = 0, inc = 100;
3365 if ((dirp = (opendir(dir))) == NULL) return 0;
3367 while ((dp = readdir(dirp)) != NULL) {
3368 // Do not show current dir and hidden files
3369 if (!strcmp(dp->d_name, ".") ||
3370 !strcmp(dp->d_name, "..") ||
3371 must_hide_file(conn, dp->d_name)) {
3374 mg_snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
3376 // Resize the array if nesessary
3377 if (arr_ind >= arr_size) {
3378 if ((p = (struct dir_entry *)
3379 realloc(*arr, (inc + arr_size) * sizeof(**arr))) != NULL) {
3380 // Memset new chunk to zero, otherwize st_mtime will have garbage which
3381 // can make strftime() segfault, see
3382 // http://code.google.com/p/mongoose/issues/detail?id=79
3383 memset(p + arr_size, 0, sizeof(**arr) * inc);
3390 if (arr_ind < arr_size) {
3391 (*arr)[arr_ind].conn = conn;
3392 (*arr)[arr_ind].file_name = strdup(dp->d_name);
3393 stat(path, &(*arr)[arr_ind].st);
3402 int mg_url_encode(const char *src, size_t s_len, char *dst, size_t dst_len) {
3403 static const char *dont_escape = "._-$,;~()";
3404 static const char *hex = "0123456789abcdef";
3405 size_t i = 0, j = 0;
3407 for (i = j = 0; dst_len > 0 && i < s_len && j + 2 < dst_len - 1; i++, j++) {
3408 if (isalnum(* (const unsigned char *) (src + i)) ||
3409 strchr(dont_escape, * (const unsigned char *) (src + i)) != NULL) {
3411 } else if (j + 3 < dst_len) {
3413 dst[j + 1] = hex[(* (const unsigned char *) (src + i)) >> 4];
3414 dst[j + 2] = hex[(* (const unsigned char *) (src + i)) & 0xf];
3422 #endif // !NO_DIRECTORY_LISTING || !MONGOOSE_NO_DAV
3424 #ifndef MONGOOSE_NO_DIRECTORY_LISTING
3426 static void print_dir_entry(const struct dir_entry *de) {
3427 char size[64], mod[64], href[MAX_PATH_SIZE * 3];
3428 int64_t fsize = de->st.st_size;
3429 int is_dir = S_ISDIR(de->st.st_mode);
3430 const char *slash = is_dir ? "/" : "";
3433 mg_snprintf(size, sizeof(size), "%s", "[DIRECTORY]");
3435 // We use (signed) cast below because MSVC 6 compiler cannot
3436 // convert unsigned __int64 to double.
3438 mg_snprintf(size, sizeof(size), "%d", (int) fsize);
3439 } else if (fsize < 0x100000) {
3440 mg_snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0);
3441 } else if (fsize < 0x40000000) {
3442 mg_snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576);
3444 mg_snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824);
3447 strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&de->st.st_mtime));
3448 mg_url_encode(de->file_name, strlen(de->file_name), href, sizeof(href));
3449 mg_printf_data(&de->conn->mg_conn,
3450 "<tr><td><a href=\"%s%s\">%s%s</a></td>"
3451 "<td> %s</td><td> %s</td></tr>\n",
3452 href, slash, de->file_name, slash, mod, size);
3455 // Sort directory entries by size, or name, or modification time.
3456 // On windows, __cdecl specification is needed in case if project is built
3457 // with __stdcall convention. qsort always requires __cdels callback.
3458 static int __cdecl compare_dir_entries(const void *p1, const void *p2) {
3459 const struct dir_entry *a = (const struct dir_entry *) p1,
3460 *b = (const struct dir_entry *) p2;
3461 const char *qs = a->conn->mg_conn.query_string ?
3462 a->conn->mg_conn.query_string : "na";
3465 if (S_ISDIR(a->st.st_mode) && !S_ISDIR(b->st.st_mode)) {
3466 return -1; // Always put directories on top
3467 } else if (!S_ISDIR(a->st.st_mode) && S_ISDIR(b->st.st_mode)) {
3468 return 1; // Always put directories on top
3469 } else if (*qs == 'n') {
3470 cmp_result = strcmp(a->file_name, b->file_name);
3471 } else if (*qs == 's') {
3472 cmp_result = a->st.st_size == b->st.st_size ? 0 :
3473 a->st.st_size > b->st.st_size ? 1 : -1;
3474 } else if (*qs == 'd') {
3475 cmp_result = a->st.st_mtime == b->st.st_mtime ? 0 :
3476 a->st.st_mtime > b->st.st_mtime ? 1 : -1;
3479 return qs[1] == 'd' ? -cmp_result : cmp_result;
3482 static void send_directory_listing(struct connection *conn, const char *dir) {
3483 struct dir_entry *arr = NULL;
3484 int i, num_entries, sort_direction = conn->mg_conn.query_string != NULL &&
3485 conn->mg_conn.query_string[1] == 'd' ? 'a' : 'd';
3487 mg_send_header(&conn->mg_conn, "Transfer-Encoding", "chunked");
3488 mg_send_header(&conn->mg_conn, "Content-Type", "text/html; charset=utf-8");
3490 mg_printf_data(&conn->mg_conn,
3491 "<html><head><title>Index of %s</title>"
3492 "<style>th {text-align: left;}</style></head>"
3493 "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
3494 "<tr><th><a href=\"?n%c\">Name</a></th>"
3495 "<th><a href=\"?d%c\">Modified</a></th>"
3496 "<th><a href=\"?s%c\">Size</a></th></tr>"
3497 "<tr><td colspan=\"3\"><hr></td></tr>",
3498 conn->mg_conn.uri, conn->mg_conn.uri,
3499 sort_direction, sort_direction, sort_direction);
3501 num_entries = scan_directory(conn, dir, &arr);
3502 qsort(arr, num_entries, sizeof(arr[0]), compare_dir_entries);
3503 for (i = 0; i < num_entries; i++) {
3504 print_dir_entry(&arr[i]);
3505 free(arr[i].file_name);
3509 write_terminating_chunk(conn);
3510 close_local_endpoint(conn);
3512 #endif // MONGOOSE_NO_DIRECTORY_LISTING
3514 #ifndef MONGOOSE_NO_DAV
3515 static void print_props(struct connection *conn, const char *uri,
3519 gmt_time_string(mtime, sizeof(mtime), &stp->st_mtime);
3520 mg_printf(&conn->mg_conn,
3522 "<d:href>%s</d:href>"
3525 "<d:resourcetype>%s</d:resourcetype>"
3526 "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
3527 "<d:getlastmodified>%s</d:getlastmodified>"
3529 "<d:status>HTTP/1.1 200 OK</d:status>"
3532 uri, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "",
3533 (int64_t) stp->st_size, mtime);
3536 static void handle_propfind(struct connection *conn, const char *path,
3537 file_stat_t *stp, int exists) {
3538 static const char header[] = "HTTP/1.1 207 Multi-Status\r\n"
3539 "Connection: close\r\n"
3540 "Content-Type: text/xml; charset=utf-8\r\n\r\n"
3541 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
3542 "<d:multistatus xmlns:d='DAV:'>\n";
3543 static const char footer[] = "</d:multistatus>";
3544 const char *depth = mg_get_header(&conn->mg_conn, "Depth");
3545 #ifdef MONGOOSE_NO_DIRECTORY_LISTING
3546 const char *list_dir = "no";
3548 const char *list_dir = conn->server->config_options[ENABLE_DIRECTORY_LISTING];
3551 conn->mg_conn.status_code = 207;
3553 // Print properties for the requested resource itself
3555 conn->mg_conn.status_code = 404;
3556 mg_printf(&conn->mg_conn, "%s", "HTTP/1.1 404 Not Found\r\n\r\n");
3557 } else if (S_ISDIR(stp->st_mode) && mg_strcasecmp(list_dir, "yes") != 0) {
3558 conn->mg_conn.status_code = 403;
3559 mg_printf(&conn->mg_conn, "%s",
3560 "HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
3562 ns_send(conn->ns_conn, header, sizeof(header) - 1);
3563 print_props(conn, conn->mg_conn.uri, stp);
3565 if (S_ISDIR(stp->st_mode) &&
3566 (depth == NULL || strcmp(depth, "0") != 0)) {
3567 struct dir_entry *arr = NULL;
3568 int i, num_entries = scan_directory(conn, path, &arr);
3570 for (i = 0; i < num_entries; i++) {
3571 char buf[MAX_PATH_SIZE * 3];
3572 struct dir_entry *de = &arr[i];
3573 mg_url_encode(de->file_name, strlen(de->file_name), buf, sizeof(buf));
3574 print_props(conn, buf, &de->st);
3575 free(de->file_name);
3579 ns_send(conn->ns_conn, footer, sizeof(footer) - 1);
3582 close_local_endpoint(conn);
3585 static void handle_mkcol(struct connection *conn, const char *path) {
3586 int status_code = 500;
3588 if (conn->mg_conn.content_len > 0) {
3590 } else if (!mkdir(path, 0755)) {
3592 } else if (errno == EEXIST) {
3594 } else if (errno == EACCES) {
3596 } else if (errno == ENOENT) {
3599 send_http_error(conn, status_code, NULL);
3602 static int remove_directory(const char *dir) {
3603 char path[MAX_PATH_SIZE];
3608 if ((dirp = opendir(dir)) == NULL) return 0;
3610 while ((dp = readdir(dirp)) != NULL) {
3611 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue;
3612 mg_snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
3614 if (S_ISDIR(st.st_mode)) {
3615 remove_directory(path);
3626 static void handle_delete(struct connection *conn, const char *path) {
3629 if (stat(path, &st) != 0) {
3630 send_http_error(conn, 404, NULL);
3631 } else if (S_ISDIR(st.st_mode)) {
3632 remove_directory(path);
3633 send_http_error(conn, 204, NULL);
3634 } else if (remove(path) == 0) {
3635 send_http_error(conn, 204, NULL);
3637 send_http_error(conn, 423, NULL);
3641 // For a given PUT path, create all intermediate subdirectories
3642 // for given path. Return 0 if the path itself is a directory,
3643 // or -1 on error, 1 if OK.
3644 static int put_dir(const char *path) {
3645 char buf[MAX_PATH_SIZE];
3649 // Create intermediate directories if they do not exist
3650 for (s = p = path + 1; (p = strchr(s, '/')) != NULL; s = ++p) {
3651 if (p - path >= (int) sizeof(buf)) return -1; // Buffer overflow
3652 memcpy(buf, path, p - path);
3653 buf[p - path] = '\0';
3654 if (stat(buf, &st) != 0 && mkdir(buf, 0755) != 0) return -1;
3655 if (p[1] == '\0') return 0; // Path is a directory itself
3661 static void handle_put(struct connection *conn, const char *path) {
3663 const char *range, *cl_hdr = mg_get_header(&conn->mg_conn, "Content-Length");
3667 conn->mg_conn.status_code = !stat(path, &st) ? 200 : 201;
3668 if ((rc = put_dir(path)) == 0) {
3669 mg_printf(&conn->mg_conn, "HTTP/1.1 %d OK\r\n\r\n",
3670 conn->mg_conn.status_code);
3671 close_local_endpoint(conn);
3672 } else if (rc == -1) {
3673 send_http_error(conn, 500, "put_dir: %s", strerror(errno));
3674 } else if (cl_hdr == NULL) {
3675 send_http_error(conn, 411, NULL);
3676 } else if ((conn->endpoint.fd =
3677 open(path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0644)) < 0) {
3678 send_http_error(conn, 500, "open(%s): %s", path, strerror(errno));
3680 DBG(("PUT [%s] %lu", path, (unsigned long) conn->ns_conn->recv_iobuf.len));
3681 conn->endpoint_type = EP_PUT;
3682 ns_set_close_on_exec(conn->endpoint.fd);
3683 range = mg_get_header(&conn->mg_conn, "Content-Range");
3684 conn->cl = to64(cl_hdr);
3686 if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
3687 conn->mg_conn.status_code = 206;
3688 lseek(conn->endpoint.fd, r1, SEEK_SET);
3689 conn->cl = r2 > r1 ? r2 - r1 + 1: conn->cl - r1;
3691 mg_printf(&conn->mg_conn, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n",
3692 conn->mg_conn.status_code);
3696 static void forward_put_data(struct connection *conn) {
3697 struct iobuf *io = &conn->ns_conn->recv_iobuf;
3698 size_t k = conn->cl < (int64_t) io->len ? conn->cl : (int64_t) io->len; // To write
3699 int n = write(conn->endpoint.fd, io->buf, k); // Write them!
3701 iobuf_remove(io, n);
3704 if (conn->cl <= 0) {
3705 close_local_endpoint(conn);
3708 #endif // MONGOOSE_NO_DAV
3710 static void send_options(struct connection *conn) {
3711 conn->mg_conn.status_code = 200;
3712 mg_printf(&conn->mg_conn, "%s",
3713 "HTTP/1.1 200 OK\r\nAllow: GET, POST, HEAD, CONNECT, PUT, "
3714 "DELETE, OPTIONS, PROPFIND, MKCOL\r\nDAV: 1\r\n\r\n");
3715 close_local_endpoint(conn);
3718 #ifndef MONGOOSE_NO_AUTH
3719 void mg_send_digest_auth_request(struct mg_connection *c) {
3720 struct connection *conn = MG_CONN_2_CONN(c);
3721 c->status_code = 401;
3723 "HTTP/1.1 401 Unauthorized\r\n"
3724 "WWW-Authenticate: Digest qop=\"auth\", "
3725 "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
3726 conn->server->config_options[AUTH_DOMAIN],
3727 (unsigned long) time(NULL));
3728 close_local_endpoint(conn);
3731 // Use the global passwords file, if specified by auth_gpass option,
3732 // or search for .htpasswd in the requested directory.
3733 static FILE *open_auth_file(struct connection *conn, const char *path,
3735 char name[MAX_PATH_SIZE];
3736 const char *p, *gpass = conn->server->config_options[GLOBAL_AUTH_FILE];
3739 if (gpass != NULL) {
3740 // Use global passwords file
3741 fp = fopen(gpass, "r");
3742 } else if (is_directory) {
3743 mg_snprintf(name, sizeof(name), "%s%c%s", path, '/', PASSWORDS_FILE_NAME);
3744 fp = fopen(name, "r");
3746 // Try to find .htpasswd in requested directory.
3747 if ((p = strrchr(path, '/')) == NULL) p = path;
3748 mg_snprintf(name, sizeof(name), "%.*s%c%s",
3749 (int) (p - path), path, '/', PASSWORDS_FILE_NAME);
3750 fp = fopen(name, "r");
3756 #if !defined(HAVE_MD5) && !defined(MONGOOSE_NO_AUTH)
3757 typedef struct MD5Context {
3760 unsigned char in[64];
3763 static void byteReverse(unsigned char *buf, unsigned longs) {
3766 // Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN
3767 if (is_big_endian()) {
3769 t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
3770 ((unsigned) buf[1] << 8 | buf[0]);
3771 * (uint32_t *) buf = t;
3777 #define F1(x, y, z) (z ^ (x & (y ^ z)))
3778 #define F2(x, y, z) F1(z, x, y)
3779 #define F3(x, y, z) (x ^ y ^ z)
3780 #define F4(x, y, z) (y ^ (x | ~z))
3782 #define MD5STEP(f, w, x, y, z, data, s) \
3783 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
3785 // Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
3786 // initialization constants.
3787 static void MD5Init(MD5_CTX *ctx) {
3788 ctx->buf[0] = 0x67452301;
3789 ctx->buf[1] = 0xefcdab89;
3790 ctx->buf[2] = 0x98badcfe;
3791 ctx->buf[3] = 0x10325476;
3797 static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
3798 register uint32_t a, b, c, d;
3805 MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
3806 MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
3807 MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
3808 MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
3809 MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
3810 MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
3811 MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
3812 MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
3813 MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
3814 MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
3815 MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
3816 MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
3817 MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
3818 MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
3819 MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
3820 MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
3822 MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
3823 MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
3824 MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
3825 MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
3826 MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
3827 MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
3828 MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
3829 MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
3830 MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
3831 MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
3832 MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
3833 MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
3834 MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
3835 MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
3836 MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
3837 MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
3839 MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
3840 MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
3841 MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
3842 MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
3843 MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
3844 MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
3845 MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
3846 MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
3847 MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
3848 MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
3849 MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
3850 MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
3851 MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
3852 MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
3853 MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
3854 MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
3856 MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
3857 MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
3858 MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
3859 MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
3860 MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
3861 MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
3862 MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
3863 MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
3864 MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
3865 MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
3866 MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
3867 MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
3868 MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
3869 MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
3870 MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
3871 MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
3879 static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) {
3883 if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
3885 ctx->bits[1] += len >> 29;
3887 t = (t >> 3) & 0x3f;
3890 unsigned char *p = (unsigned char *) ctx->in + t;
3894 memcpy(p, buf, len);
3898 byteReverse(ctx->in, 16);
3899 MD5Transform(ctx->buf, (uint32_t *) ctx->in);
3905 memcpy(ctx->in, buf, 64);
3906 byteReverse(ctx->in, 16);
3907 MD5Transform(ctx->buf, (uint32_t *) ctx->in);
3912 memcpy(ctx->in, buf, len);
3915 static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) {
3920 count = (ctx->bits[0] >> 3) & 0x3F;
3922 p = ctx->in + count;
3924 count = 64 - 1 - count;
3926 memset(p, 0, count);
3927 byteReverse(ctx->in, 16);
3928 MD5Transform(ctx->buf, (uint32_t *) ctx->in);
3929 memset(ctx->in, 0, 56);
3931 memset(p, 0, count - 8);
3933 byteReverse(ctx->in, 14);
3935 a = (uint32_t *)ctx->in;
3936 a[14] = ctx->bits[0];
3937 a[15] = ctx->bits[1];
3939 MD5Transform(ctx->buf, (uint32_t *) ctx->in);
3940 byteReverse((unsigned char *) ctx->buf, 4);
3941 memcpy(digest, ctx->buf, 16);
3942 memset((char *) ctx, 0, sizeof(*ctx));
3948 // Stringify binary data. Output buffer must be twice as big as input,
3949 // because each byte takes 2 bytes in string representation
3950 static void bin2str(char *to, const unsigned char *p, size_t len) {
3951 static const char *hex = "0123456789abcdef";
3953 for (; len--; p++) {
3954 *to++ = hex[p[0] >> 4];
3955 *to++ = hex[p[0] & 0x0f];
3960 // Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
3961 char *mg_md5(char buf[33], ...) {
3962 unsigned char hash[16];
3970 while ((p = va_arg(ap, const char *)) != NULL) {
3971 MD5Update(&ctx, (const unsigned char *) p, (unsigned) strlen(p));
3975 MD5Final(hash, &ctx);
3976 bin2str(buf, hash, sizeof(hash));
3980 // Check the user's password, return 1 if OK
3981 static int check_password(const char *method, const char *ha1, const char *uri,
3982 const char *nonce, const char *nc, const char *cnonce,
3983 const char *qop, const char *response) {
3984 char ha2[32 + 1], expected_response[32 + 1];
3987 // Check for authentication timeout
3988 if ((unsigned long) time(NULL) - (unsigned long) to64(nonce) > 3600 * 2) {
3993 mg_md5(ha2, method, ":", uri, NULL);
3994 mg_md5(expected_response, ha1, ":", nonce, ":", nc,
3995 ":", cnonce, ":", qop, ":", ha2, NULL);
3997 return mg_strcasecmp(response, expected_response) == 0 ? MG_TRUE : MG_FALSE;
4001 // Authorize against the opened passwords file. Return 1 if authorized.
4002 int mg_authorize_digest(struct mg_connection *c, FILE *fp) {
4003 struct connection *conn = MG_CONN_2_CONN(c);
4005 char line[256], f_user[256], ha1[256], f_domain[256], user[100], nonce[100],
4006 uri[MAX_REQUEST_SIZE], cnonce[100], resp[100], qop[100], nc[100];
4008 if (c == NULL || fp == NULL) return 0;
4009 if ((hdr = mg_get_header(c, "Authorization")) == NULL ||
4010 mg_strncasecmp(hdr, "Digest ", 7) != 0) return 0;
4011 if (!mg_parse_header(hdr, "username", user, sizeof(user))) return 0;
4012 if (!mg_parse_header(hdr, "cnonce", cnonce, sizeof(cnonce))) return 0;
4013 if (!mg_parse_header(hdr, "response", resp, sizeof(resp))) return 0;
4014 if (!mg_parse_header(hdr, "uri", uri, sizeof(uri))) return 0;
4015 if (!mg_parse_header(hdr, "qop", qop, sizeof(qop))) return 0;
4016 if (!mg_parse_header(hdr, "nc", nc, sizeof(nc))) return 0;
4017 if (!mg_parse_header(hdr, "nonce", nonce, sizeof(nonce))) return 0;
4019 while (fgets(line, sizeof(line), fp) != NULL) {
4020 if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) == 3 &&
4021 !strcmp(user, f_user) &&
4022 // NOTE(lsm): due to a bug in MSIE, we do not compare URIs
4023 !strcmp(conn->server->config_options[AUTH_DOMAIN], f_domain))
4024 return check_password(c->request_method, ha1, uri,
4025 nonce, nc, cnonce, qop, resp);
4031 // Return 1 if request is authorised, 0 otherwise.
4032 static int is_authorized(struct connection *conn, const char *path,
4035 int authorized = MG_TRUE;
4037 if ((fp = open_auth_file(conn, path, is_directory)) != NULL) {
4038 authorized = mg_authorize_digest(&conn->mg_conn, fp);
4045 static int is_authorized_for_dav(struct connection *conn) {
4046 const char *auth_file = conn->server->config_options[DAV_AUTH_FILE];
4047 const char *method = conn->mg_conn.request_method;
4049 int authorized = MG_FALSE;
4051 // If dav_auth_file is not set, allow non-authorized PROPFIND
4052 if (method != NULL && !strcmp(method, "PROPFIND") && auth_file == NULL) {
4053 authorized = MG_TRUE;
4054 } else if (auth_file != NULL && (fp = fopen(auth_file, "r")) != NULL) {
4055 authorized = mg_authorize_digest(&conn->mg_conn, fp);
4062 static int is_dav_request(const struct connection *conn) {
4063 const char *s = conn->mg_conn.request_method;
4064 return !strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
4065 !strcmp(s, "MKCOL") || !strcmp(s, "PROPFIND");
4067 #endif // MONGOOSE_NO_AUTH
4069 static int parse_header(const char *str, int str_len, const char *var_name,
4070 char *buf, size_t buf_size) {
4071 int ch = ' ', len = 0, n = strlen(var_name);
4072 const char *p, *end = str + str_len, *s = NULL;
4074 if (buf != NULL && buf_size > 0) buf[0] = '\0';
4076 // Find where variable starts
4077 for (s = str; s != NULL && s + n < end; s++) {
4078 if ((s == str || s[-1] == ' ' || s[-1] == ',') && s[n] == '=' &&
4079 !memcmp(s, var_name, n)) break;
4082 if (s != NULL && &s[n + 1] < end) {
4084 if (*s == '"' || *s == '\'') ch = *s++;
4086 while (p < end && p[0] != ch && p[0] != ',' && len < (int) buf_size) {
4087 if (p[0] == '\\' && p[1] == ch) p++;
4090 if (len >= (int) buf_size || (ch != ' ' && *p != ch)) {
4093 if (len > 0 && s[len - 1] == ',') len--;
4094 if (len > 0 && s[len - 1] == ';') len--;
4102 int mg_parse_header(const char *s, const char *var_name, char *buf,
4104 return parse_header(s, s == NULL ? 0 : strlen(s), var_name, buf, buf_size);
4107 #ifndef MONGOOSE_NO_SSI
4108 static void send_ssi_file(struct mg_connection *, const char *, FILE *, int);
4110 static void send_file_data(struct mg_connection *conn, FILE *fp) {
4111 char buf[IOBUF_SIZE];
4113 while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
4114 mg_write(conn, buf, n);
4118 static void do_ssi_include(struct mg_connection *conn, const char *ssi,
4119 char *tag, int include_level) {
4120 char file_name[IOBUF_SIZE], path[MAX_PATH_SIZE], *p;
4121 char **opts = (MG_CONN_2_CONN(conn))->server->config_options;
4124 // sscanf() is safe here, since send_ssi_file() also uses buffer
4125 // of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
4126 if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
4127 // File name is relative to the webserver root
4128 mg_snprintf(path, sizeof(path), "%s%c%s",
4129 opts[DOCUMENT_ROOT], '/', file_name);
4130 } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
4131 // File name is relative to the webserver working directory
4132 // or it is absolute system path
4133 mg_snprintf(path, sizeof(path), "%s", file_name);
4134 } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
4135 sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
4136 // File name is relative to the currect document
4137 mg_snprintf(path, sizeof(path), "%s", ssi);
4138 if ((p = strrchr(path, '/')) != NULL) {
4141 mg_snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s",
4144 mg_printf(conn, "Bad SSI #include: [%s]", tag);
4148 if ((fp = fopen(path, "rb")) == NULL) {
4149 mg_printf(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",
4150 tag, path, strerror(errno));
4152 ns_set_close_on_exec(fileno(fp));
4153 if (mg_match_prefix(opts[SSI_PATTERN], strlen(opts[SSI_PATTERN]),
4155 send_ssi_file(conn, path, fp, include_level + 1);
4157 send_file_data(conn, fp);
4163 #ifndef MONGOOSE_NO_POPEN
4164 static void do_ssi_exec(struct mg_connection *conn, char *tag) {
4165 char cmd[IOBUF_SIZE];
4168 if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
4169 mg_printf(conn, "Bad SSI #exec: [%s]", tag);
4170 } else if ((fp = popen(cmd, "r")) == NULL) {
4171 mg_printf(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(errno));
4173 send_file_data(conn, fp);
4177 #endif // !MONGOOSE_NO_POPEN
4179 static void send_ssi_file(struct mg_connection *conn, const char *path,
4180 FILE *fp, int include_level) {
4181 char buf[IOBUF_SIZE];
4182 int ch, offset, len, in_ssi_tag;
4184 if (include_level > 10) {
4185 mg_printf(conn, "SSI #include level is too deep (%s)", path);
4189 in_ssi_tag = len = offset = 0;
4190 while ((ch = fgetc(fp)) != EOF) {
4191 if (in_ssi_tag && ch == '>') {
4193 buf[len++] = (char) ch;
4195 assert(len <= (int) sizeof(buf));
4196 if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
4197 // Not an SSI tag, pass it
4198 (void) mg_write(conn, buf, (size_t) len);
4200 if (!memcmp(buf + 5, "include", 7)) {
4201 do_ssi_include(conn, path, buf + 12, include_level);
4202 #if !defined(MONGOOSE_NO_POPEN)
4203 } else if (!memcmp(buf + 5, "exec", 4)) {
4204 do_ssi_exec(conn, buf + 9);
4207 mg_printf(conn, "%s: unknown SSI " "command: \"%s\"", path, buf);
4211 } else if (in_ssi_tag) {
4212 if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
4215 } else if (len == (int) sizeof(buf) - 2) {
4216 mg_printf(conn, "%s: SSI tag is too large", path);
4219 buf[len++] = ch & 0xff;
4220 } else if (ch == '<') {
4223 mg_write(conn, buf, (size_t) len);
4226 buf[len++] = ch & 0xff;
4228 buf[len++] = ch & 0xff;
4229 if (len == (int) sizeof(buf)) {
4230 mg_write(conn, buf, (size_t) len);
4236 // Send the rest of buffered data
4238 mg_write(conn, buf, (size_t) len);
4242 static void handle_ssi_request(struct connection *conn, const char *path) {
4244 struct vec mime_vec;
4246 if ((fp = fopen(path, "rb")) == NULL) {
4247 send_http_error(conn, 500, "fopen(%s): %s", path, strerror(errno));
4249 ns_set_close_on_exec(fileno(fp));
4250 get_mime_type(conn->server, path, &mime_vec);
4251 conn->mg_conn.status_code = 200;
4252 mg_printf(&conn->mg_conn,
4253 "HTTP/1.1 %d OK\r\n"
4254 "Content-Type: %.*s\r\n"
4255 "Connection: close\r\n\r\n",
4256 conn->mg_conn.status_code, (int) mime_vec.len, mime_vec.ptr);
4257 send_ssi_file(&conn->mg_conn, path, fp, 0);
4259 close_local_endpoint(conn);
4264 static void proxy_request(struct ns_connection *pc, struct mg_connection *c) {
4265 int i, sent_close_header = 0;
4267 ns_printf(pc, "%s %s%s%s HTTP/%s\r\n", c->request_method, c->uri,
4268 c->query_string ? "?" : "",
4269 c->query_string ? c->query_string : "",
4271 for (i = 0; i < c->num_headers; i++) {
4272 if (mg_strcasecmp(c->http_headers[i].name, "Connection") == 0) {
4273 // Force connection close, cause we don't parse proxy replies
4274 // therefore we don't know message boundaries
4275 ns_printf(pc, "%s: %s\r\n", "Connection", "close");
4276 sent_close_header = 1;
4278 ns_printf(pc, "%s: %s\r\n", c->http_headers[i].name,
4279 c->http_headers[i].value);
4282 if (!sent_close_header) {
4283 ns_printf(pc, "%s: %s\r\n", "Connection", "close");
4285 ns_printf(pc, "%s", "\r\n");
4286 ns_send(pc, c->content, c->content_len);
4290 #ifdef NS_ENABLE_SSL
4291 int mg_terminate_ssl(struct mg_connection *c, const char *cert) {
4292 static const char ok[] = "HTTP/1.0 200 OK\r\n\r\n";
4293 struct connection *conn = MG_CONN_2_CONN(c);
4296 DBG(("%p MITM", conn));
4297 if ((ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) return 0;
4299 SSL_CTX_use_certificate_file(ctx, cert, 1);
4300 SSL_CTX_use_PrivateKey_file(ctx, cert, 1);
4301 SSL_CTX_use_certificate_chain_file(ctx, cert);
4303 // When clear-text reply is pushed to client, switch to SSL mode.
4304 // TODO(lsm): check for send() failure
4305 send(conn->ns_conn->sock, ok, sizeof(ok) - 1, 0);
4306 //DBG(("%p %lu %d SEND", c, (unsigned long) sizeof(ok) - 1, n));
4307 conn->ns_conn->send_iobuf.len = 0;
4308 conn->endpoint_type = EP_USER; // To keep-alive in close_local_endpoint()
4309 close_local_endpoint(conn); // Clean up current CONNECT request
4310 if ((conn->ns_conn->ssl = SSL_new(ctx)) != NULL) {
4311 SSL_set_fd(conn->ns_conn->ssl, conn->ns_conn->sock);
4318 int mg_forward(struct mg_connection *c, const char *addr) {
4319 static const char ok[] = "HTTP/1.1 200 OK\r\n\r\n";
4320 struct connection *conn = MG_CONN_2_CONN(c);
4321 struct ns_connection *pc;
4323 if ((pc = ns_connect(&conn->server->ns_mgr, addr,
4324 mg_ev_handler, conn)) == NULL) {
4325 conn->ns_conn->flags |= NSF_CLOSE_IMMEDIATELY;
4329 // Interlink two connections
4330 pc->flags |= MG_PROXY_CONN;
4331 conn->endpoint_type = EP_PROXY;
4332 conn->endpoint.nc = pc;
4333 DBG(("%p [%s] [%s] -> %p %p", conn, c->uri, addr, pc, conn->ns_conn->ssl));
4335 if (strcmp(c->request_method, "CONNECT") == 0) {
4336 // For CONNECT request, reply with 200 OK. Tunnel is established.
4337 // TODO(lsm): check for send() failure
4338 (void) send(conn->ns_conn->sock, ok, sizeof(ok) - 1, 0);
4340 // Strip "http://host:port" part from the URI
4341 if (memcmp(c->uri, "http://", 7) == 0) c->uri += 7;
4342 while (*c->uri != '\0' && *c->uri != '/') c->uri++;
4343 proxy_request(pc, c);
4348 static void proxify_connection(struct connection *conn) {
4349 char proto[10], host[500], cert[500], addr[1000];
4350 unsigned short port = 80;
4351 struct mg_connection *c = &conn->mg_conn;
4353 const char *url = c->uri;
4355 proto[0] = host[0] = cert[0] = '\0';
4356 if (sscanf(url, "%499[^: ]:%hu%n", host, &port, &n) != 2 &&
4357 sscanf(url, "%9[a-z]://%499[^: ]:%hu%n", proto, host, &port, &n) != 3 &&
4358 sscanf(url, "%9[a-z]://%499[^/ ]%n", proto, host, &n) != 2) {
4362 snprintf(addr, sizeof(addr), "%s://%s:%hu",
4363 conn->ns_conn->ssl != NULL ? "ssl" : "tcp", host, port);
4364 if (n <= 0 || !mg_forward(c, addr)) {
4365 conn->ns_conn->flags |= NSF_CLOSE_IMMEDIATELY;
4369 #ifndef MONGOOSE_NO_FILESYSTEM
4370 void mg_send_file_internal(struct mg_connection *c, const char *file_name,
4371 file_stat_t *st, int exists,
4372 const char *extra_headers) {
4373 struct connection *conn = MG_CONN_2_CONN(c);
4374 char path[MAX_PATH_SIZE];
4375 const int is_directory = S_ISDIR(st->st_mode);
4376 #ifndef MONGOOSE_NO_CGI
4377 const char *cgi_pat = conn->server->config_options[CGI_PATTERN];
4379 const char *cgi_pat = DEFAULT_CGI_PATTERN;
4381 #ifndef MONGOOSE_NO_DIRECTORY_LISTING
4382 const char *dir_lst = conn->server->config_options[ENABLE_DIRECTORY_LISTING];
4384 const char *dir_lst = "yes";
4387 mg_snprintf(path, sizeof(path), "%s", file_name);
4389 if (!exists || must_hide_file(conn, path)) {
4390 send_http_error(conn, 404, NULL);
4391 } else if (is_directory &&
4392 conn->mg_conn.uri[strlen(conn->mg_conn.uri) - 1] != '/') {
4393 conn->mg_conn.status_code = 301;
4394 mg_printf(&conn->mg_conn, "HTTP/1.1 301 Moved Permanently\r\n"
4395 "Location: %s/\r\n\r\n", conn->mg_conn.uri);
4396 close_local_endpoint(conn);
4397 } else if (is_directory && !find_index_file(conn, path, sizeof(path), st)) {
4398 if (!mg_strcasecmp(dir_lst, "yes")) {
4399 #ifndef MONGOOSE_NO_DIRECTORY_LISTING
4400 send_directory_listing(conn, path);
4402 send_http_error(conn, 501, NULL);
4405 send_http_error(conn, 403, NULL);
4407 } else if (mg_match_prefix(cgi_pat, strlen(cgi_pat), path) > 0) {
4408 #if !defined(MONGOOSE_NO_CGI)
4409 open_cgi_endpoint(conn, path);
4411 send_http_error(conn, 501, NULL);
4412 #endif // !MONGOOSE_NO_CGI
4413 #ifndef MONGOOSE_NO_SSI
4414 } else if (mg_match_prefix(conn->server->config_options[SSI_PATTERN],
4415 strlen(conn->server->config_options[SSI_PATTERN]),
4417 handle_ssi_request(conn, path);
4419 } else if (is_not_modified(conn, st)) {
4420 send_http_error(conn, 304, NULL);
4421 } else if ((conn->endpoint.fd = open(path, O_RDONLY | O_BINARY, 0)) != -1) {
4422 // O_BINARY is required for Windows, otherwise in default text mode
4423 // two bytes \r\n will be read as one.
4424 open_file_endpoint(conn, path, st, extra_headers);
4426 send_http_error(conn, 404, NULL);
4429 void mg_send_file(struct mg_connection *c, const char *file_name,
4430 const char *extra_headers) {
4432 const int exists = stat(file_name, &st) == 0;
4433 mg_send_file_internal(c, file_name, &st, exists, extra_headers);
4435 #endif // !MONGOOSE_NO_FILESYSTEM
4437 static void open_local_endpoint(struct connection *conn, int skip_user) {
4438 #ifndef MONGOOSE_NO_FILESYSTEM
4439 char path[MAX_PATH_SIZE];
4444 // If EP_USER was set in a prev call, reset it
4445 conn->endpoint_type = EP_NONE;
4447 #ifndef MONGOOSE_NO_AUTH
4448 if (conn->server->event_handler && call_user(conn, MG_AUTH) == MG_FALSE) {
4449 mg_send_digest_auth_request(&conn->mg_conn);
4454 // Call URI handler if one is registered for this URI
4455 if (skip_user == 0 && conn->server->event_handler != NULL) {
4456 conn->endpoint_type = EP_USER;
4457 #if MONGOOSE_POST_SIZE_LIMIT > 1
4459 const char *cl = mg_get_header(&conn->mg_conn, "Content-Length");
4460 if ((strcmp(conn->mg_conn.request_method, "POST") == 0 ||
4461 strcmp(conn->mg_conn.request_method, "PUT") == 0) &&
4462 (cl == NULL || to64(cl) > MONGOOSE_POST_SIZE_LIMIT)) {
4463 send_http_error(conn, 500, "POST size > %lu",
4464 (unsigned long) MONGOOSE_POST_SIZE_LIMIT);
4471 if (strcmp(conn->mg_conn.request_method, "CONNECT") == 0 ||
4472 mg_strncasecmp(conn->mg_conn.uri, "http", 4) == 0) {
4473 const char *enp = conn->server->config_options[ENABLE_PROXY];
4474 if (enp == NULL || strcmp(enp, "yes") != 0) {
4475 send_http_error(conn, 405, NULL);
4477 proxify_connection(conn);
4482 if (!strcmp(conn->mg_conn.request_method, "OPTIONS")) {
4487 #ifdef MONGOOSE_NO_FILESYSTEM
4488 send_http_error(conn, 404, NULL);
4490 exists = convert_uri_to_file_name(conn, path, sizeof(path), &st);
4492 if (!strcmp(conn->mg_conn.request_method, "OPTIONS")) {
4494 } else if (conn->server->config_options[DOCUMENT_ROOT] == NULL) {
4495 send_http_error(conn, 404, NULL);
4496 #ifndef MONGOOSE_NO_AUTH
4497 } else if ((!is_dav_request(conn) && !is_authorized(conn, path,
4498 exists && S_ISDIR(st.st_mode))) ||
4499 (is_dav_request(conn) && !is_authorized_for_dav(conn))) {
4500 mg_send_digest_auth_request(&conn->mg_conn);
4501 close_local_endpoint(conn);
4503 #ifndef MONGOOSE_NO_DAV
4504 } else if (must_hide_file(conn, path)) {
4505 send_http_error(conn, 404, NULL);
4506 } else if (!strcmp(conn->mg_conn.request_method, "PROPFIND")) {
4507 handle_propfind(conn, path, &st, exists);
4508 } else if (!strcmp(conn->mg_conn.request_method, "MKCOL")) {
4509 handle_mkcol(conn, path);
4510 } else if (!strcmp(conn->mg_conn.request_method, "DELETE")) {
4511 handle_delete(conn, path);
4512 } else if (!strcmp(conn->mg_conn.request_method, "PUT")) {
4513 handle_put(conn, path);
4516 mg_send_file_internal(&conn->mg_conn, path, &st, exists, NULL);
4518 #endif // MONGOOSE_NO_FILESYSTEM
4521 static void send_continue_if_expected(struct connection *conn) {
4522 static const char expect_response[] = "HTTP/1.1 100 Continue\r\n\r\n";
4523 const char *expect_hdr = mg_get_header(&conn->mg_conn, "Expect");
4525 if (expect_hdr != NULL && !mg_strcasecmp(expect_hdr, "100-continue")) {
4526 ns_send(conn->ns_conn, expect_response, sizeof(expect_response) - 1);
4530 // Conform to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
4531 static int is_valid_uri(const char *uri) {
4533 return uri[0] == '/' ||
4534 strcmp(uri, "*") == 0 || // OPTIONS method can use asterisk URI
4535 mg_strncasecmp(uri, "http", 4) == 0 || // Naive check for the absolute URI
4536 sscanf(uri, "%*[^ :]:%hu", &n) > 0; // CONNECT method can use host:port
4539 static void try_parse(struct connection *conn) {
4540 struct iobuf *io = &conn->ns_conn->recv_iobuf;
4542 if (conn->request_len == 0 &&
4543 (conn->request_len = get_request_len(io->buf, io->len)) > 0) {
4544 // If request is buffered in, remove it from the iobuf. This is because
4545 // iobuf could be reallocated, and pointers in parsed request could
4547 conn->request = (char *) malloc(conn->request_len);
4548 memcpy(conn->request, io->buf, conn->request_len);
4549 //DBG(("%p [%.*s]", conn, conn->request_len, conn->request));
4550 iobuf_remove(io, conn->request_len);
4551 conn->request_len = parse_http_message(conn->request, conn->request_len,
4553 if (conn->request_len > 0) {
4554 const char *cl_hdr = mg_get_header(&conn->mg_conn, "Content-Length");
4555 conn->cl = cl_hdr == NULL ? 0 : to64(cl_hdr);
4556 conn->mg_conn.content_len = (size_t) conn->cl;
4561 static void do_proxy(struct connection *conn) {
4562 if (0 && conn->request_len == 0) {
4564 DBG(("%p parsing -> %d", conn, conn->request_len));
4565 if (conn->request_len > 0 && call_user(conn, MG_REQUEST) == MG_FALSE) {
4566 proxy_request(conn->endpoint.nc, &conn->mg_conn);
4567 } else if (conn->request_len < 0) {
4568 ns_forward(conn->ns_conn, conn->endpoint.nc);
4571 DBG(("%p forwarding", conn));
4572 ns_forward(conn->ns_conn, conn->endpoint.nc);
4576 static void on_recv_data(struct connection *conn) {
4577 struct iobuf *io = &conn->ns_conn->recv_iobuf;
4580 if (conn->endpoint_type == EP_PROXY) {
4581 if (conn->endpoint.nc != NULL) do_proxy(conn);
4586 DBG(("%p %d %lu %d", conn, conn->request_len, (unsigned long)io->len,
4587 conn->ns_conn->flags));
4588 if (conn->request_len < 0 ||
4589 (conn->request_len > 0 && !is_valid_uri(conn->mg_conn.uri))) {
4590 send_http_error(conn, 400, NULL);
4591 } else if (conn->request_len == 0 && io->len > MAX_REQUEST_SIZE) {
4592 send_http_error(conn, 413, NULL);
4593 } else if (conn->request_len > 0 &&
4594 strcmp(conn->mg_conn.http_version, "1.0") != 0 &&
4595 strcmp(conn->mg_conn.http_version, "1.1") != 0) {
4596 send_http_error(conn, 505, NULL);
4597 } else if (conn->request_len > 0 && conn->endpoint_type == EP_NONE) {
4598 #ifndef MONGOOSE_NO_WEBSOCKET
4599 send_websocket_handshake_if_requested(&conn->mg_conn);
4601 send_continue_if_expected(conn);
4602 open_local_endpoint(conn, 0);
4605 #ifndef MONGOOSE_NO_CGI
4606 if (conn->endpoint_type == EP_CGI && conn->endpoint.nc != NULL) {
4607 ns_forward(conn->ns_conn, conn->endpoint.nc);
4610 if (conn->endpoint_type == EP_USER) {
4611 conn->mg_conn.content = io->buf;
4612 conn->mg_conn.content_len = io->len;
4613 n = call_user(conn, MG_RECV);
4615 conn->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
4616 } else if ((size_t) n <= io->len) {
4617 iobuf_remove(io, n);
4619 call_request_handler_if_data_is_buffered(conn);
4621 #ifndef MONGOOSE_NO_DAV
4622 if (conn->endpoint_type == EP_PUT && io->len > 0) {
4623 forward_put_data(conn);
4628 static void call_http_client_handler(struct connection *conn) {
4629 //conn->mg_conn.status_code = code;
4630 // For responses without Content-Lengh, use the whole buffer
4631 if (conn->cl == 0) {
4632 conn->mg_conn.content_len = conn->ns_conn->recv_iobuf.len;
4634 conn->mg_conn.content = conn->ns_conn->recv_iobuf.buf;
4635 if (call_user(conn, MG_REPLY) == MG_FALSE) {
4636 conn->ns_conn->flags |= NSF_CLOSE_IMMEDIATELY;
4638 iobuf_remove(&conn->ns_conn->recv_iobuf, conn->mg_conn.content_len);
4639 conn->mg_conn.status_code = 0;
4640 conn->cl = conn->num_bytes_recv = conn->request_len = 0;
4641 free(conn->request);
4642 conn->request = NULL;
4645 static void process_response(struct connection *conn) {
4646 struct iobuf *io = &conn->ns_conn->recv_iobuf;
4649 DBG(("%p %d %lu", conn, conn->request_len, (unsigned long)io->len));
4650 if (conn->request_len < 0 ||
4651 (conn->request_len == 0 && io->len > MAX_REQUEST_SIZE)) {
4652 call_http_client_handler(conn);
4653 } else if ((int64_t) io->len >= conn->cl) {
4654 call_http_client_handler(conn);
4658 struct mg_connection *mg_connect(struct mg_server *server, const char *addr) {
4659 struct ns_connection *nsconn;
4660 struct connection *conn;
4662 nsconn = ns_connect(&server->ns_mgr, addr, mg_ev_handler, NULL);
4663 if (nsconn == NULL) return 0;
4665 if ((conn = (struct connection *) calloc(1, sizeof(*conn))) == NULL) {
4666 nsconn->flags |= NSF_CLOSE_IMMEDIATELY;
4670 // Interlink two structs
4671 conn->ns_conn = nsconn;
4672 nsconn->user_data = conn;
4674 conn->server = server;
4675 conn->endpoint_type = EP_CLIENT;
4676 //conn->handler = handler;
4677 conn->mg_conn.server_param = server->ns_mgr.user_data;
4678 conn->ns_conn->flags = NSF_CONNECTING;
4680 return &conn->mg_conn;
4683 #ifndef MONGOOSE_NO_LOGGING
4684 static void log_header(const struct mg_connection *conn, const char *header,
4686 const char *header_value;
4688 if ((header_value = mg_get_header(conn, header)) == NULL) {
4689 (void) fprintf(fp, "%s", " -");
4691 (void) fprintf(fp, " \"%s\"", header_value);
4695 static void log_access(const struct connection *conn, const char *path) {
4696 const struct mg_connection *c = &conn->mg_conn;
4697 FILE *fp = (path == NULL) ? NULL : fopen(path, "a+");
4698 char date[64], user[100];
4701 if (fp == NULL) return;
4703 strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", localtime(&now));
4706 mg_parse_header(mg_get_header(&conn->mg_conn, "Authorization"), "username",
4707 user, sizeof(user));
4708 fprintf(fp, "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d 0",
4709 c->remote_ip, user[0] == '\0' ? "-" : user, date,
4710 c->request_method ? c->request_method : "-",
4711 c->uri ? c->uri : "-", c->query_string ? "?" : "",
4712 c->query_string ? c->query_string : "",
4713 c->http_version, c->status_code);
4714 log_header(c, "Referer", fp);
4715 log_header(c, "User-Agent", fp);
4724 static void close_local_endpoint(struct connection *conn) {
4725 struct mg_connection *c = &conn->mg_conn;
4726 // Must be done before free()
4727 int keep_alive = should_keep_alive(&conn->mg_conn) &&
4728 (conn->endpoint_type == EP_FILE || conn->endpoint_type == EP_USER);
4729 DBG(("%p %d %d %d", conn, conn->endpoint_type, keep_alive,
4730 conn->ns_conn->flags));
4732 switch (conn->endpoint_type) {
4735 close(conn->endpoint.fd);
4739 if (conn->endpoint.nc != NULL) {
4740 DBG(("%p %p %p :-)", conn, conn->ns_conn, conn->endpoint.nc));
4741 conn->endpoint.nc->flags |= NSF_CLOSE_IMMEDIATELY;
4742 conn->endpoint.nc->user_data = NULL;
4748 #ifndef MONGOOSE_NO_LOGGING
4749 if (c->status_code > 0 && conn->endpoint_type != EP_CLIENT &&
4750 c->status_code != 400) {
4751 log_access(conn, conn->server->config_options[ACCESS_LOG_FILE]);
4755 // Gobble possible POST data sent to the URI handler
4756 iobuf_free(&conn->ns_conn->recv_iobuf);
4757 free(conn->request);
4758 free(conn->path_info);
4759 conn->endpoint.nc = NULL;
4760 conn->request = conn->path_info = NULL;
4762 conn->endpoint_type = EP_NONE;
4763 conn->cl = conn->num_bytes_recv = conn->request_len = 0;
4764 conn->ns_conn->flags &= ~(NSF_FINISHED_SENDING_DATA |
4765 NSF_BUFFER_BUT_DONT_SEND | NSF_CLOSE_IMMEDIATELY |
4766 MG_HEADERS_SENT | MG_LONG_RUNNING);
4768 // Do not memset() the whole structure, as some of the fields
4769 // (IP addresses & ports, server_param) must survive. Nullify the rest.
4770 c->request_method = c->uri = c->http_version = c->query_string = NULL;
4771 c->num_headers = c->status_code = c->is_websocket = c->content_len = 0;
4772 c->connection_param = c->callback_param = NULL;
4775 on_recv_data(conn); // Can call us recursively if pipelining is used
4777 conn->ns_conn->flags |= conn->ns_conn->send_iobuf.len == 0 ?
4778 NSF_CLOSE_IMMEDIATELY : NSF_FINISHED_SENDING_DATA;
4782 static void transfer_file_data(struct connection *conn) {
4783 char buf[IOBUF_SIZE];
4786 // If output buffer is too big, don't send anything. Wait until
4787 // mongoose drains already buffered data to the client.
4788 if (conn->ns_conn->send_iobuf.len > sizeof(buf) * 2) return;
4791 n = read(conn->endpoint.fd, buf, conn->cl < (int64_t) sizeof(buf) ?
4792 (int) conn->cl : (int) sizeof(buf));
4795 close_local_endpoint(conn);
4798 ns_send(conn->ns_conn, buf, n);
4799 if (conn->cl <= 0) {
4800 close_local_endpoint(conn);
4805 int mg_poll_server(struct mg_server *server, int milliseconds) {
4806 return ns_mgr_poll(&server->ns_mgr, milliseconds);
4809 void mg_destroy_server(struct mg_server **server) {
4810 if (server != NULL && *server != NULL) {
4811 struct mg_server *s = *server;
4814 ns_mgr_free(&s->ns_mgr);
4815 for (i = 0; i < (int) ARRAY_SIZE(s->config_options); i++) {
4816 free(s->config_options[i]); // It is OK to free(NULL)
4823 struct mg_connection *mg_next(struct mg_server *s, struct mg_connection *c) {
4824 struct ns_connection *nc = ns_next(&s->ns_mgr, c == NULL ? NULL :
4825 MG_CONN_2_CONN(c)->ns_conn);
4826 if (nc != NULL && nc->user_data != NULL) {
4827 return & ((struct connection *) nc->user_data)->mg_conn;
4833 static int get_var(const char *data, size_t data_len, const char *name,
4834 char *dst, size_t dst_len) {
4835 const char *p, *e, *s;
4839 if (dst == NULL || dst_len == 0) {
4841 } else if (data == NULL || name == NULL || data_len == 0) {
4845 name_len = strlen(name);
4846 e = data + data_len;
4850 // data is "var1=val1&var2=val2...". Find variable first
4851 for (p = data; p + name_len < e; p++) {
4852 if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
4853 !mg_strncasecmp(name, p, name_len)) {
4855 // Point p to variable value
4858 // Point s to the end of the value
4859 s = (const char *) memchr(p, '&', (size_t)(e - p));
4865 // Decode variable into destination buffer
4866 len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
4868 // Redirect error code from -1 to -2 (destination buffer too small).
4880 int mg_get_var(const struct mg_connection *conn, const char *name,
4881 char *dst, size_t dst_len) {
4882 int len = get_var(conn->query_string, conn->query_string == NULL ? 0 :
4883 strlen(conn->query_string), name, dst, dst_len);
4885 len = get_var(conn->content, conn->content_len, name, dst, dst_len);
4890 static int get_line_len(const char *buf, int buf_len) {
4892 while (len < buf_len && buf[len] != '\n') len++;
4893 return buf[len] == '\n' ? len + 1: -1;
4896 int mg_parse_multipart(const char *buf, int buf_len,
4897 char *var_name, int var_name_len,
4898 char *file_name, int file_name_len,
4899 const char **data, int *data_len) {
4900 static const char cd[] = "Content-Disposition: ";
4901 //struct mg_connection c;
4902 int hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
4905 if (buf == NULL || buf_len <= 0) return 0;
4906 if ((hl = get_request_len(buf, buf_len)) <= 0) return 0;
4907 if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
4909 // Get boundary length
4910 bl = get_line_len(buf, buf_len);
4912 // Loop through headers, fetch variable name and file name
4913 var_name[0] = file_name[0] = '\0';
4914 for (n = bl; (ll = get_line_len(buf + n, hl - n)) > 0; n += ll) {
4915 if (mg_strncasecmp(cd, buf + n, cdl) == 0) {
4916 parse_header(buf + n + cdl, ll - (cdl + 2), "name",
4917 var_name, var_name_len);
4918 parse_header(buf + n + cdl, ll - (cdl + 2), "filename",
4919 file_name, file_name_len);
4923 // Scan body, search for terminating boundary
4924 for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
4925 if (buf[pos] == '-' && !memcmp(buf, &buf[pos], bl - 2)) {
4926 if (data_len != NULL) *data_len = (pos - 2) - hl;
4927 if (data != NULL) *data = buf + hl;
4935 const char **mg_get_valid_option_names(void) {
4936 return static_config_options;
4939 void mg_copy_listeners(struct mg_server *s, struct mg_server *to) {
4940 struct ns_connection *c;
4941 for (c = ns_next(&s->ns_mgr, NULL); c != NULL; c = ns_next(&s->ns_mgr, c)) {
4942 struct ns_connection *tmp;
4943 if ((c->flags & NSF_LISTENING) &&
4944 (tmp = (struct ns_connection *) malloc(sizeof(*tmp))) != NULL) {
4945 memcpy(tmp, c, sizeof(*tmp));
4946 tmp->mgr = &to->ns_mgr;
4947 ns_add_conn(tmp->mgr, tmp);
4952 static int get_option_index(const char *name) {
4955 for (i = 0; static_config_options[i * 2] != NULL; i++) {
4956 if (strcmp(static_config_options[i * 2], name) == 0) {
4963 static void set_default_option_values(char **opts) {
4964 const char *value, **all_opts = mg_get_valid_option_names();
4967 for (i = 0; all_opts[i * 2] != NULL; i++) {
4968 value = all_opts[i * 2 + 1];
4969 if (opts[i] == NULL && value != NULL) {
4970 opts[i] = mg_strdup(value);
4975 const char *mg_set_option(struct mg_server *server, const char *name,
4976 const char *value) {
4977 int ind = get_option_index(name);
4978 const char *error_msg = NULL;
4981 if (ind < 0) return "No such option";
4982 v = &server->config_options[ind];
4984 // Return success immediately if setting to the same value
4985 if ((*v == NULL && value == NULL) ||
4986 (value != NULL && *v != NULL && !strcmp(value, *v))) {
4995 if (value == NULL || value[0] == '\0') return NULL;
4997 *v = mg_strdup(value);
4998 DBG(("%s [%s]", name, *v));
5000 if (ind == LISTENING_PORT) {
5002 while ((value = next_option(value, &vec, NULL)) != NULL) {
5003 struct ns_connection *c = ns_bind(&server->ns_mgr, vec.ptr,
5004 mg_ev_handler, NULL);
5006 error_msg = "Cannot bind to port";
5010 ns_sock_to_str(c->sock, buf, sizeof(buf), 2);
5012 *v = mg_strdup(buf);
5015 #ifndef MONGOOSE_NO_FILESYSTEM
5016 } else if (ind == HEXDUMP_FILE) {
5017 server->ns_mgr.hexdump_file = *v;
5020 } else if (ind == RUN_AS_USER) {
5022 if ((pw = getpwnam(value)) == NULL) {
5023 error_msg = "Unknown user";
5024 } else if (setgid(pw->pw_gid) != 0) {
5025 error_msg = "setgid() failed";
5026 } else if (setuid(pw->pw_uid) != 0) {
5027 error_msg = "setuid() failed";
5035 static void set_ips(struct ns_connection *nc, int is_rem) {
5036 struct connection *conn = (struct connection *) nc->user_data;
5037 struct mg_connection *c = &conn->mg_conn;
5040 ns_sock_to_str(nc->sock, buf, sizeof(buf), is_rem ? 7 : 3);
5041 sscanf(buf, "%47[^:]:%hu",
5042 is_rem ? c->remote_ip : c->local_ip,
5043 is_rem ? &c->remote_port : &c->local_port);
5044 //DBG(("%p %s %s", conn, is_rem ? "rem" : "loc", buf));
5047 static void on_accept(struct ns_connection *nc, union socket_address *sa) {
5048 struct mg_server *server = (struct mg_server *) nc->mgr;
5049 struct connection *conn;
5051 if (!check_acl(server->config_options[ACCESS_CONTROL_LIST],
5052 ntohl(* (uint32_t *) &sa->sin.sin_addr)) ||
5053 (conn = (struct connection *) calloc(1, sizeof(*conn))) == NULL) {
5054 nc->flags |= NSF_CLOSE_IMMEDIATELY;
5056 // Circularly link two connection structures
5057 nc->user_data = conn;
5060 // Initialize the rest of connection attributes
5061 conn->server = server;
5062 conn->mg_conn.server_param = nc->mgr->user_data;
5068 static void process_udp(struct ns_connection *nc) {
5069 struct iobuf *io = &nc->recv_iobuf;
5070 struct connection conn;
5072 memset(&conn, 0, sizeof(conn));
5074 conn.server = (struct mg_server *) nc->mgr;
5075 conn.request_len = parse_http_message(io->buf, io->len, &conn.mg_conn);
5076 on_recv_data(&conn);
5077 //ns_printf(nc, "%s", "HTTP/1.0 200 OK\r\n\r\n");
5080 static void mg_ev_handler(struct ns_connection *nc, int ev, void *p) {
5081 struct connection *conn = (struct connection *) nc->user_data;
5083 // Send NS event to the handler. Note that call_user won't send an event
5084 // if conn == NULL. Therefore, repeat this for NS_ACCEPT event as well.
5085 #ifdef MONGOOSE_SEND_NS_EVENTS
5087 struct connection *conn = (struct connection *) nc->user_data;
5088 void *param[2] = { nc, p };
5089 if (conn != NULL) conn->mg_conn.callback_param = param;
5090 call_user(conn, (enum mg_event) ev);
5096 on_accept(nc, (union socket_address *) p);
5097 #ifdef MONGOOSE_SEND_NS_EVENTS
5099 struct connection *conn = (struct connection *) nc->user_data;
5100 void *param[2] = { nc, p };
5101 if (conn != NULL) conn->mg_conn.callback_param = param;
5102 call_user(conn, (enum mg_event) ev);
5108 if (nc->user_data != NULL) {
5112 conn->mg_conn.status_code = * (int *) p;
5113 if (conn->mg_conn.status_code != 0 ||
5114 (!(nc->flags & MG_PROXY_CONN) &&
5115 call_user(conn, MG_CONNECT) == MG_FALSE)) {
5116 nc->flags |= NSF_CLOSE_IMMEDIATELY;
5122 conn->num_bytes_recv += * (int *) p;
5125 if (nc->flags & NSF_UDP) {
5127 } else if (nc->listener != NULL) {
5129 #ifndef MONGOOSE_NO_CGI
5130 } else if (nc->flags & MG_CGI_CONN) {
5133 } else if (nc->flags & MG_PROXY_CONN) {
5135 ns_forward(nc, conn->ns_conn);
5138 process_response(conn);
5146 nc->user_data = NULL;
5147 if (nc->flags & (MG_CGI_CONN | MG_PROXY_CONN)) {
5148 DBG(("%p %p closing cgi/proxy conn", conn, nc));
5149 if (conn && conn->ns_conn) {
5150 conn->ns_conn->flags &= ~NSF_BUFFER_BUT_DONT_SEND;
5151 conn->ns_conn->flags |= conn->ns_conn->send_iobuf.len > 0 ?
5152 NSF_FINISHED_SENDING_DATA : NSF_CLOSE_IMMEDIATELY;
5153 conn->endpoint.nc = NULL;
5155 } else if (conn != NULL) {
5156 DBG(("%p %p %d closing", conn, nc, conn->endpoint_type));
5158 if (conn->endpoint_type == EP_CLIENT && nc->recv_iobuf.len > 0) {
5159 call_http_client_handler(conn);
5162 call_user(conn, MG_CLOSE);
5163 close_local_endpoint(conn);
5164 conn->ns_conn = NULL;
5171 if (call_user(conn, MG_POLL) == MG_TRUE) {
5172 if (conn->ns_conn->flags & MG_HEADERS_SENT) {
5173 write_terminating_chunk(conn);
5175 close_local_endpoint(conn);
5178 if (conn->endpoint_type == EP_FILE) {
5179 transfer_file_data(conn);
5183 // Expire idle connections
5185 time_t current_time = * (time_t *) p;
5187 if (conn != NULL && conn->mg_conn.is_websocket) {
5188 ping_idle_websocket_connection(conn, current_time);
5191 if (nc->listener != NULL &&
5192 nc->last_io_time + MONGOOSE_IDLE_TIMEOUT_SECONDS < current_time) {
5193 mg_ev_handler(nc, NS_CLOSE, NULL);
5194 nc->flags |= NSF_CLOSE_IMMEDIATELY;
5204 static void iter2(struct ns_connection *nc, int ev, void *param) {
5205 mg_handler_t func = NULL;
5206 struct connection *conn = (struct connection *) nc->user_data;
5207 const char *msg = (const char *) param;
5211 //DBG(("%p [%s]", conn, msg));
5212 if (sscanf(msg, "%p %n", &func, &n) && func != NULL) {
5213 conn->mg_conn.callback_param = (void *) (msg + n);
5214 func(&conn->mg_conn, MG_POLL);
5218 void mg_wakeup_server_ex(struct mg_server *server, mg_handler_t cb,
5219 const char *fmt, ...) {
5224 // Encode callback (cb) into a buffer
5225 len = snprintf(buf, sizeof(buf), "%p ", cb);
5227 len += vsnprintf(buf + len, sizeof(buf) - len, fmt, ap);
5230 // "len + 1" is to include terminating \0 in the message
5231 ns_broadcast(&server->ns_mgr, iter2, buf, len + 1);
5234 void mg_wakeup_server(struct mg_server *server) {
5235 ns_broadcast(&server->ns_mgr, NULL, (void *) "", 0);
5238 const char *mg_get_option(const struct mg_server *server, const char *name) {
5239 const char **opts = (const char **) server->config_options;
5240 int i = get_option_index(name);
5241 return i == -1 ? NULL : opts[i] == NULL ? "" : opts[i];
5244 struct mg_server *mg_create_server(void *server_data, mg_handler_t handler) {
5245 struct mg_server *server = (struct mg_server *) calloc(1, sizeof(*server));
5246 ns_mgr_init(&server->ns_mgr, server_data);
5247 set_default_option_values(server->config_options);
5248 server->event_handler = handler;