]> git.mxchange.org Git - flightgear.git/blob - 3rdparty/mongoose/mongoose.c
Pull in latest mongoose HEAD
[flightgear.git] / 3rdparty / mongoose / mongoose.c
1 // Copyright (c) 2004-2013 Sergey Lyubka <valenok@gmail.com>
2 // Copyright (c) 2013-2014 Cesanta Software Limited
3 // All rights reserved
4 //
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/>.
9 //
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.
14 //
15 // Alternatively, you can license this library under a commercial
16 // license, as set out in <http://cesanta.com/>.
17
18 #ifdef NOEMBED_NET_SKELETON
19 #include "net_skeleton.h"
20 #else
21 // net_skeleton start
22 // Copyright (c) 2014 Cesanta Software Limited
23 // All rights reserved
24 //
25 // This software is dual-licensed: you can redistribute it and/or modify
26 // it under the terms of the GNU General Public License version 2 as
27 // published by the Free Software Foundation. For the terms of this
28 // license, see <http://www.gnu.org/licenses/>.
29 //
30 // You are free to use this software under the terms of the GNU General
31 // Public License, but WITHOUT ANY WARRANTY; without even the implied
32 // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
33 // See the GNU General Public License for more details.
34 //
35 // Alternatively, you can license this software under a commercial
36 // license, as set out in <http://cesanta.com/>.
37
38 #ifndef NS_SKELETON_HEADER_INCLUDED
39 #define NS_SKELETON_HEADER_INCLUDED
40
41 #define NS_SKELETON_VERSION "2.1.0"
42
43 #undef UNICODE                  // Use ANSI WinAPI functions
44 #undef _UNICODE                 // Use multibyte encoding on Windows
45 #define _MBCS                   // Use multibyte encoding on Windows
46 #define _INTEGRAL_MAX_BITS 64   // Enable _stati64() on Windows
47 #ifndef _CRT_SECURE_NO_WARNINGS
48 #define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005+
49 #endif
50 #undef WIN32_LEAN_AND_MEAN      // Let windows.h always include winsock2.h
51 #ifdef __Linux__
52 #define _XOPEN_SOURCE 600       // For flockfile() on Linux
53 #endif
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
58 #endif
59 #define _FILE_OFFSET_BITS 64    // Enable 64-bit file offsets
60
61 #ifdef _MSC_VER
62 #pragma warning (disable : 4127)  // FD_SET() emits warning, disable it
63 #pragma warning (disable : 4204)  // missing c99 support
64 #endif
65
66 #if defined(_WIN32) && !defined(MONGOOSE_NO_CGI)
67 #define MONGOOSE_ENABLE_THREADS   /* Windows uses stdio threads for CGI */
68 #endif
69
70 #ifndef MONGOOSE_ENABLE_THREADS
71 #define NS_DISABLE_THREADS
72 #endif
73
74 #ifdef __OS2__
75 #define _MMAP_DECLARED          // Prevent dummy mmap() declaration in stdio.h
76 #endif
77
78 #include <sys/types.h>
79 #include <sys/stat.h>
80 #include <assert.h>
81 #include <ctype.h>
82 #include <errno.h>
83 #include <fcntl.h>
84 #include <stdarg.h>
85 #include <stddef.h>
86 #include <stdio.h>
87 #include <stdlib.h>
88 #include <string.h>
89 #include <time.h>
90 #include <signal.h>
91
92 #ifdef _WIN32
93 #ifdef _MSC_VER
94 #pragma comment(lib, "ws2_32.lib")    // Linking with winsock library
95 #include <BaseTsd.h>
96 typedef SSIZE_T ssize_t;
97 #endif
98 #ifndef FD_SETSIZE
99 #define FD_SETSIZE 1024
100 #endif
101 #include <winsock2.h>
102 #include <ws2tcpip.h>
103 #include <windows.h>
104 #include <process.h>
105 #ifndef EINPROGRESS
106 #define EINPROGRESS WSAEINPROGRESS
107 #endif
108 #ifndef EWOULDBLOCK
109 #define EWOULDBLOCK WSAEWOULDBLOCK
110 #endif
111 #ifndef __func__
112 #define STRX(x) #x
113 #define STR(x) STRX(x)
114 #define __func__ __FILE__ ":" STR(__LINE__)
115 #endif
116 #ifndef va_copy
117 #define va_copy(x,y) x = y
118 #endif // MINGW #defines va_copy
119 #define snprintf _snprintf
120 #define vsnprintf _vsnprintf
121 #define sleep(x) Sleep((x) * 1000)
122 #define to64(x) _atoi64(x)
123 typedef int socklen_t;
124 typedef unsigned char uint8_t;
125 typedef unsigned int uint32_t;
126 typedef unsigned short uint16_t;
127 typedef unsigned __int64 uint64_t;
128 typedef __int64   int64_t;
129 typedef SOCKET sock_t;
130 typedef struct _stati64 ns_stat_t;
131 #ifndef S_ISDIR
132 #define S_ISDIR(x) ((x) & _S_IFDIR)
133 #endif
134 #else
135 #include <errno.h>
136 #include <fcntl.h>
137 #include <netdb.h>
138 #include <pthread.h>
139 #include <stdarg.h>
140 #include <unistd.h>
141 #include <arpa/inet.h>  // For inet_pton() when NS_ENABLE_IPV6 is defined
142 #include <netinet/in.h>
143 #include <sys/socket.h>
144 #include <sys/select.h>
145 #define closesocket(x) close(x)
146 #ifndef __OS2__
147 #define __cdecl
148 #else
149 #include <sys/time.h>
150 typedef int socklen_t;
151 #endif
152 #define INVALID_SOCKET (-1)
153 #define to64(x) strtoll(x, NULL, 10)
154 typedef int sock_t;
155 typedef struct stat ns_stat_t;
156 #endif
157
158 #ifdef NS_ENABLE_DEBUG
159 #define DBG(x) do { printf("%-20s ", __func__); printf x; putchar('\n'); \
160   fflush(stdout); } while(0)
161 #else
162 #define DBG(x)
163 #endif
164
165 #ifndef ARRAY_SIZE
166 #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
167 #endif
168
169 #ifdef NS_ENABLE_SSL
170 #ifdef __APPLE__
171 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
172 #endif
173 #include <openssl/ssl.h>
174 #else
175 typedef void *SSL;
176 typedef void *SSL_CTX;
177 #endif
178
179 #ifdef __cplusplus
180 extern "C" {
181 #endif // __cplusplus
182
183 union socket_address {
184   struct sockaddr sa;
185   struct sockaddr_in sin;
186 #ifdef NS_ENABLE_IPV6
187   struct sockaddr_in6 sin6;
188 #else
189   struct sockaddr sin6;
190 #endif
191 };
192
193 // Describes chunk of memory
194 struct ns_str {
195   const char *p;
196   size_t len;
197 };
198
199 // IO buffers interface
200 struct iobuf {
201   char *buf;
202   size_t len;
203   size_t size;
204 };
205
206 void iobuf_init(struct iobuf *, size_t initial_size);
207 void iobuf_free(struct iobuf *);
208 size_t iobuf_append(struct iobuf *, const void *data, size_t data_size);
209 void iobuf_remove(struct iobuf *, size_t data_size);
210 void iobuf_resize(struct iobuf *, size_t new_size);
211
212 // Callback function (event handler) prototype, must be defined by user.
213 // Net skeleton will call event handler, passing events defined above.
214 struct ns_connection;
215 typedef void (*ns_callback_t)(struct ns_connection *, int event_num, void *evp);
216
217 // Events. Meaning of event parameter (evp) is given in the comment.
218 #define NS_POLL    0  // Sent to each connection on each call to ns_mgr_poll()
219 #define NS_ACCEPT  1  // New connection accept()-ed. union socket_address *addr
220 #define NS_CONNECT 2  // connect() succeeded or failed. int *success_status
221 #define NS_RECV    3  // Data has benn received. int *num_bytes
222 #define NS_SEND    4  // Data has been written to a socket. int *num_bytes
223 #define NS_CLOSE   5  // Connection is closed. NULL
224
225
226 struct ns_mgr {
227   struct ns_connection *active_connections;
228   const char *hexdump_file;         // Debug hexdump file path
229   sock_t ctl[2];                    // Socketpair for mg_wakeup()
230   void *user_data;                  // User data
231 };
232
233
234 struct ns_connection {
235   struct ns_connection *next, *prev;  // ns_mgr::active_connections linkage
236   struct ns_connection *listener;     // Set only for accept()-ed connections
237   struct ns_mgr *mgr;
238
239   sock_t sock;                // Socket
240   union socket_address sa;    // Peer address
241   size_t recv_iobuf_limit; /* Max size of recv buffer */
242   struct iobuf recv_iobuf;    // Received data
243   struct iobuf send_iobuf;    // Data scheduled for sending
244   SSL *ssl;
245   SSL_CTX *ssl_ctx;
246   void *user_data;            // User-specific data
247   void *proto_data;           // Application protocol-specific data
248   time_t last_io_time;        // Timestamp of the last socket IO
249   ns_callback_t callback;     // Event handler function
250
251   unsigned int flags;
252 #define NSF_FINISHED_SENDING_DATA   (1 << 0)
253 #define NSF_BUFFER_BUT_DONT_SEND    (1 << 1)
254 #define NSF_SSL_HANDSHAKE_DONE      (1 << 2)
255 #define NSF_CONNECTING              (1 << 3)
256 #define NSF_CLOSE_IMMEDIATELY       (1 << 4)
257 #define NSF_WANT_READ               (1 << 5)
258 #define NSF_WANT_WRITE              (1 << 6)
259 #define NSF_LISTENING               (1 << 7)
260 #define NSF_UDP                     (1 << 8)
261
262 #define NSF_USER_1                  (1 << 20)
263 #define NSF_USER_2                  (1 << 21)
264 #define NSF_USER_3                  (1 << 22)
265 #define NSF_USER_4                  (1 << 23)
266 #define NSF_USER_5                  (1 << 24)
267 #define NSF_USER_6                  (1 << 25)
268 };
269
270 void ns_mgr_init(struct ns_mgr *, void *user_data);
271 void ns_mgr_free(struct ns_mgr *);
272 time_t ns_mgr_poll(struct ns_mgr *, int milli);
273 void ns_broadcast(struct ns_mgr *, ns_callback_t, void *, size_t);
274
275 struct ns_connection *ns_next(struct ns_mgr *, struct ns_connection *);
276 struct ns_connection *ns_add_sock(struct ns_mgr *, sock_t,
277                                   ns_callback_t, void *);
278 struct ns_connection *ns_bind(struct ns_mgr *, const char *,
279                               ns_callback_t, void *);
280 struct ns_connection *ns_connect(struct ns_mgr *, const char *,
281                                  ns_callback_t, void *);
282
283 int ns_send(struct ns_connection *, const void *buf, size_t len);
284 int ns_printf(struct ns_connection *, const char *fmt, ...);
285 int ns_vprintf(struct ns_connection *, const char *fmt, va_list ap);
286
287 // Utility functions
288 void *ns_start_thread(void *(*f)(void *), void *p);
289 int ns_socketpair(sock_t [2]);
290 int ns_socketpair2(sock_t [2], int sock_type);  // SOCK_STREAM or SOCK_DGRAM
291 void ns_set_close_on_exec(sock_t);
292 void ns_sock_to_str(sock_t sock, char *buf, size_t len, int flags);
293 int ns_hexdump(const void *buf, int len, char *dst, int dst_len);
294 int ns_avprintf(char **buf, size_t size, const char *fmt, va_list ap);
295 int ns_resolve(const char *domain_name, char *ip_addr_buf, size_t buf_len);
296
297 #ifdef __cplusplus
298 }
299 #endif // __cplusplus
300
301 #endif // NS_SKELETON_HEADER_INCLUDED
302 // Copyright (c) 2014 Cesanta Software Limited
303 // All rights reserved
304 //
305 // This software is dual-licensed: you can redistribute it and/or modify
306 // it under the terms of the GNU General Public License version 2 as
307 // published by the Free Software Foundation. For the terms of this
308 // license, see <http://www.gnu.org/licenses/>.
309 //
310 // You are free to use this software under the terms of the GNU General
311 // Public License, but WITHOUT ANY WARRANTY; without even the implied
312 // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
313 // See the GNU General Public License for more details.
314 //
315 // Alternatively, you can license this software under a commercial
316 // license, as set out in <http://cesanta.com/>.
317 //
318 // $Date: 2014-09-28 05:04:41 UTC $
319
320
321 #ifndef NS_MALLOC
322 #define NS_MALLOC malloc
323 #endif
324
325 #ifndef NS_REALLOC
326 #define NS_REALLOC realloc
327 #endif
328
329 #ifndef NS_FREE
330 #define NS_FREE free
331 #endif
332
333 #ifndef NS_CALLOC
334 #define NS_CALLOC calloc
335 #endif
336
337 #define NS_CTL_MSG_MESSAGE_SIZE     (8 * 1024)
338 #define NS_READ_BUFFER_SIZE         2048
339 #define NS_UDP_RECEIVE_BUFFER_SIZE  2000
340 #define NS_VPRINTF_BUFFER_SIZE      500
341
342 struct ctl_msg {
343   ns_callback_t callback;
344   char message[NS_CTL_MSG_MESSAGE_SIZE];
345 };
346
347 void iobuf_resize(struct iobuf *io, size_t new_size) {
348   char *p;
349   if ((new_size > io->size || (new_size < io->size && new_size >= io->len)) &&
350       (p = (char *) NS_REALLOC(io->buf, new_size)) != NULL) {
351     io->size = new_size;
352     io->buf = p;
353   }
354 }
355
356 void iobuf_init(struct iobuf *iobuf, size_t initial_size) {
357   iobuf->len = iobuf->size = 0;
358   iobuf->buf = NULL;
359   iobuf_resize(iobuf, initial_size);
360 }
361
362 void iobuf_free(struct iobuf *iobuf) {
363   if (iobuf != NULL) {
364     if (iobuf->buf != NULL) NS_FREE(iobuf->buf);
365     iobuf_init(iobuf, 0);
366   }
367 }
368
369 size_t iobuf_append(struct iobuf *io, const void *buf, size_t len) {
370   char *p = NULL;
371
372   assert(io != NULL);
373   assert(io->len <= io->size);
374
375   /* check overflow */
376   if (len > ~(size_t)0 - (size_t)(io->buf + io->len)) {
377     return 0;
378   }
379
380   if (len <= 0) {
381   } else if (io->len + len <= io->size) {
382     memcpy(io->buf + io->len, buf, len);
383     io->len += len;
384   } else if ((p = (char *) NS_REALLOC(io->buf, io->len + len)) != NULL) {
385     io->buf = p;
386     memcpy(io->buf + io->len, buf, len);
387     io->len += len;
388     io->size = io->len;
389   } else {
390     len = 0;
391   }
392
393   return len;
394 }
395
396 void iobuf_remove(struct iobuf *io, size_t n) {
397   if (n > 0 && n <= io->len) {
398     memmove(io->buf, io->buf + n, io->len - n);
399     io->len -= n;
400   }
401 }
402
403 static size_t ns_out(struct ns_connection *nc, const void *buf, size_t len) {
404   if (nc->flags & NSF_UDP) {
405     long n = sendto(nc->sock, (const char *) buf, len, 0, &nc->sa.sa,
406                     sizeof(nc->sa.sin));
407     DBG(("%p %d send %ld (%d %s)", nc, nc->sock, n, errno, strerror(errno)));
408     return n < 0 ? 0 : n;
409   } else {
410     return iobuf_append(&nc->send_iobuf, buf, len);
411   }
412 }
413
414 #ifndef NS_DISABLE_THREADS
415 void *ns_start_thread(void *(*f)(void *), void *p) {
416 #ifdef _WIN32
417   return (void *) _beginthread((void (__cdecl *)(void *)) f, 0, p);
418 #else
419   pthread_t thread_id = (pthread_t) 0;
420   pthread_attr_t attr;
421
422   (void) pthread_attr_init(&attr);
423   (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
424
425 #if defined(NS_STACK_SIZE) && NS_STACK_SIZE > 1
426   (void) pthread_attr_setstacksize(&attr, NS_STACK_SIZE);
427 #endif
428
429   pthread_create(&thread_id, &attr, f, p);
430   pthread_attr_destroy(&attr);
431
432   return (void *) thread_id;
433 #endif
434 }
435 #endif  // NS_DISABLE_THREADS
436
437 static void ns_add_conn(struct ns_mgr *mgr, struct ns_connection *c) {
438   c->next = mgr->active_connections;
439   mgr->active_connections = c;
440   c->prev = NULL;
441   if (c->next != NULL) c->next->prev = c;
442 }
443
444 static void ns_remove_conn(struct ns_connection *conn) {
445   if (conn->prev == NULL) conn->mgr->active_connections = conn->next;
446   if (conn->prev) conn->prev->next = conn->next;
447   if (conn->next) conn->next->prev = conn->prev;
448 }
449
450 // Print message to buffer. If buffer is large enough to hold the message,
451 // return buffer. If buffer is to small, allocate large enough buffer on heap,
452 // and return allocated buffer.
453 int ns_avprintf(char **buf, size_t size, const char *fmt, va_list ap) {
454   va_list ap_copy;
455   int len;
456
457   va_copy(ap_copy, ap);
458   len = vsnprintf(*buf, size, fmt, ap_copy);
459   va_end(ap_copy);
460
461   if (len < 0) {
462     // eCos and Windows are not standard-compliant and return -1 when
463     // the buffer is too small. Keep allocating larger buffers until we
464     // succeed or out of memory.
465     *buf = NULL;
466     while (len < 0) {
467       if (*buf) NS_FREE(*buf);
468       size *= 2;
469       if ((*buf = (char *) NS_MALLOC(size)) == NULL) break;
470       va_copy(ap_copy, ap);
471       len = vsnprintf(*buf, size, fmt, ap_copy);
472       va_end(ap_copy);
473     }
474   } else if (len > (int) size) {
475     // Standard-compliant code path. Allocate a buffer that is large enough.
476     if ((*buf = (char *) NS_MALLOC(len + 1)) == NULL) {
477       len = -1;
478     } else {
479       va_copy(ap_copy, ap);
480       len = vsnprintf(*buf, len + 1, fmt, ap_copy);
481       va_end(ap_copy);
482     }
483   }
484
485   return len;
486 }
487
488 int ns_vprintf(struct ns_connection *nc, const char *fmt, va_list ap) {
489   char mem[NS_VPRINTF_BUFFER_SIZE], *buf = mem;
490   int len;
491
492   if ((len = ns_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
493     ns_out(nc, buf, len);
494   }
495   if (buf != mem && buf != NULL) {
496     NS_FREE(buf);
497   }
498
499   return len;
500 }
501
502 int ns_printf(struct ns_connection *conn, const char *fmt, ...) {
503   int len;
504   va_list ap;
505   va_start(ap, fmt);
506   len = ns_vprintf(conn, fmt, ap);
507   va_end(ap);
508   return len;
509 }
510
511 static void hexdump(struct ns_connection *nc, const char *path,
512                     int num_bytes, int ev) {
513   const struct iobuf *io = ev == NS_SEND ? &nc->send_iobuf : &nc->recv_iobuf;
514   FILE *fp;
515   char *buf, src[60], dst[60];
516   int buf_size = num_bytes * 5 + 100;
517
518   if ((fp = fopen(path, "a")) != NULL) {
519     ns_sock_to_str(nc->sock, src, sizeof(src), 3);
520     ns_sock_to_str(nc->sock, dst, sizeof(dst), 7);
521     fprintf(fp, "%lu %p %s %s %s %d\n", (unsigned long) time(NULL),
522             nc->user_data, src,
523             ev == NS_RECV ? "<-" : ev == NS_SEND ? "->" :
524             ev == NS_ACCEPT ? "<A" : ev == NS_CONNECT ? "C>" : "XX",
525             dst, num_bytes);
526     if (num_bytes > 0 && (buf = (char *) NS_MALLOC(buf_size)) != NULL) {
527       ns_hexdump(io->buf + (ev == NS_SEND ? 0 : io->len) -
528         (ev == NS_SEND ? 0 : num_bytes), num_bytes, buf, buf_size);
529       fprintf(fp, "%s", buf);
530       NS_FREE(buf);
531     }
532     fclose(fp);
533   }
534 }
535
536 static void ns_call(struct ns_connection *nc, int ev, void *p) {
537   if (nc->mgr->hexdump_file != NULL && ev != NS_POLL) {
538     int len = (ev == NS_RECV || ev == NS_SEND) ? * (int *) p : 0;
539     hexdump(nc, nc->mgr->hexdump_file, len, ev);
540   }
541
542   nc->callback(nc, ev, p);
543 }
544
545 static void ns_destroy_conn(struct ns_connection *conn) {
546   closesocket(conn->sock);
547   iobuf_free(&conn->recv_iobuf);
548   iobuf_free(&conn->send_iobuf);
549 #ifdef NS_ENABLE_SSL
550   if (conn->ssl != NULL) {
551     SSL_free(conn->ssl);
552   }
553   if (conn->ssl_ctx != NULL) {
554     SSL_CTX_free(conn->ssl_ctx);
555   }
556 #endif
557   NS_FREE(conn);
558 }
559
560 static void ns_close_conn(struct ns_connection *conn) {
561   DBG(("%p %d", conn, conn->flags));
562   ns_call(conn, NS_CLOSE, NULL);
563   ns_remove_conn(conn);
564   ns_destroy_conn(conn);
565 }
566
567 void ns_set_close_on_exec(sock_t sock) {
568 #ifdef _WIN32
569   (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
570 #else
571   fcntl(sock, F_SETFD, FD_CLOEXEC);
572 #endif
573 }
574
575 static void ns_set_non_blocking_mode(sock_t sock) {
576 #ifdef _WIN32
577   unsigned long on = 1;
578   ioctlsocket(sock, FIONBIO, &on);
579 #else
580   int flags = fcntl(sock, F_GETFL, 0);
581   fcntl(sock, F_SETFL, flags | O_NONBLOCK);
582 #endif
583 }
584
585 #ifndef NS_DISABLE_SOCKETPAIR
586 int ns_socketpair2(sock_t sp[2], int sock_type) {
587   union socket_address sa;
588   sock_t sock;
589   socklen_t len = sizeof(sa.sin);
590   int ret = 0;
591
592   sp[0] = sp[1] = INVALID_SOCKET;
593
594   (void) memset(&sa, 0, sizeof(sa));
595   sa.sin.sin_family = AF_INET;
596   sa.sin.sin_port = htons(0);
597   sa.sin.sin_addr.s_addr = htonl(0x7f000001);
598
599   if ((sock = socket(AF_INET, sock_type, 0)) != INVALID_SOCKET &&
600       !bind(sock, &sa.sa, len) &&
601       (sock_type == SOCK_DGRAM || !listen(sock, 1)) &&
602       !getsockname(sock, &sa.sa, &len) &&
603       (sp[0] = socket(AF_INET, sock_type, 0)) != INVALID_SOCKET &&
604       !connect(sp[0], &sa.sa, len) &&
605       (sock_type == SOCK_STREAM ||
606        (!getsockname(sp[0], &sa.sa, &len) && !connect(sock, &sa.sa, len))) &&
607       (sp[1] = (sock_type == SOCK_DGRAM ? sock :
608                 accept(sock, &sa.sa, &len))) != INVALID_SOCKET) {
609     ns_set_close_on_exec(sp[0]);
610     ns_set_close_on_exec(sp[1]);
611     ret = 1;
612   } else {
613     if (sp[0] != INVALID_SOCKET) closesocket(sp[0]);
614     if (sp[1] != INVALID_SOCKET) closesocket(sp[1]);
615     sp[0] = sp[1] = INVALID_SOCKET;
616   }
617   if (sock_type != SOCK_DGRAM) closesocket(sock);
618
619   return ret;
620 }
621
622 int ns_socketpair(sock_t sp[2]) {
623   return ns_socketpair2(sp, SOCK_STREAM);
624 }
625 #endif  // NS_DISABLE_SOCKETPAIR
626
627 // TODO(lsm): use non-blocking resolver
628 static int ns_resolve2(const char *host, struct in_addr *ina) {
629 #ifdef NS_ENABLE_GETADDRINFO
630   int rv = 0;
631   struct addrinfo hints, *servinfo, *p;
632   struct sockaddr_in *h = NULL;
633
634   memset(&hints, 0, sizeof hints);
635   hints.ai_family = AF_INET;
636   hints.ai_socktype = SOCK_STREAM;
637
638   if((rv = getaddrinfo(host, NULL , NULL, &servinfo)) != 0) {
639     DBG(("getaddrinfo(%s) failed: %s", host, strerror(errno)));
640     return 0;
641   }
642
643   for(p = servinfo; p != NULL; p = p->ai_next) {
644     memcpy(&h, &p->ai_addr, sizeof(struct sockaddr_in *));
645     memcpy(ina, &h->sin_addr, sizeof(ina));
646   }
647
648   freeaddrinfo(servinfo);
649   return 1;
650 #else
651   struct hostent *he;
652   if ((he = gethostbyname(host)) == NULL) {
653     DBG(("gethostbyname(%s) failed: %s", host, strerror(errno)));
654   } else {
655     memcpy(ina, he->h_addr_list[0], sizeof(*ina));
656     return 1;
657   }
658   return 0;
659 #endif
660 }
661
662 // Resolve FDQN "host", store IP address in the "ip".
663 // Return > 0 (IP address length) on success.
664 int ns_resolve(const char *host, char *buf, size_t n) {
665   struct in_addr ad;
666   return ns_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0;
667 }
668
669 // Address format: [PROTO://][IP_ADDRESS:]PORT[:CERT][:CA_CERT]
670 static int ns_parse_address(const char *str, union socket_address *sa,
671                             int *proto, int *use_ssl, char *cert, char *ca) {
672   unsigned int a, b, c, d, port;
673   int n = 0, len = 0;
674   char host[200];
675 #ifdef NS_ENABLE_IPV6
676   char buf[100];
677 #endif
678
679   // MacOS needs that. If we do not zero it, subsequent bind() will fail.
680   // Also, all-zeroes in the socket address means binding to all addresses
681   // for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
682   memset(sa, 0, sizeof(*sa));
683   sa->sin.sin_family = AF_INET;
684
685   *proto = SOCK_STREAM;
686   *use_ssl = 0;
687   cert[0] = ca[0] = '\0';
688
689   if (memcmp(str, "ssl://", 6) == 0) {
690     str += 6;
691     *use_ssl = 1;
692   } else if (memcmp(str, "udp://", 6) == 0) {
693     str += 6;
694     *proto = SOCK_DGRAM;
695   } else if (memcmp(str, "tcp://", 6) == 0) {
696     str += 6;
697   }
698
699   if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
700     // Bind to a specific IPv4 address, e.g. 192.168.1.5:8080
701     sa->sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
702     sa->sin.sin_port = htons((uint16_t) port);
703 #ifdef NS_ENABLE_IPV6
704   } else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 &&
705              inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
706     // IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080
707     sa->sin6.sin6_family = AF_INET6;
708     sa->sin6.sin6_port = htons((uint16_t) port);
709 #endif
710   } else if (sscanf(str, "%199[^ :]:%u%n", host, &port, &len) == 2) {
711     sa->sin.sin_port = htons((uint16_t) port);
712     ns_resolve2(host, &sa->sin.sin_addr);
713   } else if (sscanf(str, "%u%n", &port, &len) == 1) {
714     // If only port is specified, bind to IPv4, INADDR_ANY
715     sa->sin.sin_port = htons((uint16_t) port);
716   }
717
718   if (*use_ssl && (sscanf(str + len, ":%99[^:,]:%99[^:,]%n", cert, ca, &n) == 2 ||
719                    sscanf(str + len, ":%99[^:,]%n", cert, &n) == 1)) {
720     len += n;
721   }
722
723   return port < 0xffff && str[len] == '\0' ? len : 0;
724 }
725
726 // 'sa' must be an initialized address to bind to
727 static sock_t ns_open_listening_socket(union socket_address *sa, int proto) {
728   socklen_t sa_len = (sa->sa.sa_family == AF_INET) ?
729     sizeof(sa->sin) : sizeof(sa->sin6);
730   sock_t sock = INVALID_SOCKET;
731 #ifndef _WIN32
732   int on = 1;
733 #endif
734
735   if ((sock = socket(sa->sa.sa_family, proto, 0)) != INVALID_SOCKET &&
736 #ifndef _WIN32
737       // SO_RESUSEADDR is not enabled on Windows because the semantics of
738       // SO_REUSEADDR on UNIX and Windows is different. On Windows,
739       // SO_REUSEADDR allows to bind a socket to a port without error even if
740       // the port is already open by another program. This is not the behavior
741       // SO_REUSEADDR was designed for, and leads to hard-to-track failure
742       // scenarios. Therefore, SO_REUSEADDR was disabled on Windows.
743       !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) &&
744 #endif
745       !bind(sock, &sa->sa, sa_len) &&
746       (proto == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) {
747     ns_set_non_blocking_mode(sock);
748     // In case port was set to 0, get the real port number
749     (void) getsockname(sock, &sa->sa, &sa_len);
750   } else if (sock != INVALID_SOCKET) {
751     closesocket(sock);
752     sock = INVALID_SOCKET;
753   }
754
755   return sock;
756 }
757
758 #ifdef NS_ENABLE_SSL
759 // Certificate generation script is at
760 // https://github.com/cesanta/net_skeleton/blob/master/scripts/gen_certs.sh
761
762 static int ns_use_ca_cert(SSL_CTX *ctx, const char *cert) {
763   if (ctx == NULL) {
764     return -1;
765   } else if (cert == NULL || cert[0] == '\0') {
766     return 0;
767   }
768   SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
769   return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? 0 : -2;
770 }
771
772 static int ns_use_cert(SSL_CTX *ctx, const char *pem_file) {
773   if (ctx == NULL) {
774     return -1;
775   } else if (pem_file == NULL || pem_file[0] == '\0') {
776     return 0;
777   } else if (SSL_CTX_use_certificate_file(ctx, pem_file, 1) == 0 ||
778              SSL_CTX_use_PrivateKey_file(ctx, pem_file, 1) == 0) {
779     return -2;
780   } else {
781     SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
782     SSL_CTX_use_certificate_chain_file(ctx, pem_file);
783     return 0;
784   }
785 }
786 #endif  // NS_ENABLE_SSL
787
788 struct ns_connection *ns_bind(struct ns_mgr *srv, const char *str,
789                               ns_callback_t callback, void *user_data) {
790   union socket_address sa;
791   struct ns_connection *nc = NULL;
792   int use_ssl, proto;
793   char cert[100], ca_cert[100];
794   sock_t sock;
795
796   ns_parse_address(str, &sa, &proto, &use_ssl, cert, ca_cert);
797   if (use_ssl && cert[0] == '\0') return NULL;
798
799   if ((sock = ns_open_listening_socket(&sa, proto)) == INVALID_SOCKET) {
800   } else if ((nc = ns_add_sock(srv, sock, callback, NULL)) == NULL) {
801     closesocket(sock);
802   } else {
803     nc->sa = sa;
804     nc->flags |= NSF_LISTENING;
805     nc->user_data = user_data;
806     nc->callback = callback;
807
808     if (proto == SOCK_DGRAM) {
809       nc->flags |= NSF_UDP;
810     }
811
812 #ifdef NS_ENABLE_SSL
813     if (use_ssl) {
814       nc->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
815       if (ns_use_cert(nc->ssl_ctx, cert) != 0 ||
816           ns_use_ca_cert(nc->ssl_ctx, ca_cert) != 0) {
817         ns_close_conn(nc);
818         nc = NULL;
819       }
820     }
821 #endif
822
823     DBG(("%p sock %d/%d ssl %p %p", nc, sock, proto, nc->ssl_ctx, nc->ssl));
824   }
825
826   return nc;
827 }
828
829 static struct ns_connection *accept_conn(struct ns_connection *ls) {
830   struct ns_connection *c = NULL;
831   union socket_address sa;
832   socklen_t len = sizeof(sa);
833   sock_t sock = INVALID_SOCKET;
834
835   // NOTE(lsm): on Windows, sock is always > FD_SETSIZE
836   if ((sock = accept(ls->sock, &sa.sa, &len)) == INVALID_SOCKET) {
837   } else if ((c = ns_add_sock(ls->mgr, sock, ls->callback,
838               ls->user_data)) == NULL) {
839     closesocket(sock);
840 #ifdef NS_ENABLE_SSL
841   } else if (ls->ssl_ctx != NULL &&
842              ((c->ssl = SSL_new(ls->ssl_ctx)) == NULL ||
843               SSL_set_fd(c->ssl, sock) != 1)) {
844     DBG(("SSL error"));
845     ns_close_conn(c);
846     c = NULL;
847 #endif
848   } else {
849     c->listener = ls;
850     c->proto_data = ls->proto_data;
851     ns_call(c, NS_ACCEPT, &sa);
852     DBG(("%p %d %p %p", c, c->sock, c->ssl_ctx, c->ssl));
853   }
854
855   return c;
856 }
857
858 static int ns_is_error(int n) {
859   return n == 0 ||
860     (n < 0 && errno != EINTR && errno != EINPROGRESS &&
861      errno != EAGAIN && errno != EWOULDBLOCK
862 #ifdef _WIN32
863      && WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK
864 #endif
865     );
866 }
867
868 void ns_sock_to_str(sock_t sock, char *buf, size_t len, int flags) {
869   union socket_address sa;
870   socklen_t slen = sizeof(sa);
871
872   if (buf != NULL && len > 0) {
873     buf[0] = '\0';
874     memset(&sa, 0, sizeof(sa));
875     if (flags & 4) {
876       getpeername(sock, &sa.sa, &slen);
877     } else {
878       getsockname(sock, &sa.sa, &slen);
879     }
880     if (flags & 1) {
881 #if defined(NS_ENABLE_IPV6)
882       inet_ntop(sa.sa.sa_family, sa.sa.sa_family == AF_INET ?
883                 (void *) &sa.sin.sin_addr :
884                 (void *) &sa.sin6.sin6_addr, buf, len);
885 #elif defined(_WIN32)
886       // Only Windoze Vista (and newer) have inet_ntop()
887       strncpy(buf, inet_ntoa(sa.sin.sin_addr), len);
888 #else
889       inet_ntop(sa.sa.sa_family, (void *) &sa.sin.sin_addr, buf,(socklen_t)len);
890 #endif
891     }
892     if (flags & 2) {
893       snprintf(buf + strlen(buf), len - (strlen(buf) + 1), "%s%d",
894                flags & 1 ? ":" : "", (int) ntohs(sa.sin.sin_port));
895     }
896   }
897 }
898
899 int ns_hexdump(const void *buf, int len, char *dst, int dst_len) {
900   const unsigned char *p = (const unsigned char *) buf;
901   char ascii[17] = "";
902   int i, idx, n = 0;
903
904   for (i = 0; i < len; i++) {
905     idx = i % 16;
906     if (idx == 0) {
907       if (i > 0) n += snprintf(dst + n, dst_len - n, "  %s\n", ascii);
908       n += snprintf(dst + n, dst_len - n, "%04x ", i);
909     }
910     n += snprintf(dst + n, dst_len - n, " %02x", p[i]);
911     ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i];
912     ascii[idx + 1] = '\0';
913   }
914
915   while (i++ % 16) n += snprintf(dst + n, dst_len - n, "%s", "   ");
916   n += snprintf(dst + n, dst_len - n, "  %s\n\n", ascii);
917
918   return n;
919 }
920
921 #ifdef NS_ENABLE_SSL
922 static int ns_ssl_err(struct ns_connection *conn, int res) {
923   int ssl_err = SSL_get_error(conn->ssl, res);
924   if (ssl_err == SSL_ERROR_WANT_READ) conn->flags |= NSF_WANT_READ;
925   if (ssl_err == SSL_ERROR_WANT_WRITE) conn->flags |= NSF_WANT_WRITE;
926   return ssl_err;
927 }
928 #endif
929
930 static void ns_read_from_socket(struct ns_connection *conn) {
931   char buf[NS_READ_BUFFER_SIZE];
932   int n = 0;
933
934   if (conn->flags & NSF_CONNECTING) {
935     int ok = 1, ret;
936     socklen_t len = sizeof(ok);
937
938     ret = getsockopt(conn->sock, SOL_SOCKET, SO_ERROR, (char *) &ok, &len);
939     (void) ret;
940 #ifdef NS_ENABLE_SSL
941     if (ret == 0 && ok == 0 && conn->ssl != NULL) {
942       int res = SSL_connect(conn->ssl);
943       int ssl_err = ns_ssl_err(conn, res);
944       if (res == 1) {
945         conn->flags |= NSF_SSL_HANDSHAKE_DONE;
946       } else if (ssl_err == SSL_ERROR_WANT_READ ||
947                  ssl_err == SSL_ERROR_WANT_WRITE) {
948         return; // Call us again
949       } else {
950         ok = 1;
951       }
952       conn->flags &= ~(NSF_WANT_READ | NSF_WANT_WRITE);
953     }
954 #endif
955     conn->flags &= ~NSF_CONNECTING;
956     DBG(("%p ok=%d", conn, ok));
957     if (ok != 0) {
958       conn->flags |= NSF_CLOSE_IMMEDIATELY;
959     }
960     ns_call(conn, NS_CONNECT, &ok);
961     return;
962   }
963
964 #ifdef NS_ENABLE_SSL
965   if (conn->ssl != NULL) {
966     if (conn->flags & NSF_SSL_HANDSHAKE_DONE) {
967       // SSL library may have more bytes ready to read then we ask to read.
968       // Therefore, read in a loop until we read everything. Without the loop,
969       // we skip to the next select() cycle which can just timeout.
970       while ((n = SSL_read(conn->ssl, buf, sizeof(buf))) > 0) {
971         DBG(("%p %d <- %d bytes (SSL)", conn, conn->flags, n));
972         iobuf_append(&conn->recv_iobuf, buf, n);
973         ns_call(conn, NS_RECV, &n);
974       }
975       ns_ssl_err(conn, n);
976     } else {
977       int res = SSL_accept(conn->ssl);
978       int ssl_err = ns_ssl_err(conn, res);
979       if (res == 1) {
980         conn->flags |= NSF_SSL_HANDSHAKE_DONE;
981         conn->flags &= ~(NSF_WANT_READ | NSF_WANT_WRITE);
982       } else if (ssl_err == SSL_ERROR_WANT_READ ||
983                  ssl_err == SSL_ERROR_WANT_WRITE) {
984         return; // Call us again
985       } else {
986         conn->flags |= NSF_CLOSE_IMMEDIATELY;
987       }
988       return;
989     }
990   } else
991 #endif
992   {
993     while ((n = (int) recv(conn->sock, buf, sizeof(buf), 0)) > 0) {
994       DBG(("%p %d <- %d bytes (PLAIN)", conn, conn->flags, n));
995       iobuf_append(&conn->recv_iobuf, buf, n);
996       ns_call(conn, NS_RECV, &n);
997     }
998   }
999
1000   if (ns_is_error(n)) {
1001     conn->flags |= NSF_CLOSE_IMMEDIATELY;
1002   }
1003 }
1004
1005 static void ns_write_to_socket(struct ns_connection *conn) {
1006   struct iobuf *io = &conn->send_iobuf;
1007   int n = 0;
1008
1009 #ifdef NS_ENABLE_SSL
1010   if (conn->ssl != NULL) {
1011     n = SSL_write(conn->ssl, io->buf, io->len);
1012     if (n <= 0) {
1013       int ssl_err = ns_ssl_err(conn, n);
1014       if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
1015         return; // Call us again
1016       } else {
1017         conn->flags |= NSF_CLOSE_IMMEDIATELY;
1018       }
1019     } else {
1020       conn->flags &= ~(NSF_WANT_READ | NSF_WANT_WRITE);
1021     }
1022   } else
1023 #endif
1024   { n = (int) send(conn->sock, io->buf, io->len, 0); }
1025
1026   DBG(("%p %d -> %d bytes", conn, conn->flags, n));
1027
1028   ns_call(conn, NS_SEND, &n);
1029   if (ns_is_error(n)) {
1030     conn->flags |= NSF_CLOSE_IMMEDIATELY;
1031   } else if (n > 0) {
1032     iobuf_remove(io, n);
1033   }
1034 }
1035
1036 int ns_send(struct ns_connection *conn, const void *buf, size_t len) {
1037   return (int) ns_out(conn, buf, len);
1038 }
1039
1040 static void ns_handle_udp(struct ns_connection *ls) {
1041   struct ns_connection nc;
1042   char buf[NS_UDP_RECEIVE_BUFFER_SIZE];
1043   ssize_t n;
1044   socklen_t s_len = sizeof(nc.sa);
1045
1046   memset(&nc, 0, sizeof(nc));
1047   n = recvfrom(ls->sock, buf, sizeof(buf), 0, &nc.sa.sa, &s_len);
1048   if (n <= 0) {
1049     DBG(("%p recvfrom: %s", ls, strerror(errno)));
1050   } else {
1051     nc.mgr = ls->mgr;
1052     nc.recv_iobuf.buf = buf;
1053     nc.recv_iobuf.len = nc.recv_iobuf.size = n;
1054     nc.sock = ls->sock;
1055     nc.callback = ls->callback;
1056     nc.user_data = ls->user_data;
1057     nc.proto_data = ls->proto_data;
1058     nc.mgr = ls->mgr;
1059     nc.listener = ls;
1060     nc.flags = NSF_UDP;
1061     DBG(("%p %d bytes received", ls, n));
1062     ns_call(&nc, NS_RECV, &n);
1063   }
1064 }
1065
1066 static void ns_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) {
1067   if ( (sock != INVALID_SOCKET) && (sock < FD_SETSIZE) ) {
1068     FD_SET(sock, set);
1069     if (*max_fd == INVALID_SOCKET || sock > *max_fd) {
1070       *max_fd = sock;
1071     }
1072   }
1073 }
1074
1075 time_t ns_mgr_poll(struct ns_mgr *mgr, int milli) {
1076   struct ns_connection *conn, *tmp_conn;
1077   struct timeval tv;
1078   fd_set read_set, write_set;
1079   sock_t max_fd = INVALID_SOCKET;
1080   time_t current_time = time(NULL);
1081
1082   FD_ZERO(&read_set);
1083   FD_ZERO(&write_set);
1084   ns_add_to_set(mgr->ctl[1], &read_set, &max_fd);
1085
1086   for (conn = mgr->active_connections; conn != NULL; conn = tmp_conn) {
1087     tmp_conn = conn->next;
1088     if (!(conn->flags & (NSF_LISTENING | NSF_CONNECTING))) {
1089       ns_call(conn, NS_POLL, &current_time);
1090     }
1091     if (conn->flags & NSF_CLOSE_IMMEDIATELY) {
1092       ns_close_conn(conn);
1093     } else {
1094       if (!(conn->flags & NSF_WANT_WRITE)) {
1095         //DBG(("%p read_set", conn));
1096         ns_add_to_set(conn->sock, &read_set, &max_fd);
1097       }
1098       if (((conn->flags & NSF_CONNECTING) && !(conn->flags & NSF_WANT_READ)) ||
1099           (conn->send_iobuf.len > 0 && !(conn->flags & NSF_CONNECTING) &&
1100            !(conn->flags & NSF_BUFFER_BUT_DONT_SEND))) {
1101         //DBG(("%p write_set", conn));
1102         ns_add_to_set(conn->sock, &write_set, &max_fd);
1103       }
1104     }
1105   }
1106
1107   tv.tv_sec = milli / 1000;
1108   tv.tv_usec = (milli % 1000) * 1000;
1109
1110   if (select((int) max_fd + 1, &read_set, &write_set, NULL, &tv) > 0) {
1111     // select() might have been waiting for a long time, reset current_time
1112     // now to prevent last_io_time being set to the past.
1113     current_time = time(NULL);
1114
1115     // Read wakeup messages
1116     if (mgr->ctl[1] != INVALID_SOCKET &&
1117         FD_ISSET(mgr->ctl[1], &read_set)) {
1118       struct ctl_msg ctl_msg;
1119       int len = (int) recv(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0);
1120       send(mgr->ctl[1], ctl_msg.message, 1, 0);
1121       if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) {
1122         struct ns_connection *c;
1123         for (c = ns_next(mgr, NULL); c != NULL; c = ns_next(mgr, c)) {
1124           ctl_msg.callback(c, NS_POLL, ctl_msg.message);
1125         }
1126       }
1127     }
1128
1129     for (conn = mgr->active_connections; conn != NULL; conn = tmp_conn) {
1130       tmp_conn = conn->next;
1131       if (FD_ISSET(conn->sock, &read_set)) {
1132         if (conn->flags & NSF_LISTENING) {
1133           if (conn->flags & NSF_UDP) {
1134             ns_handle_udp(conn);
1135           } else {
1136             // We're not looping here, and accepting just one connection at
1137             // a time. The reason is that eCos does not respect non-blocking
1138             // flag on a listening socket and hangs in a loop.
1139             accept_conn(conn);
1140           }
1141         } else {
1142           conn->last_io_time = current_time;
1143           ns_read_from_socket(conn);
1144         }
1145       }
1146
1147       if (FD_ISSET(conn->sock, &write_set)) {
1148         if (conn->flags & NSF_CONNECTING) {
1149           ns_read_from_socket(conn);
1150         } else if (!(conn->flags & NSF_BUFFER_BUT_DONT_SEND)) {
1151           conn->last_io_time = current_time;
1152           ns_write_to_socket(conn);
1153         }
1154       }
1155     }
1156   }
1157
1158   for (conn = mgr->active_connections; conn != NULL; conn = tmp_conn) {
1159     tmp_conn = conn->next;
1160     if ((conn->flags & NSF_CLOSE_IMMEDIATELY) ||
1161         (conn->send_iobuf.len == 0 &&
1162           (conn->flags & NSF_FINISHED_SENDING_DATA))) {
1163       ns_close_conn(conn);
1164     }
1165   }
1166
1167   return current_time;
1168 }
1169
1170 struct ns_connection *ns_connect(struct ns_mgr *mgr, const char *address,
1171                                  ns_callback_t callback, void *user_data) {
1172   sock_t sock = INVALID_SOCKET;
1173   struct ns_connection *nc = NULL;
1174   union socket_address sa;
1175   char cert[100], ca_cert[100];
1176   int rc, use_ssl, proto;
1177
1178   ns_parse_address(address, &sa, &proto, &use_ssl, cert, ca_cert);
1179   if ((sock = socket(AF_INET, proto, 0)) == INVALID_SOCKET) {
1180     return NULL;
1181   }
1182   ns_set_non_blocking_mode(sock);
1183   rc = (proto == SOCK_DGRAM) ? 0 : connect(sock, &sa.sa, sizeof(sa.sin));
1184
1185   if (rc != 0 && ns_is_error(rc)) {
1186     closesocket(sock);
1187     return NULL;
1188   } else if ((nc = ns_add_sock(mgr, sock, callback, user_data)) == NULL) {
1189     closesocket(sock);
1190     return NULL;
1191   }
1192
1193   nc->sa = sa;   // Important, cause UDP conns will use sendto()
1194   nc->flags = (proto == SOCK_DGRAM) ? NSF_UDP : NSF_CONNECTING;
1195
1196 #ifdef NS_ENABLE_SSL
1197   if (use_ssl) {
1198     if ((nc->ssl_ctx = SSL_CTX_new(SSLv23_client_method())) == NULL ||
1199         ns_use_cert(nc->ssl_ctx, cert) != 0 ||
1200         ns_use_ca_cert(nc->ssl_ctx, ca_cert) != 0 ||
1201         (nc->ssl = SSL_new(nc->ssl_ctx)) == NULL) {
1202       ns_close_conn(nc);
1203       return NULL;
1204     } else {
1205       SSL_set_fd(nc->ssl, sock);
1206     }
1207   }
1208 #endif
1209
1210   return nc;
1211 }
1212
1213 struct ns_connection *ns_add_sock(struct ns_mgr *s, sock_t sock,
1214                                   ns_callback_t callback, void *user_data) {
1215   struct ns_connection *conn;
1216   if ((conn = (struct ns_connection *) NS_MALLOC(sizeof(*conn))) != NULL) {
1217     memset(conn, 0, sizeof(*conn));
1218     ns_set_non_blocking_mode(sock);
1219     ns_set_close_on_exec(sock);
1220     conn->sock = sock;
1221     conn->user_data = user_data;
1222     conn->callback = callback;
1223     conn->mgr = s;
1224     conn->last_io_time = time(NULL);
1225     ns_add_conn(s, conn);
1226     DBG(("%p %d", conn, sock));
1227   }
1228   return conn;
1229 }
1230
1231 struct ns_connection *ns_next(struct ns_mgr *s, struct ns_connection *conn) {
1232   return conn == NULL ? s->active_connections : conn->next;
1233 }
1234
1235 void ns_broadcast(struct ns_mgr *mgr, ns_callback_t cb,void *data, size_t len) {
1236   struct ctl_msg ctl_msg;
1237   if (mgr->ctl[0] != INVALID_SOCKET && data != NULL &&
1238       len < sizeof(ctl_msg.message)) {
1239     ctl_msg.callback = cb;
1240     memcpy(ctl_msg.message, data, len);
1241     send(mgr->ctl[0], (char *) &ctl_msg,
1242          offsetof(struct ctl_msg, message) + len, 0);
1243     recv(mgr->ctl[0], (char *) &len, 1, 0);
1244   }
1245 }
1246
1247 void ns_mgr_init(struct ns_mgr *s, void *user_data) {
1248   memset(s, 0, sizeof(*s));
1249   s->ctl[0] = s->ctl[1] = INVALID_SOCKET;
1250   s->user_data = user_data;
1251
1252 #ifdef _WIN32
1253   { WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); }
1254 #else
1255   // Ignore SIGPIPE signal, so if client cancels the request, it
1256   // won't kill the whole process.
1257   signal(SIGPIPE, SIG_IGN);
1258 #endif
1259
1260 #ifndef NS_DISABLE_SOCKETPAIR
1261   do {
1262     ns_socketpair2(s->ctl, SOCK_DGRAM);
1263   } while (s->ctl[0] == INVALID_SOCKET);
1264 #endif
1265
1266 #ifdef NS_ENABLE_SSL
1267   {static int init_done; if (!init_done) { SSL_library_init(); init_done++; }}
1268 #endif
1269 }
1270
1271 void ns_mgr_free(struct ns_mgr *s) {
1272   struct ns_connection *conn, *tmp_conn;
1273
1274   DBG(("%p", s));
1275   if (s == NULL) return;
1276   // Do one last poll, see https://github.com/cesanta/mongoose/issues/286
1277   ns_mgr_poll(s, 0);
1278
1279   if (s->ctl[0] != INVALID_SOCKET) closesocket(s->ctl[0]);
1280   if (s->ctl[1] != INVALID_SOCKET) closesocket(s->ctl[1]);
1281   s->ctl[0] = s->ctl[1] = INVALID_SOCKET;
1282
1283   for (conn = s->active_connections; conn != NULL; conn = tmp_conn) {
1284     tmp_conn = conn->next;
1285     ns_close_conn(conn);
1286   }
1287 }
1288 // net_skeleton end
1289 #endif  // NOEMBED_NET_SKELETON
1290
1291 #include <ctype.h>
1292
1293 #ifdef _WIN32         //////////////// Windows specific defines and includes
1294 #include <io.h>       // For _lseeki64
1295 #include <direct.h>   // For _mkdir
1296 #ifndef S_ISDIR
1297 #define S_ISDIR(x) ((x) & _S_IFDIR)
1298 #endif
1299 #ifdef stat
1300 #undef stat
1301 #endif
1302 #ifdef lseek
1303 #undef lseek
1304 #endif
1305 #ifdef popen
1306 #undef popen
1307 #endif
1308 #ifdef pclose
1309 #undef pclose
1310 #endif
1311 #define stat(x, y) mg_stat((x), (y))
1312 #define fopen(x, y) mg_fopen((x), (y))
1313 #define open(x, y, z) mg_open((x), (y), (z))
1314 #define close(x) _close(x)
1315 #define fileno(x) _fileno(x)
1316 #define lseek(x, y, z) _lseeki64((x), (y), (z))
1317 #define read(x, y, z) _read((x), (y), (z))
1318 #define write(x, y, z) _write((x), (y), (z))
1319 #define popen(x, y) _popen((x), (y))
1320 #define pclose(x) _pclose(x)
1321 #define mkdir(x, y) _mkdir(x)
1322 #define rmdir(x) _rmdir(x)
1323 #define strdup(x) _strdup(x)
1324 #ifndef __func__
1325 #define STRX(x) #x
1326 #define STR(x) STRX(x)
1327 #define __func__ __FILE__ ":" STR(__LINE__)
1328 #endif
1329 #define INT64_FMT   "I64d"
1330 #define flockfile(x)      ((void) (x))
1331 #define funlockfile(x)    ((void) (x))
1332 typedef struct _stati64 file_stat_t;
1333 typedef HANDLE process_id_t;
1334
1335 #else                    ////////////// UNIX specific defines and includes
1336
1337 #if !defined(MONGOOSE_NO_FILESYSTEM) &&\
1338     (!defined(MONGOOSE_NO_DAV) || !defined(MONGOOSE_NO_DIRECTORY_LISTING))
1339 #include <dirent.h>
1340 #endif
1341 #if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_DL)
1342 #include <dlfcn.h>
1343 #endif
1344 #include <inttypes.h>
1345 #include <pwd.h>
1346 #if !defined(O_BINARY)
1347 #define O_BINARY 0
1348 #endif
1349 #define INT64_FMT PRId64
1350 typedef struct stat file_stat_t;
1351 typedef pid_t process_id_t;
1352 #endif                  //////// End of platform-specific defines and includes
1353
1354 #include "mongoose.h"
1355
1356 #define MAX_REQUEST_SIZE 16384
1357 #define IOBUF_SIZE 8192
1358 #define MAX_PATH_SIZE 8192
1359 #define DEFAULT_CGI_PATTERN "**.cgi$|**.pl$|**.php$"
1360 #define CGI_ENVIRONMENT_SIZE 8192
1361 #define MAX_CGI_ENVIR_VARS 64
1362 #define ENV_EXPORT_TO_CGI "MONGOOSE_CGI"
1363 #define PASSWORDS_FILE_NAME ".htpasswd"
1364
1365 #ifndef MONGOOSE_USE_WEBSOCKET_PING_INTERVAL
1366 #define MONGOOSE_USE_WEBSOCKET_PING_INTERVAL 5
1367 #endif
1368
1369 // Extra HTTP headers to send in every static file reply
1370 #if !defined(MONGOOSE_USE_EXTRA_HTTP_HEADERS)
1371 #define MONGOOSE_USE_EXTRA_HTTP_HEADERS ""
1372 #endif
1373
1374 #ifndef MONGOOSE_POST_SIZE_LIMIT
1375 #define MONGOOSE_POST_SIZE_LIMIT 0
1376 #endif
1377
1378 #ifndef MONGOOSE_IDLE_TIMEOUT_SECONDS
1379 #define MONGOOSE_IDLE_TIMEOUT_SECONDS 300
1380 #endif
1381
1382 #if defined(NS_DISABLE_SOCKETPAIR) && !defined(MONGOOSE_NO_CGI)
1383 #define MONGOOSE_NO_CGI
1384 #endif
1385
1386 #ifdef MONGOOSE_NO_FILESYSTEM
1387 #define MONGOOSE_NO_AUTH
1388 #if !defined(MONGOOSE_NO_CGI)
1389 #define MONGOOSE_NO_CGI
1390 #endif
1391 #define MONGOOSE_NO_DAV
1392 #define MONGOOSE_NO_DIRECTORY_LISTING
1393 #define MONGOOSE_NO_LOGGING
1394 #define MONGOOSE_NO_SSI
1395 #define MONGOOSE_NO_DL
1396 #endif
1397
1398 struct vec {
1399   const char *ptr;
1400   size_t len;
1401 };
1402
1403 // For directory listing and WevDAV support
1404 struct dir_entry {
1405   struct connection *conn;
1406   char *file_name;
1407   file_stat_t st;
1408 };
1409
1410 // NOTE(lsm): this enum should be in sync with the config_options.
1411 enum {
1412   ACCESS_CONTROL_LIST,
1413 #ifndef MONGOOSE_NO_FILESYSTEM
1414   ACCESS_LOG_FILE,
1415 #ifndef MONGOOSE_NO_AUTH
1416   AUTH_DOMAIN,
1417 #endif
1418 #ifndef MONGOOSE_NO_CGI
1419   CGI_INTERPRETER,
1420   CGI_PATTERN,
1421 #endif
1422   DAV_AUTH_FILE,
1423   DAV_ROOT,
1424   DOCUMENT_ROOT,
1425 #ifndef MONGOOSE_NO_DIRECTORY_LISTING
1426   ENABLE_DIRECTORY_LISTING,
1427 #endif
1428 #endif
1429   ENABLE_PROXY,
1430   EXTRA_MIME_TYPES,
1431 #if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_AUTH)
1432   GLOBAL_AUTH_FILE,
1433 #endif
1434 #ifndef MONGOOSE_NO_FILESYSTEM
1435   HIDE_FILES_PATTERN,
1436   HEXDUMP_FILE,
1437   INDEX_FILES,
1438 #endif
1439   LISTENING_PORT,
1440 #ifndef _WIN32
1441   RUN_AS_USER,
1442 #endif
1443 #ifndef MONGOOSE_NO_SSI
1444   SSI_PATTERN,
1445 #endif
1446   URL_REWRITES,
1447   NUM_OPTIONS
1448 };
1449
1450 static const char *static_config_options[] = {
1451   "access_control_list", NULL,
1452 #ifndef MONGOOSE_NO_FILESYSTEM
1453   "access_log_file", NULL,
1454 #ifndef MONGOOSE_NO_AUTH
1455   "auth_domain", "mydomain.com",
1456 #endif
1457 #ifndef MONGOOSE_NO_CGI
1458   "cgi_interpreter", NULL,
1459   "cgi_pattern", DEFAULT_CGI_PATTERN,
1460 #endif
1461   "dav_auth_file", NULL,
1462   "dav_root", NULL,
1463   "document_root",  NULL,
1464 #ifndef MONGOOSE_NO_DIRECTORY_LISTING
1465   "enable_directory_listing", "yes",
1466 #endif
1467 #endif
1468   "enable_proxy", NULL,
1469   "extra_mime_types", NULL,
1470 #if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_AUTH)
1471   "global_auth_file", NULL,
1472 #endif
1473 #ifndef MONGOOSE_NO_FILESYSTEM
1474   "hide_files_patterns", NULL,
1475   "hexdump_file", NULL,
1476   "index_files","index.html,index.htm,index.shtml,index.cgi,index.php",
1477 #endif
1478   "listening_port", NULL,
1479 #ifndef _WIN32
1480   "run_as_user", NULL,
1481 #endif
1482 #ifndef MONGOOSE_NO_SSI
1483   "ssi_pattern", "**.shtml$|**.shtm$",
1484 #endif
1485   "url_rewrites", NULL,
1486   NULL
1487 };
1488
1489 struct mg_server {
1490   struct ns_mgr ns_mgr;
1491   union socket_address lsa;   // Listening socket address
1492   mg_handler_t event_handler;
1493   char *config_options[NUM_OPTIONS];
1494 };
1495
1496 // Local endpoint representation
1497 union endpoint {
1498   int fd;                     // Opened regular local file
1499   struct ns_connection *nc;   // CGI or proxy->target connection
1500 };
1501
1502 enum endpoint_type {
1503  EP_NONE, EP_FILE, EP_CGI, EP_USER, EP_PUT, EP_CLIENT, EP_PROXY
1504 };
1505
1506 #define MG_HEADERS_SENT NSF_USER_1
1507 #define MG_USING_CHUNKED_API NSF_USER_2
1508 #define MG_CGI_CONN NSF_USER_3
1509 #define MG_PROXY_CONN NSF_USER_4
1510 #define MG_PROXY_DONT_PARSE NSF_USER_5
1511
1512 struct connection {
1513   struct ns_connection *ns_conn;  // NOTE(lsm): main.c depends on this order
1514   struct mg_connection mg_conn;
1515   struct mg_server *server;
1516   union endpoint endpoint;
1517   enum endpoint_type endpoint_type;
1518   char *path_info;
1519   char *request;
1520   int64_t num_bytes_recv; // Total number of bytes received
1521   int64_t cl;             // Reply content length, for Range support
1522   ssize_t request_len;  // Request length, including last \r\n after last header
1523 };
1524
1525 #define MG_CONN_2_CONN(c) ((struct connection *) ((char *) (c) - \
1526   offsetof(struct connection, mg_conn)))
1527
1528 static void open_local_endpoint(struct connection *conn, int skip_user);
1529 static void close_local_endpoint(struct connection *conn);
1530 static void mg_ev_handler(struct ns_connection *nc, int ev, void *p);
1531
1532 static const struct {
1533   const char *extension;
1534   size_t ext_len;
1535   const char *mime_type;
1536 } static_builtin_mime_types[] = {
1537   {".html", 5, "text/html"},
1538   {".htm", 4, "text/html"},
1539   {".shtm", 5, "text/html"},
1540   {".shtml", 6, "text/html"},
1541   {".css", 4, "text/css"},
1542   {".js",  3, "application/javascript"},
1543   {".ico", 4, "image/x-icon"},
1544   {".gif", 4, "image/gif"},
1545   {".jpg", 4, "image/jpeg"},
1546   {".jpeg", 5, "image/jpeg"},
1547   {".png", 4, "image/png"},
1548   {".svg", 4, "image/svg+xml"},
1549   {".txt", 4, "text/plain"},
1550   {".torrent", 8, "application/x-bittorrent"},
1551   {".wav", 4, "audio/x-wav"},
1552   {".mp3", 4, "audio/x-mp3"},
1553   {".mid", 4, "audio/mid"},
1554   {".m3u", 4, "audio/x-mpegurl"},
1555   {".ogg", 4, "application/ogg"},
1556   {".ram", 4, "audio/x-pn-realaudio"},
1557   {".xml", 4, "text/xml"},
1558   {".json",  5, "application/json"},
1559   {".xslt", 5, "application/xml"},
1560   {".xsl", 4, "application/xml"},
1561   {".ra",  3, "audio/x-pn-realaudio"},
1562   {".doc", 4, "application/msword"},
1563   {".exe", 4, "application/octet-stream"},
1564   {".zip", 4, "application/x-zip-compressed"},
1565   {".xls", 4, "application/excel"},
1566   {".tgz", 4, "application/x-tar-gz"},
1567   {".tar", 4, "application/x-tar"},
1568   {".gz",  3, "application/x-gunzip"},
1569   {".arj", 4, "application/x-arj-compressed"},
1570   {".rar", 4, "application/x-rar-compressed"},
1571   {".rtf", 4, "application/rtf"},
1572   {".pdf", 4, "application/pdf"},
1573   {".swf", 4, "application/x-shockwave-flash"},
1574   {".mpg", 4, "video/mpeg"},
1575   {".webm", 5, "video/webm"},
1576   {".mpeg", 5, "video/mpeg"},
1577   {".mov", 4, "video/quicktime"},
1578   {".mp4", 4, "video/mp4"},
1579   {".m4v", 4, "video/x-m4v"},
1580   {".asf", 4, "video/x-ms-asf"},
1581   {".avi", 4, "video/x-msvideo"},
1582   {".bmp", 4, "image/bmp"},
1583   {".ttf", 4, "application/x-font-ttf"},
1584   {NULL,  0, NULL}
1585 };
1586
1587 #ifdef MONGOOSE_ENABLE_THREADS
1588 void *mg_start_thread(void *(*f)(void *), void *p) {
1589   return ns_start_thread(f, p);
1590 }
1591 #endif  // MONGOOSE_ENABLE_THREADS
1592
1593 #ifndef MONGOOSE_NO_MMAP
1594 #ifdef _WIN32
1595 static void *mmap(void *addr, int64_t len, int prot, int flags, int fd,
1596                   int offset) {
1597   HANDLE fh = (HANDLE) _get_osfhandle(fd);
1598   HANDLE mh = CreateFileMapping(fh, 0, PAGE_READONLY, 0, 0, 0);
1599   void *p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, (size_t) len);
1600   CloseHandle(mh);
1601   return p;
1602 }
1603 #define munmap(x, y)  UnmapViewOfFile(x)
1604 #define MAP_FAILED NULL
1605 #define MAP_PRIVATE 0
1606 #define PROT_READ 0
1607 #elif defined(__OS2__)
1608 static void *mmap(void *addr, int64_t len, int prot, int flags, int fd,
1609                   int offset) {
1610   void *p;
1611
1612   int pos = lseek( fd, 0, SEEK_CUR ); /* Get a current position */
1613
1614   if (pos == -1)
1615     return NULL;
1616
1617   /* Seek to offset offset */
1618   if (lseek( fd, offset, SEEK_SET) == -1)
1619     return NULL;
1620
1621   p = malloc(len);
1622
1623   /* Read in a file */
1624   if (!p || read(fd, p, len) == -1) {
1625     free(p);
1626     p = NULL;
1627   }
1628
1629   /* Restore the position */
1630   lseek(fd, pos, SEEK_SET);
1631
1632   return p;
1633 }
1634 #define munmap(x, y)  free(x)
1635 #define MAP_FAILED NULL
1636 #define MAP_PRIVATE 0
1637 #define PROT_READ 0
1638 #else
1639 #include <sys/mman.h>
1640 #endif
1641
1642 void *mg_mmap(FILE *fp, size_t size) {
1643   void *p = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fileno(fp), 0);
1644   return p == MAP_FAILED ? NULL : p;
1645 }
1646
1647 void mg_munmap(void *p, size_t size) {
1648   munmap(p, size);
1649 }
1650 #endif  // MONGOOSE_NO_MMAP
1651
1652 #if defined(_WIN32) && !defined(MONGOOSE_NO_FILESYSTEM)
1653 // Encode 'path' which is assumed UTF-8 string, into UNICODE string.
1654 // wbuf and wbuf_len is a target buffer and its length.
1655 static void to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
1656   char buf[MAX_PATH_SIZE * 2], buf2[MAX_PATH_SIZE * 2], *p;
1657
1658   strncpy(buf, path, sizeof(buf));
1659   buf[sizeof(buf) - 1] = '\0';
1660
1661   // Trim trailing slashes. Leave backslash for paths like "X:\"
1662   p = buf + strlen(buf) - 1;
1663   while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
1664
1665   // Convert to Unicode and back. If doubly-converted string does not
1666   // match the original, something is fishy, reject.
1667   memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
1668   MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
1669   WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
1670                       NULL, NULL);
1671   if (strcmp(buf, buf2) != 0) {
1672     wbuf[0] = L'\0';
1673   }
1674 }
1675
1676 static int mg_stat(const char *path, file_stat_t *st) {
1677   wchar_t wpath[MAX_PATH_SIZE];
1678   to_wchar(path, wpath, ARRAY_SIZE(wpath));
1679   DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
1680   return _wstati64(wpath, st);
1681 }
1682
1683 static FILE *mg_fopen(const char *path, const char *mode) {
1684   wchar_t wpath[MAX_PATH_SIZE], wmode[10];
1685   to_wchar(path, wpath, ARRAY_SIZE(wpath));
1686   to_wchar(mode, wmode, ARRAY_SIZE(wmode));
1687   return _wfopen(wpath, wmode);
1688 }
1689
1690 static int mg_open(const char *path, int flag, int mode) {
1691   wchar_t wpath[MAX_PATH_SIZE];
1692   to_wchar(path, wpath, ARRAY_SIZE(wpath));
1693   return _wopen(wpath, flag, mode);
1694 }
1695 #endif // _WIN32 && !MONGOOSE_NO_FILESYSTEM
1696
1697 // A helper function for traversing a comma separated list of values.
1698 // It returns a list pointer shifted to the next value, or NULL if the end
1699 // of the list found.
1700 // Value is stored in val vector. If value has form "x=y", then eq_val
1701 // vector is initialized to point to the "y" part, and val vector length
1702 // is adjusted to point only to "x".
1703 static const char *next_option(const char *list, struct vec *val,
1704                                struct vec *eq_val) {
1705   if (list == NULL || *list == '\0') {
1706     // End of the list
1707     list = NULL;
1708   } else {
1709     val->ptr = list;
1710     if ((list = strchr(val->ptr, ',')) != NULL) {
1711       // Comma found. Store length and shift the list ptr
1712       val->len = list - val->ptr;
1713       list++;
1714     } else {
1715       // This value is the last one
1716       list = val->ptr + strlen(val->ptr);
1717       val->len = list - val->ptr;
1718     }
1719
1720     if (eq_val != NULL) {
1721       // Value has form "x=y", adjust pointers and lengths
1722       // so that val points to "x", and eq_val points to "y".
1723       eq_val->len = 0;
1724       eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);
1725       if (eq_val->ptr != NULL) {
1726         eq_val->ptr++;  // Skip over '=' character
1727         eq_val->len = val->ptr + val->len - eq_val->ptr;
1728         val->len = (eq_val->ptr - val->ptr) - 1;
1729       }
1730     }
1731   }
1732
1733   return list;
1734 }
1735
1736 // Like snprintf(), but never returns negative value, or a value
1737 // that is larger than a supplied buffer.
1738 static int mg_vsnprintf(char *buf, size_t buflen, const char *fmt, va_list ap) {
1739   int n;
1740   if (buflen < 1) return 0;
1741   n = vsnprintf(buf, buflen, fmt, ap);
1742   if (n < 0) {
1743     n = 0;
1744   } else if (n >= (int) buflen) {
1745     n = (int) buflen - 1;
1746   }
1747   buf[n] = '\0';
1748   return n;
1749 }
1750
1751 static int mg_snprintf(char *buf, size_t buflen, const char *fmt, ...) {
1752   va_list ap;
1753   int n;
1754   va_start(ap, fmt);
1755   n = mg_vsnprintf(buf, buflen, fmt, ap);
1756   va_end(ap);
1757   return n;
1758 }
1759
1760 // Check whether full request is buffered. Return:
1761 //   -1  if request is malformed
1762 //    0  if request is not yet fully buffered
1763 //   >0  actual request length, including last \r\n\r\n
1764 static int get_request_len(const char *s, size_t buf_len) {
1765   const unsigned char *buf = (unsigned char *) s;
1766   size_t i;
1767
1768   for (i = 0; i < buf_len; i++) {
1769     // Control characters are not allowed but >=128 are.
1770     // Abort scan as soon as one malformed character is found.
1771     if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
1772       return -1;
1773     } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
1774       return i + 2;
1775     } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
1776                buf[i + 2] == '\n') {
1777       return i + 3;
1778     }
1779   }
1780
1781   return 0;
1782 }
1783
1784 // Skip the characters until one of the delimiters characters found.
1785 // 0-terminate resulting word. Skip the rest of the delimiters if any.
1786 // Advance pointer to buffer to the next word. Return found 0-terminated word.
1787 static char *skip(char **buf, const char *delimiters) {
1788   char *p, *begin_word, *end_word, *end_delimiters;
1789
1790   begin_word = *buf;
1791   end_word = begin_word + strcspn(begin_word, delimiters);
1792   end_delimiters = end_word + strspn(end_word, delimiters);
1793
1794   for (p = end_word; p < end_delimiters; p++) {
1795     *p = '\0';
1796   }
1797
1798   *buf = end_delimiters;
1799
1800   return begin_word;
1801 }
1802
1803 // Parse HTTP headers from the given buffer, advance buffer to the point
1804 // where parsing stopped.
1805 static void parse_http_headers(char **buf, struct mg_connection *ri) {
1806   size_t i;
1807
1808   for (i = 0; i < ARRAY_SIZE(ri->http_headers); i++) {
1809     ri->http_headers[i].name = skip(buf, ": ");
1810     ri->http_headers[i].value = skip(buf, "\r\n");
1811     if (ri->http_headers[i].name[0] == '\0')
1812       break;
1813     ri->num_headers = i + 1;
1814   }
1815 }
1816
1817 static const char *status_code_to_str(int status_code) {
1818   switch (status_code) {
1819
1820     case 100: return "Continue";
1821     case 101: return "Switching Protocols";
1822     case 102: return "Processing";
1823
1824     case 200: return "OK";
1825     case 201: return "Created";
1826     case 202: return "Accepted";
1827     case 203: return "Non-Authoritative Information";
1828     case 204: return "No Content";
1829     case 205: return "Reset Content";
1830     case 206: return "Partial Content";
1831     case 207: return "Multi-Status";
1832     case 208: return "Already Reported";
1833     case 226: return "IM Used";
1834
1835     case 300: return "Multiple Choices";
1836     case 301: return "Moved Permanently";
1837     case 302: return "Found";
1838     case 303: return "See Other";
1839     case 304: return "Not Modified";
1840     case 305: return "Use Proxy";
1841     case 306: return "Switch Proxy";
1842     case 307: return "Temporary Redirect";
1843     case 308: return "Permanent Redirect";
1844
1845     case 400: return "Bad Request";
1846     case 401: return "Unauthorized";
1847     case 402: return "Payment Required";
1848     case 403: return "Forbidden";
1849     case 404: return "Not Found";
1850     case 405: return "Method Not Allowed";
1851     case 406: return "Not Acceptable";
1852     case 407: return "Proxy Authentication Required";
1853     case 408: return "Request Timeout";
1854     case 409: return "Conflict";
1855     case 410: return "Gone";
1856     case 411: return "Length Required";
1857     case 412: return "Precondition Failed";
1858     case 413: return "Payload Too Large";
1859     case 414: return "URI Too Long";
1860     case 415: return "Unsupported Media Type";
1861     case 416: return "Requested Range Not Satisfiable";
1862     case 417: return "Expectation Failed";
1863     case 418: return "I\'m a teapot";
1864     case 422: return "Unprocessable Entity";
1865     case 423: return "Locked";
1866     case 424: return "Failed Dependency";
1867     case 426: return "Upgrade Required";
1868     case 428: return "Precondition Required";
1869     case 429: return "Too Many Requests";
1870     case 431: return "Request Header Fields Too Large";
1871     case 451: return "Unavailable For Legal Reasons";
1872
1873     case 500: return "Internal Server Error";
1874     case 501: return "Not Implemented";
1875     case 502: return "Bad Gateway";
1876     case 503: return "Service Unavailable";
1877     case 504: return "Gateway Timeout";
1878     case 505: return "HTTP Version Not Supported";
1879     case 506: return "Variant Also Negotiates";
1880     case 507: return "Insufficient Storage";
1881     case 508: return "Loop Detected";
1882     case 510: return "Not Extended";
1883     case 511: return "Network Authentication Required";
1884
1885     default:  return "Server Error";
1886   }
1887 }
1888
1889 static int call_user(struct connection *conn, enum mg_event ev) {
1890   return conn != NULL && conn->server != NULL &&
1891     conn->server->event_handler != NULL ?
1892     conn->server->event_handler(&conn->mg_conn, ev) : MG_FALSE;
1893 }
1894
1895 static void send_http_error(struct connection *conn, int code,
1896                             const char *fmt, ...) {
1897   const char *message = status_code_to_str(code);
1898   const char *rewrites = conn->server->config_options[URL_REWRITES];
1899   char headers[200], body[200];
1900   struct vec a, b;
1901   va_list ap;
1902   int body_len, headers_len, match_code;
1903
1904   conn->mg_conn.status_code = code;
1905
1906   // Invoke error handler if it is set
1907   if (call_user(conn, MG_HTTP_ERROR) == MG_TRUE) {
1908     close_local_endpoint(conn);
1909     return;
1910   }
1911
1912   // Handle error code rewrites
1913   while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
1914     if ((match_code = atoi(a.ptr)) > 0 && match_code == code) {
1915       struct mg_connection *c = &conn->mg_conn;
1916       c->status_code = 302;
1917       mg_printf(c, "HTTP/1.1 %d Moved\r\n"
1918                 "Location: %.*s?code=%d&orig_uri=%s&query_string=%s\r\n\r\n",
1919                 c->status_code, b.len, b.ptr, code, c->uri,
1920                 c->query_string == NULL ? "" : c->query_string);
1921       close_local_endpoint(conn);
1922       return;
1923     }
1924   }
1925
1926   body_len = mg_snprintf(body, sizeof(body), "%d %s\n", code, message);
1927   if (fmt != NULL) {
1928     va_start(ap, fmt);
1929     body_len += mg_vsnprintf(body + body_len, sizeof(body) - body_len, fmt, ap);
1930     va_end(ap);
1931   }
1932   if ((code >= 300 && code <= 399) || code == 204) {
1933     // 3xx errors do not have body
1934     body_len = 0;
1935   }
1936   headers_len = mg_snprintf(headers, sizeof(headers),
1937                             "HTTP/1.1 %d %s\r\nContent-Length: %d\r\n"
1938                             "Content-Type: text/plain\r\n\r\n",
1939                             code, message, body_len);
1940   ns_send(conn->ns_conn, headers, headers_len);
1941   ns_send(conn->ns_conn, body, body_len);
1942   close_local_endpoint(conn);  // This will write to the log file
1943 }
1944
1945 static void write_chunk(struct connection *conn, const char *buf, int len) {
1946   char chunk_size[50];
1947   int n = mg_snprintf(chunk_size, sizeof(chunk_size), "%X\r\n", len);
1948   ns_send(conn->ns_conn, chunk_size, n);
1949   ns_send(conn->ns_conn, buf, len);
1950   ns_send(conn->ns_conn, "\r\n", 2);
1951 }
1952
1953 size_t mg_printf(struct mg_connection *conn, const char *fmt, ...) {
1954   va_list ap;
1955   int ret;
1956
1957   va_start(ap, fmt);
1958   ret = mg_vprintf(conn, fmt, ap);
1959   va_end(ap);
1960
1961   return ret;
1962 }
1963
1964 size_t mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap) {
1965   struct connection *c = MG_CONN_2_CONN(conn);
1966
1967   ns_vprintf(c->ns_conn, fmt, ap);
1968
1969   return c->ns_conn->send_iobuf.len;
1970 }
1971
1972 static void ns_forward(struct ns_connection *from, struct ns_connection *to) {
1973   DBG(("%p -> %p %lu bytes", from, to, (unsigned long)from->recv_iobuf.len));
1974   ns_send(to, from->recv_iobuf.buf, from->recv_iobuf.len);
1975   iobuf_remove(&from->recv_iobuf, from->recv_iobuf.len);
1976 }
1977
1978 #ifndef MONGOOSE_NO_CGI
1979 #ifdef _WIN32
1980 struct threadparam {
1981   sock_t s;
1982   HANDLE hPipe;
1983 };
1984
1985 static int wait_until_ready(sock_t sock, int for_read) {
1986   fd_set set;
1987   if ( (sock == INVALID_SOCKET) || (sock >= FD_SETSIZE) )
1988     return 0;
1989   FD_ZERO(&set);
1990   FD_SET(sock, &set);
1991   select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0);
1992   return 1;
1993 }
1994
1995 static void *push_to_stdin(void *arg) {
1996   struct threadparam *tp = (struct threadparam *)arg;
1997   int n, sent, stop = 0;
1998   DWORD k;
1999   char buf[IOBUF_SIZE];
2000
2001   while (!stop && wait_until_ready(tp->s, 1) &&
2002          (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
2003     if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
2004     for (sent = 0; !stop && sent < n; sent += k) {
2005       if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
2006     }
2007   }
2008   DBG(("%s", "FORWARDED EVERYTHING TO CGI"));
2009   CloseHandle(tp->hPipe);
2010   NS_FREE(tp);
2011   _endthread();
2012   return NULL;
2013 }
2014
2015 static void *pull_from_stdout(void *arg) {
2016   struct threadparam *tp = (struct threadparam *)arg;
2017   int k = 0, stop = 0;
2018   DWORD n, sent;
2019   char buf[IOBUF_SIZE];
2020
2021   while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
2022     for (sent = 0; !stop && sent < n; sent += k) {
2023       if (wait_until_ready(tp->s, 0) &&
2024           (k = send(tp->s, buf + sent, n - sent, 0)) <= 0) stop = 1;
2025     }
2026   }
2027   DBG(("%s", "EOF FROM CGI"));
2028   CloseHandle(tp->hPipe);
2029   shutdown(tp->s, 2);  // Without this, IO thread may get truncated data
2030   closesocket(tp->s);
2031   NS_FREE(tp);
2032   _endthread();
2033   return NULL;
2034 }
2035
2036 static void spawn_stdio_thread(sock_t sock, HANDLE hPipe,
2037                                void *(*func)(void *)) {
2038   struct threadparam *tp = (struct threadparam *)NS_MALLOC(sizeof(*tp));
2039   if (tp != NULL) {
2040     tp->s = sock;
2041     tp->hPipe = hPipe;
2042     mg_start_thread(func, tp);
2043   }
2044 }
2045
2046 static void abs_path(const char *utf8_path, char *abs_path, size_t len) {
2047   wchar_t buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE];
2048   to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
2049   GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
2050   WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
2051 }
2052
2053 static process_id_t start_process(char *interp, const char *cmd,
2054                                   const char *env, const char *envp[],
2055                                   const char *dir, sock_t sock) {
2056   STARTUPINFOW si;
2057   PROCESS_INFORMATION pi;
2058   HANDLE a[2], b[2], me = GetCurrentProcess();
2059   wchar_t wcmd[MAX_PATH_SIZE], full_dir[MAX_PATH_SIZE];
2060   char buf[MAX_PATH_SIZE], buf4[MAX_PATH_SIZE], buf5[MAX_PATH_SIZE],
2061        cmdline[MAX_PATH_SIZE], *p;
2062   DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
2063   FILE *fp;
2064
2065   memset(&si, 0, sizeof(si));
2066   memset(&pi, 0, sizeof(pi));
2067
2068   si.cb = sizeof(si);
2069   si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
2070   si.wShowWindow = SW_HIDE;
2071   si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
2072
2073   CreatePipe(&a[0], &a[1], NULL, 0);
2074   CreatePipe(&b[0], &b[1], NULL, 0);
2075   DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
2076   DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
2077
2078   if (interp == NULL && (fp = fopen(cmd, "r")) != NULL) {
2079     buf[0] = buf[1] = '\0';
2080     fgets(buf, sizeof(buf), fp);
2081     buf[sizeof(buf) - 1] = '\0';
2082     if (buf[0] == '#' && buf[1] == '!') {
2083       interp = buf + 2;
2084       for (p = interp + strlen(interp) - 1;
2085            isspace(* (uint8_t *) p) && p > interp; p--) *p = '\0';
2086     }
2087     fclose(fp);
2088   }
2089
2090   if (interp != NULL) {
2091     abs_path(interp, buf4, ARRAY_SIZE(buf4));
2092     interp = buf4;
2093   }
2094   abs_path(dir, buf5, ARRAY_SIZE(buf5));
2095   to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
2096   mg_snprintf(cmdline, sizeof(cmdline), "%s%s\"%s\"",
2097               interp ? interp : "", interp ? " " : "", cmd);
2098   to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
2099
2100   if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
2101                      (void *) env, full_dir, &si, &pi) != 0) {
2102     spawn_stdio_thread(sock, a[1], push_to_stdin);
2103     spawn_stdio_thread(sock, b[0], pull_from_stdout);
2104   } else {
2105     CloseHandle(a[1]);
2106     CloseHandle(b[0]);
2107     closesocket(sock);
2108   }
2109   DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
2110
2111   // Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE
2112   CloseHandle(si.hStdOutput);
2113   CloseHandle(si.hStdInput);
2114   //CloseHandle(pi.hThread);
2115   //CloseHandle(pi.hProcess);
2116
2117   return pi.hProcess;
2118 }
2119 #else
2120 static process_id_t start_process(const char *interp, const char *cmd,
2121                                   const char *env, const char *envp[],
2122                                   const char *dir, sock_t sock) {
2123   char buf[500];
2124   process_id_t pid = fork();
2125   (void) env;
2126
2127   if (pid == 0) {
2128     (void) chdir(dir);
2129     (void) dup2(sock, 0);
2130     (void) dup2(sock, 1);
2131     closesocket(sock);
2132
2133     // After exec, all signal handlers are restored to their default values,
2134     // with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
2135     // implementation, SIGCHLD's handler will leave unchanged after exec
2136     // if it was set to be ignored. Restore it to default action.
2137     signal(SIGCHLD, SIG_DFL);
2138
2139     if (interp == NULL) {
2140       execle(cmd, cmd, (char *) 0, envp); // Using (char *) 0 to avoid warning
2141     } else {
2142       execle(interp, interp, cmd, (char *) 0, envp);
2143     }
2144     snprintf(buf, sizeof(buf), "Status: 500\r\n\r\n"
2145              "500 Server Error: %s%s%s: %s", interp == NULL ? "" : interp,
2146              interp == NULL ? "" : " ", cmd, strerror(errno));
2147     send(1, buf, strlen(buf), 0);
2148     exit(EXIT_FAILURE);  // exec call failed
2149   }
2150
2151   return pid;
2152 }
2153 #endif  // _WIN32
2154
2155 // This structure helps to create an environment for the spawned CGI program.
2156 // Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
2157 // last element must be NULL.
2158 // However, on Windows there is a requirement that all these VARIABLE=VALUE\0
2159 // strings must reside in a contiguous buffer. The end of the buffer is
2160 // marked by two '\0' characters.
2161 // We satisfy both worlds: we create an envp array (which is vars), all
2162 // entries are actually pointers inside buf.
2163 struct cgi_env_block {
2164   struct mg_connection *conn;
2165   char buf[CGI_ENVIRONMENT_SIZE];       // Environment buffer
2166   const char *vars[MAX_CGI_ENVIR_VARS]; // char *envp[]
2167   int len;                              // Space taken
2168   int nvars;                            // Number of variables in envp[]
2169 };
2170
2171 // Append VARIABLE=VALUE\0 string to the buffer, and add a respective
2172 // pointer into the vars array.
2173 static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {
2174   int n, space;
2175   char *added;
2176   va_list ap;
2177
2178   // Calculate how much space is left in the buffer
2179   space = sizeof(block->buf) - block->len - 2;
2180   assert(space >= 0);
2181
2182   // Make a pointer to the free space int the buffer
2183   added = block->buf + block->len;
2184
2185   // Copy VARIABLE=VALUE\0 string into the free space
2186   va_start(ap, fmt);
2187   n = mg_vsnprintf(added, (size_t) space, fmt, ap);
2188   va_end(ap);
2189
2190   // Make sure we do not overflow buffer and the envp array
2191   if (n > 0 && n + 1 < space &&
2192       block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
2193     // Append a pointer to the added string into the envp array
2194     block->vars[block->nvars++] = added;
2195     // Bump up used length counter. Include \0 terminator
2196     block->len += n + 1;
2197   }
2198
2199   return added;
2200 }
2201
2202 static void addenv2(struct cgi_env_block *blk, const char *name) {
2203   const char *s;
2204   if ((s = getenv(name)) != NULL) addenv(blk, "%s=%s", name, s);
2205 }
2206
2207 static void prepare_cgi_environment(struct connection *conn,
2208                                     const char *prog,
2209                                     struct cgi_env_block *blk) {
2210   struct mg_connection *ri = &conn->mg_conn;
2211   const char *s, *slash;
2212   char *p, **opts = conn->server->config_options;
2213   int  i;
2214
2215   blk->len = blk->nvars = 0;
2216   blk->conn = ri;
2217
2218   if ((s = getenv("SERVER_NAME")) != NULL) {
2219     addenv(blk, "SERVER_NAME=%s", s);
2220   } else {
2221     addenv(blk, "SERVER_NAME=%s", ri->local_ip);
2222   }
2223   addenv(blk, "SERVER_ROOT=%s", opts[DOCUMENT_ROOT]);
2224   addenv(blk, "DOCUMENT_ROOT=%s", opts[DOCUMENT_ROOT]);
2225   addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MONGOOSE_VERSION);
2226
2227   // Prepare the environment block
2228   addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
2229   addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
2230   addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP
2231
2232   // TODO(lsm): fix this for IPv6 case
2233   //addenv(blk, "SERVER_PORT=%d", ri->remote_port);
2234
2235   addenv(blk, "REQUEST_METHOD=%s", ri->request_method);
2236   addenv(blk, "REMOTE_ADDR=%s", ri->remote_ip);
2237   addenv(blk, "REMOTE_PORT=%d", ri->remote_port);
2238   addenv(blk, "REQUEST_URI=%s%s%s", ri->uri,
2239          ri->query_string == NULL ? "" : "?",
2240          ri->query_string == NULL ? "" : ri->query_string);
2241
2242   // SCRIPT_NAME
2243   if (conn->path_info != NULL) {
2244     addenv(blk, "SCRIPT_NAME=%.*s",
2245            (int) (strlen(ri->uri) - strlen(conn->path_info)), ri->uri);
2246     addenv(blk, "PATH_INFO=%s", conn->path_info);
2247   } else {
2248     s = strrchr(prog, '/');
2249     slash = strrchr(ri->uri, '/');
2250     addenv(blk, "SCRIPT_NAME=%.*s%s",
2251            slash == NULL ? 0 : (int) (slash - ri->uri), ri->uri,
2252            s == NULL ? prog : s);
2253   }
2254
2255   addenv(blk, "SCRIPT_FILENAME=%s", prog);
2256   addenv(blk, "PATH_TRANSLATED=%s", prog);
2257   addenv(blk, "HTTPS=%s", conn->ns_conn->ssl != NULL ? "on" : "off");
2258
2259   if ((s = mg_get_header(ri, "Content-Type")) != NULL)
2260     addenv(blk, "CONTENT_TYPE=%s", s);
2261
2262   if (ri->query_string != NULL)
2263     addenv(blk, "QUERY_STRING=%s", ri->query_string);
2264
2265   if ((s = mg_get_header(ri, "Content-Length")) != NULL)
2266     addenv(blk, "CONTENT_LENGTH=%s", s);
2267
2268   addenv2(blk, "PATH");
2269   addenv2(blk, "TMP");
2270   addenv2(blk, "TEMP");
2271   addenv2(blk, "TMPDIR");
2272   addenv2(blk, "PERLLIB");
2273   addenv2(blk, ENV_EXPORT_TO_CGI);
2274
2275 #if defined(_WIN32)
2276   addenv2(blk, "COMSPEC");
2277   addenv2(blk, "SYSTEMROOT");
2278   addenv2(blk, "SystemDrive");
2279   addenv2(blk, "ProgramFiles");
2280   addenv2(blk, "ProgramFiles(x86)");
2281   addenv2(blk, "CommonProgramFiles(x86)");
2282 #else
2283   addenv2(blk, "LD_LIBRARY_PATH");
2284 #endif // _WIN32
2285
2286   // Add all headers as HTTP_* variables
2287   for (i = 0; i < ri->num_headers; i++) {
2288     p = addenv(blk, "HTTP_%s=%s",
2289         ri->http_headers[i].name, ri->http_headers[i].value);
2290
2291     // Convert variable name into uppercase, and change - to _
2292     for (; *p != '=' && *p != '\0'; p++) {
2293       if (*p == '-')
2294         *p = '_';
2295       *p = (char) toupper(* (unsigned char *) p);
2296     }
2297   }
2298
2299   blk->vars[blk->nvars++] = NULL;
2300   blk->buf[blk->len++] = '\0';
2301
2302   assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
2303   assert(blk->len > 0);
2304   assert(blk->len < (int) sizeof(blk->buf));
2305 }
2306
2307 static const char cgi_status[] = "HTTP/1.1 200 OK\r\n";
2308
2309 static void open_cgi_endpoint(struct connection *conn, const char *prog) {
2310   struct cgi_env_block blk;
2311   char dir[MAX_PATH_SIZE];
2312   const char *p;
2313   sock_t fds[2];
2314
2315   prepare_cgi_environment(conn, prog, &blk);
2316   // CGI must be executed in its own directory. 'dir' must point to the
2317   // directory containing executable program, 'p' must point to the
2318   // executable program name relative to 'dir'.
2319   if ((p = strrchr(prog, '/')) == NULL) {
2320     mg_snprintf(dir, sizeof(dir), "%s", ".");
2321   } else {
2322     mg_snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
2323   }
2324
2325   // Try to create socketpair in a loop until success. ns_socketpair()
2326   // can be interrupted by a signal and fail.
2327   // TODO(lsm): use sigaction to restart interrupted syscall
2328   do {
2329     ns_socketpair(fds);
2330   } while (fds[0] == INVALID_SOCKET);
2331
2332   if (start_process(conn->server->config_options[CGI_INTERPRETER],
2333                     prog, blk.buf, blk.vars, dir, fds[1]) != 0) {
2334     conn->endpoint_type = EP_CGI;
2335     conn->endpoint.nc = ns_add_sock(&conn->server->ns_mgr, fds[0],
2336                                     mg_ev_handler, conn);
2337     conn->endpoint.nc->flags |= MG_CGI_CONN;
2338     ns_send(conn->ns_conn, cgi_status, sizeof(cgi_status) - 1);
2339     conn->mg_conn.status_code = 200;
2340     conn->ns_conn->flags |= NSF_BUFFER_BUT_DONT_SEND;
2341     // Pass POST data to the CGI process
2342     conn->endpoint.nc->send_iobuf = conn->ns_conn->recv_iobuf;
2343     iobuf_init(&conn->ns_conn->recv_iobuf, 0);
2344   } else {
2345     closesocket(fds[0]);
2346     send_http_error(conn, 500, "start_process(%s) failed", prog);
2347   }
2348
2349 #ifndef _WIN32
2350   closesocket(fds[1]);  // On Windows, CGI stdio thread closes that socket
2351 #endif
2352 }
2353
2354 static void on_cgi_data(struct ns_connection *nc) {
2355   struct connection *conn = (struct connection *) nc->user_data;
2356   const char *status = "500";
2357   struct mg_connection c;
2358
2359   if (!conn) return;
2360
2361   // Copy CGI data from CGI socket to the client send buffer
2362   ns_forward(nc, conn->ns_conn);
2363
2364   // If reply has not been parsed yet, parse it
2365   if (conn->ns_conn->flags & NSF_BUFFER_BUT_DONT_SEND) {
2366     struct iobuf *io = &conn->ns_conn->send_iobuf;
2367     size_t s_len = sizeof(cgi_status) - 1;
2368     int len = get_request_len(io->buf + s_len, io->len - s_len);
2369     char buf[MAX_REQUEST_SIZE], *s = buf;
2370
2371     if (len == 0) return;
2372
2373     if (len < 0 || len > (int) sizeof(buf)) {
2374       len = io->len;
2375       iobuf_remove(io, io->len);
2376       send_http_error(conn, 500, "CGI program sent malformed headers: [%.*s]",
2377         len, io->buf);
2378     } else {
2379       memset(&c, 0, sizeof(c));
2380       memcpy(buf, io->buf + s_len, len);
2381       buf[len - 1] = '\0';
2382       parse_http_headers(&s, &c);
2383       if (mg_get_header(&c, "Location") != NULL) {
2384         status = "302";
2385       } else if ((status = (char *) mg_get_header(&c, "Status")) == NULL) {
2386         status = "200";
2387       }
2388       memcpy(io->buf + 9, status, 3);
2389       conn->mg_conn.status_code = atoi(status);
2390     }
2391     conn->ns_conn->flags &= ~NSF_BUFFER_BUT_DONT_SEND;
2392   }
2393 }
2394 #endif  // !MONGOOSE_NO_CGI
2395
2396 static char *mg_strdup(const char *str) {
2397   char *copy = (char *) NS_MALLOC(strlen(str) + 1);
2398   if (copy != NULL) {
2399     strcpy(copy, str);
2400   }
2401   return copy;
2402 }
2403
2404 static int isbyte(int n) {
2405   return n >= 0 && n <= 255;
2406 }
2407
2408 static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
2409   int n, a, b, c, d, slash = 32, len = 0;
2410
2411   if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
2412       sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
2413       isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&
2414       slash >= 0 && slash < 33) {
2415     len = n;
2416     *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
2417     *mask = slash ? 0xffffffffU << (32 - slash) : 0;
2418   }
2419
2420   return len;
2421 }
2422
2423 // Verify given socket address against the ACL.
2424 // Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
2425 static int check_acl(const char *acl, uint32_t remote_ip) {
2426   int allowed, flag;
2427   uint32_t net, mask;
2428   struct vec vec;
2429
2430   // If any ACL is set, deny by default
2431   allowed = acl == NULL ? '+' : '-';
2432
2433   while ((acl = next_option(acl, &vec, NULL)) != NULL) {
2434     flag = vec.ptr[0];
2435     if ((flag != '+' && flag != '-') ||
2436         parse_net(&vec.ptr[1], &net, &mask) == 0) {
2437       return -1;
2438     }
2439
2440     if (net == (remote_ip & mask)) {
2441       allowed = flag;
2442     }
2443   }
2444
2445   return allowed == '+';
2446 }
2447
2448 // Protect against directory disclosure attack by removing '..',
2449 // excessive '/' and '\' characters
2450 static void remove_double_dots_and_double_slashes(char *s) {
2451   char *p = s;
2452
2453   while (*s != '\0') {
2454     *p++ = *s++;
2455     if (s[-1] == '/' || s[-1] == '\\') {
2456       // Skip all following slashes, backslashes and double-dots
2457       while (s[0] != '\0') {
2458         if (s[0] == '/' || s[0] == '\\') { s++; }
2459         else if (s[0] == '.' && (s[1] == '/' || s[1] == '\\')) { s += 2; }
2460         else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') { s += 2; }
2461         else if (s[0] == '.' && s[1] == '.' && (s[2] == '/' || s[2] == '\\')) { s += 3; }
2462         else { break; }
2463       }
2464     }
2465   }
2466   *p = '\0';
2467 }
2468
2469 int mg_url_decode(const char *src, size_t src_len, char *dst,
2470                   size_t dst_len, int is_form_url_encoded) {
2471   size_t i, j = 0;
2472   int a, b;
2473 #define HEXTOI(x) (isdigit(x) ? (x) - '0' : (x) - 'W')
2474
2475   for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
2476     if (src[i] == '%' && i + 2 < src_len &&
2477         isxdigit(* (const unsigned char *) (src + i + 1)) &&
2478         isxdigit(* (const unsigned char *) (src + i + 2))) {
2479       a = tolower(* (const unsigned char *) (src + i + 1));
2480       b = tolower(* (const unsigned char *) (src + i + 2));
2481       dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
2482       i += 2;
2483     } else if (is_form_url_encoded && src[i] == '+') {
2484       dst[j] = ' ';
2485     } else {
2486       dst[j] = src[i];
2487     }
2488   }
2489
2490   dst[j] = '\0'; // Null-terminate the destination
2491
2492   return i >= src_len ? j : -1;
2493 }
2494
2495 static int is_valid_http_method(const char *s) {
2496   return !strcmp(s, "GET") || !strcmp(s, "POST") || !strcmp(s, "HEAD") ||
2497     !strcmp(s, "CONNECT") || !strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
2498     !strcmp(s, "OPTIONS") || !strcmp(s, "PROPFIND") || !strcmp(s, "MKCOL") ||
2499     !strcmp(s, "PATCH");
2500 }
2501
2502 // Parse HTTP request, fill in mg_request structure.
2503 // This function modifies the buffer by NUL-terminating
2504 // HTTP request components, header names and header values.
2505 // Note that len must point to the last \n of HTTP headers.
2506 static size_t parse_http_message(char *buf, size_t len,
2507                                  struct mg_connection *ri) {
2508   int is_request, n;
2509
2510   // Reset the connection. Make sure that we don't touch fields that are
2511   // set elsewhere: remote_ip, remote_port, server_param
2512   ri->request_method = ri->uri = ri->http_version = ri->query_string = NULL;
2513   ri->num_headers = ri->status_code = ri->is_websocket = ri->content_len = 0;
2514
2515   if (len < 1) return ~0;
2516
2517   buf[len - 1] = '\0';
2518
2519   // RFC says that all initial whitespaces should be ignored
2520   while (*buf != '\0' && isspace(* (unsigned char *) buf)) {
2521     buf++;
2522   }
2523   ri->request_method = skip(&buf, " ");
2524   ri->uri = skip(&buf, " ");
2525   ri->http_version = skip(&buf, "\r\n");
2526
2527   // HTTP message could be either HTTP request or HTTP response, e.g.
2528   // "GET / HTTP/1.0 ...." or  "HTTP/1.0 200 OK ..."
2529   is_request = is_valid_http_method(ri->request_method);
2530   if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) ||
2531       (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
2532     len = ~0;
2533   } else {
2534     if (is_request) {
2535       ri->http_version += 5;
2536     } else {
2537       ri->status_code = atoi(ri->uri);
2538     }
2539     parse_http_headers(&buf, ri);
2540
2541     if ((ri->query_string = strchr(ri->uri, '?')) != NULL) {
2542       *(char *) ri->query_string++ = '\0';
2543     }
2544     n = (int) strlen(ri->uri);
2545     mg_url_decode(ri->uri, n, (char *) ri->uri, n + 1, 0);
2546     if (*ri->uri == '/' || *ri->uri == '.') {
2547       remove_double_dots_and_double_slashes((char *) ri->uri);
2548     }
2549   }
2550
2551   return len;
2552 }
2553
2554 static int lowercase(const char *s) {
2555   return tolower(* (const unsigned char *) s);
2556 }
2557
2558 static int mg_strcasecmp(const char *s1, const char *s2) {
2559   int diff;
2560
2561   do {
2562     diff = lowercase(s1++) - lowercase(s2++);
2563   } while (diff == 0 && s1[-1] != '\0');
2564
2565   return diff;
2566 }
2567
2568 static int mg_strncasecmp(const char *s1, const char *s2, size_t len) {
2569   int diff = 0;
2570
2571   if (len > 0)
2572     do {
2573       diff = lowercase(s1++) - lowercase(s2++);
2574     } while (diff == 0 && s1[-1] != '\0' && --len > 0);
2575
2576   return diff;
2577 }
2578
2579 // Return HTTP header value, or NULL if not found.
2580 const char *mg_get_header(const struct mg_connection *ri, const char *s) {
2581   int i;
2582
2583   for (i = 0; i < ri->num_headers; i++)
2584     if (!mg_strcasecmp(s, ri->http_headers[i].name))
2585       return ri->http_headers[i].value;
2586
2587   return NULL;
2588 }
2589
2590 // Perform case-insensitive match of string against pattern
2591 int mg_match_prefix(const char *pattern, ssize_t pattern_len, const char *str) {
2592   const char *or_str;
2593   int len, res, i = 0, j = 0;
2594
2595   if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
2596     res = mg_match_prefix(pattern, or_str - pattern, str);
2597     return res > 0 ? res : mg_match_prefix(or_str + 1,
2598       (pattern + pattern_len) - (or_str + 1), str);
2599   }
2600
2601   for (; i < pattern_len; i++, j++) {
2602     if (pattern[i] == '?' && str[j] != '\0') {
2603       continue;
2604     } else if (pattern[i] == '$') {
2605       return str[j] == '\0' ? j : -1;
2606     } else if (pattern[i] == '*') {
2607       i++;
2608       if (pattern[i] == '*') {
2609         i++;
2610         len = (int) strlen(str + j);
2611       } else {
2612         len = (int) strcspn(str + j, "/");
2613       }
2614       if (i == pattern_len) {
2615         return j + len;
2616       }
2617       do {
2618         res = mg_match_prefix(pattern + i, pattern_len - i, str + j + len);
2619       } while (res == -1 && len-- > 0);
2620       return res == -1 ? -1 : j + res + len;
2621     } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
2622       return -1;
2623     }
2624   }
2625   return j;
2626 }
2627
2628 // This function prints HTML pages, and expands "{{something}}" blocks
2629 // inside HTML by calling appropriate callback functions.
2630 // Note that {{@path/to/file}} construct outputs embedded file's contents,
2631 // which provides SSI-like functionality.
2632 void mg_template(struct mg_connection *conn, const char *s,
2633                  struct mg_expansion *expansions) {
2634   int i, j, pos = 0, inside_marker = 0;
2635
2636   for (i = 0; s[i] != '\0'; i++) {
2637     if (inside_marker == 0 && !memcmp(&s[i], "{{", 2)) {
2638       if (i > pos) {
2639         mg_send_data(conn, &s[pos], i - pos);
2640       }
2641       pos = i;
2642       inside_marker = 1;
2643     }
2644     if (inside_marker == 1 && !memcmp(&s[i], "}}", 2)) {
2645       for (j = 0; expansions[j].keyword != NULL; j++) {
2646         const char *kw = expansions[j].keyword;
2647         if ((int) strlen(kw) == i - (pos + 2) &&
2648             memcmp(kw, &s[pos + 2], i - (pos + 2)) == 0) {
2649           expansions[j].handler(conn);
2650           pos = i + 2;
2651           break;
2652         }
2653       }
2654       inside_marker = 0;
2655     }
2656   }
2657   if (i > pos) {
2658     mg_send_data(conn, &s[pos], i - pos);
2659   }
2660 }
2661
2662 #ifndef MONGOOSE_NO_FILESYSTEM
2663 static int is_dav_request(const struct connection *conn) {
2664   const char *s = conn->mg_conn.request_method;
2665   return !strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
2666     !strcmp(s, "MKCOL") || !strcmp(s, "PROPFIND");
2667 }
2668
2669 static int must_hide_file(struct connection *conn, const char *path) {
2670   const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
2671   const char *pattern = conn->server->config_options[HIDE_FILES_PATTERN];
2672   return mg_match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 ||
2673     (pattern != NULL && mg_match_prefix(pattern, strlen(pattern), path) > 0);
2674 }
2675
2676 // Return 1 if real file has been found, 0 otherwise
2677 static int convert_uri_to_file_name(struct connection *conn, char *buf,
2678                                     size_t buf_len, file_stat_t *st) {
2679   struct vec a, b;
2680   const char *rewrites = conn->server->config_options[URL_REWRITES];
2681   const char *root =
2682 #ifndef MONGOOSE_NO_DAV
2683     is_dav_request(conn) && conn->server->config_options[DAV_ROOT] != NULL ?
2684     conn->server->config_options[DAV_ROOT] :
2685 #endif
2686     conn->server->config_options[DOCUMENT_ROOT];
2687 #ifndef MONGOOSE_NO_CGI
2688   const char *cgi_pat = conn->server->config_options[CGI_PATTERN];
2689   char *p;
2690 #endif
2691   const char *uri = conn->mg_conn.uri;
2692   const char *domain = mg_get_header(&conn->mg_conn, "Host");
2693   // Important: match_len has to be declared as int, unless rewrites break.
2694   int match_len, root_len = root == NULL ? 0 : strlen(root);
2695
2696   // Perform virtual hosting rewrites
2697   if (rewrites != NULL && domain != NULL) {
2698     const char *colon = strchr(domain, ':');
2699     size_t domain_len = colon == NULL ? strlen(domain) : colon - domain;
2700
2701     while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
2702       if (a.len > 1 && a.ptr[0] == '@' && a.len == domain_len + 1 &&
2703           mg_strncasecmp(a.ptr + 1, domain, domain_len) == 0) {
2704         root = b.ptr;
2705         root_len = b.len;
2706         break;
2707       }
2708     }
2709   }
2710
2711   // No filesystem access
2712   if (root == NULL || root_len == 0) return 0;
2713
2714   // Handle URL rewrites
2715   mg_snprintf(buf, buf_len, "%.*s%s", root_len, root, uri);
2716   rewrites = conn->server->config_options[URL_REWRITES];  // Re-initialize!
2717   while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
2718     if ((match_len = mg_match_prefix(a.ptr, a.len, uri)) > 0) {
2719       mg_snprintf(buf, buf_len, "%.*s%s", (int) b.len, b.ptr, uri + match_len);
2720       break;
2721     }
2722   }
2723
2724   if (stat(buf, st) == 0) return 1;
2725
2726 #ifndef MONGOOSE_NO_CGI
2727   // Support PATH_INFO for CGI scripts.
2728   for (p = buf + strlen(root) + 2; *p != '\0'; p++) {
2729     if (*p == '/') {
2730       *p = '\0';
2731       if (mg_match_prefix(cgi_pat, strlen(cgi_pat), buf) > 0 &&
2732           !stat(buf, st)) {
2733       DBG(("!!!! [%s]", buf));
2734         *p = '/';
2735         conn->path_info = mg_strdup(p);
2736         *p = '\0';
2737         return 1;
2738       }
2739       *p = '/';
2740     }
2741   }
2742 #endif
2743
2744   return 0;
2745 }
2746 #endif  // MONGOOSE_NO_FILESYSTEM
2747
2748 static int should_keep_alive(const struct mg_connection *conn) {
2749   struct connection *c = MG_CONN_2_CONN(conn);
2750   const char *method = conn->request_method;
2751   const char *http_version = conn->http_version;
2752   const char *header = mg_get_header(conn, "Connection");
2753   return method != NULL &&
2754     (!strcmp(method, "GET") || c->endpoint_type == EP_USER) &&
2755     ((header != NULL && !mg_strcasecmp(header, "keep-alive")) ||
2756      (header == NULL && http_version && !strcmp(http_version, "1.1")));
2757 }
2758
2759 size_t mg_write(struct mg_connection *c, const void *buf, size_t len) {
2760   struct connection *conn = MG_CONN_2_CONN(c);
2761   ns_send(conn->ns_conn, buf, len);
2762   return conn->ns_conn->send_iobuf.len;
2763 }
2764
2765 void mg_send_status(struct mg_connection *c, int status) {
2766   struct connection *conn = MG_CONN_2_CONN(c);
2767   if (c->status_code == 0) {
2768     c->status_code = status;
2769     mg_printf(c, "HTTP/1.1 %d %s\r\n", status, status_code_to_str(status));
2770   }
2771   conn->ns_conn->flags |= MG_USING_CHUNKED_API;
2772 }
2773
2774 void mg_send_header(struct mg_connection *c, const char *name, const char *v) {
2775   struct connection *conn = MG_CONN_2_CONN(c);
2776   if (c->status_code == 0) {
2777     c->status_code = 200;
2778     mg_printf(c, "HTTP/1.1 %d %s\r\n", 200, status_code_to_str(200));
2779   }
2780   mg_printf(c, "%s: %s\r\n", name, v);
2781   conn->ns_conn->flags |= MG_USING_CHUNKED_API;
2782 }
2783
2784 static void terminate_headers(struct mg_connection *c) {
2785   struct connection *conn = MG_CONN_2_CONN(c);
2786   if (!(conn->ns_conn->flags & MG_HEADERS_SENT)) {
2787     mg_send_header(c, "Transfer-Encoding", "chunked");
2788     mg_write(c, "\r\n", 2);
2789     conn->ns_conn->flags |= MG_HEADERS_SENT;
2790   }
2791 }
2792
2793 size_t mg_send_data(struct mg_connection *c, const void *data, int data_len) {
2794   struct connection *conn = MG_CONN_2_CONN(c);
2795   terminate_headers(c);
2796   write_chunk(MG_CONN_2_CONN(c), (const char *) data, data_len);
2797   return conn->ns_conn->send_iobuf.len;
2798 }
2799
2800 size_t mg_printf_data(struct mg_connection *c, const char *fmt, ...) {
2801   va_list ap;
2802   int ret;
2803
2804   va_start(ap, fmt);
2805   ret = mg_vprintf_data(c, fmt, ap);
2806   va_end(ap);
2807
2808   return ret;
2809 }
2810
2811 size_t mg_vprintf_data(struct mg_connection *c, const char *fmt, va_list ap) {
2812   struct connection *conn = MG_CONN_2_CONN(c);
2813   int len;
2814   char mem[IOBUF_SIZE], *buf = mem;
2815
2816   terminate_headers(c);
2817
2818   len = ns_avprintf(&buf, sizeof(mem), fmt, ap);
2819
2820   if (len >= 0) {
2821     write_chunk((struct connection *) conn, buf, len);
2822   }
2823   if (buf != mem && buf != NULL) {
2824     NS_FREE(buf);
2825   }
2826   return conn->ns_conn->send_iobuf.len;
2827 }
2828
2829 #if !defined(MONGOOSE_NO_WEBSOCKET) || !defined(MONGOOSE_NO_AUTH)
2830 static int is_big_endian(void) {
2831   static const int n = 1;
2832   return ((char *) &n)[0] == 0;
2833 }
2834 #endif
2835
2836 #ifndef MONGOOSE_NO_WEBSOCKET
2837 // START OF SHA-1 code
2838 // Copyright(c) By Steve Reid <steve@edmweb.com>
2839 #define SHA1HANDSOFF
2840 #if defined(__sun)
2841 #include "solarisfixes.h"
2842 #endif
2843
2844 union char64long16 { unsigned char c[64]; uint32_t l[16]; };
2845
2846 #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
2847
2848 static uint32_t blk0(union char64long16 *block, int i) {
2849   // Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN
2850   if (!is_big_endian()) {
2851     block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
2852       (rol(block->l[i], 8) & 0x00FF00FF);
2853   }
2854   return block->l[i];
2855 }
2856
2857 /* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
2858 #undef blk
2859 #undef R0
2860 #undef R1
2861 #undef R2
2862 #undef R3
2863 #undef R4
2864
2865 #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
2866     ^block->l[(i+2)&15]^block->l[i&15],1))
2867 #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30);
2868 #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
2869 #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
2870 #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
2871 #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
2872
2873 typedef struct {
2874     uint32_t state[5];
2875     uint32_t count[2];
2876     unsigned char buffer[64];
2877 } SHA1_CTX;
2878
2879 static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) {
2880   uint32_t a, b, c, d, e;
2881   union char64long16 block[1];
2882
2883   memcpy(block, buffer, 64);
2884   a = state[0];
2885   b = state[1];
2886   c = state[2];
2887   d = state[3];
2888   e = state[4];
2889   R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3);
2890   R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7);
2891   R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11);
2892   R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15);
2893   R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
2894   R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
2895   R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
2896   R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
2897   R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
2898   R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
2899   R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
2900   R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
2901   R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
2902   R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
2903   R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
2904   R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
2905   R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
2906   R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
2907   R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
2908   R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
2909   state[0] += a;
2910   state[1] += b;
2911   state[2] += c;
2912   state[3] += d;
2913   state[4] += e;
2914   // Erase working structures. The order of operations is important,
2915   // used to ensure that compiler doesn't optimize those out.
2916   memset(block, 0, sizeof(block));
2917   a = b = c = d = e = 0;
2918   (void) a; (void) b; (void) c; (void) d; (void) e;
2919 }
2920
2921 static void SHA1Init(SHA1_CTX *context) {
2922   context->state[0] = 0x67452301;
2923   context->state[1] = 0xEFCDAB89;
2924   context->state[2] = 0x98BADCFE;
2925   context->state[3] = 0x10325476;
2926   context->state[4] = 0xC3D2E1F0;
2927   context->count[0] = context->count[1] = 0;
2928 }
2929
2930 static void SHA1Update(SHA1_CTX *context, const unsigned char *data,
2931                        size_t len) {
2932   size_t i, j;
2933
2934   j = context->count[0];
2935   if ((context->count[0] += len << 3) < j)
2936     context->count[1]++;
2937   context->count[1] += (len>>29);
2938   j = (j >> 3) & 63;
2939   if ((j + len) > 63) {
2940     memcpy(&context->buffer[j], data, (i = 64-j));
2941     SHA1Transform(context->state, context->buffer);
2942     for ( ; i + 63 < len; i += 64) {
2943       SHA1Transform(context->state, &data[i]);
2944     }
2945     j = 0;
2946   }
2947   else i = 0;
2948   memcpy(&context->buffer[j], &data[i], len - i);
2949 }
2950
2951 static void SHA1Final(unsigned char digest[20], SHA1_CTX *context) {
2952   unsigned i;
2953   unsigned char finalcount[8], c;
2954
2955   for (i = 0; i < 8; i++) {
2956     finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
2957                                      >> ((3-(i & 3)) * 8) ) & 255);
2958   }
2959   c = 0200;
2960   SHA1Update(context, &c, 1);
2961   while ((context->count[0] & 504) != 448) {
2962     c = 0000;
2963     SHA1Update(context, &c, 1);
2964   }
2965   SHA1Update(context, finalcount, 8);
2966   for (i = 0; i < 20; i++) {
2967     digest[i] = (unsigned char)
2968       ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
2969   }
2970   memset(context, '\0', sizeof(*context));
2971   memset(&finalcount, '\0', sizeof(finalcount));
2972 }
2973 // END OF SHA1 CODE
2974
2975 static void base64_encode(const unsigned char *src, int src_len, char *dst) {
2976   static const char *b64 =
2977     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2978   int i, j, a, b, c;
2979
2980   for (i = j = 0; i < src_len; i += 3) {
2981     a = src[i];
2982     b = i + 1 >= src_len ? 0 : src[i + 1];
2983     c = i + 2 >= src_len ? 0 : src[i + 2];
2984
2985     dst[j++] = b64[a >> 2];
2986     dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
2987     if (i + 1 < src_len) {
2988       dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
2989     }
2990     if (i + 2 < src_len) {
2991       dst[j++] = b64[c & 63];
2992     }
2993   }
2994   while (j % 4 != 0) {
2995     dst[j++] = '=';
2996   }
2997   dst[j++] = '\0';
2998 }
2999
3000 static void send_websocket_handshake(struct mg_connection *conn,
3001                                      const char *key) {
3002   static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
3003   char buf[500], sha[20], b64_sha[sizeof(sha) * 2];
3004   SHA1_CTX sha_ctx;
3005
3006   mg_snprintf(buf, sizeof(buf), "%s%s", key, magic);
3007   SHA1Init(&sha_ctx);
3008   SHA1Update(&sha_ctx, (unsigned char *) buf, strlen(buf));
3009   SHA1Final((unsigned char *) sha, &sha_ctx);
3010   base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
3011   mg_snprintf(buf, sizeof(buf), "%s%s%s",
3012               "HTTP/1.1 101 Switching Protocols\r\n"
3013               "Upgrade: websocket\r\n"
3014               "Connection: Upgrade\r\n"
3015               "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n");
3016
3017   mg_write(conn, buf, strlen(buf));
3018 }
3019
3020 static size_t deliver_websocket_frame(struct connection *conn) {
3021   // Having buf unsigned char * is important, as it is used below in arithmetic
3022   unsigned char *buf = (unsigned char *) conn->ns_conn->recv_iobuf.buf;
3023   size_t i, len, buf_len = conn->ns_conn->recv_iobuf.len, frame_len = 0,
3024       mask_len = 0, header_len = 0, data_len = 0, buffered = 0;
3025
3026   if (buf_len >= 2) {
3027     len = buf[1] & 127;
3028     mask_len = buf[1] & 128 ? 4 : 0;
3029     if (len < 126 && buf_len >= mask_len) {
3030       data_len = len;
3031       header_len = 2 + mask_len;
3032     } else if (len == 126 && buf_len >= 4 + mask_len) {
3033       header_len = 4 + mask_len;
3034       data_len = ((((size_t) buf[2]) << 8) + buf[3]);
3035     } else if (buf_len >= 10 + mask_len) {
3036       header_len = 10 + mask_len;
3037       data_len = (size_t) (((uint64_t) htonl(* (uint32_t *) &buf[2])) << 32) +
3038         htonl(* (uint32_t *) &buf[6]);
3039     }
3040   }
3041
3042   frame_len = header_len + data_len;
3043   buffered = frame_len > 0 && frame_len <= buf_len;
3044
3045   if (buffered) {
3046     conn->mg_conn.content_len = data_len;
3047     conn->mg_conn.content = (char *) buf + header_len;
3048     conn->mg_conn.wsbits = buf[0];
3049
3050     // Apply mask if necessary
3051     if (mask_len > 0) {
3052       for (i = 0; i < data_len; i++) {
3053         buf[i + header_len] ^= (buf + header_len - mask_len)[i % 4];
3054       }
3055     }
3056
3057     // Call the handler and remove frame from the iobuf
3058     if (call_user(conn, MG_REQUEST) == MG_FALSE ||
3059         (buf[0] & 0x0f) == WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
3060       conn->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
3061     }
3062     iobuf_remove(&conn->ns_conn->recv_iobuf, frame_len);
3063   }
3064
3065   return buffered;
3066 }
3067
3068 size_t mg_websocket_write(struct mg_connection *conn, int opcode,
3069                           const char *data, size_t data_len) {
3070     unsigned char mem[4192], *copy = mem;
3071     size_t copy_len = 0;
3072
3073     /* Check overflow */
3074     if (data_len > ~(size_t)0 - (size_t)10) {
3075       return 0;
3076     }
3077
3078     if (data_len + 10 > sizeof(mem) &&
3079         (copy = (unsigned char *) NS_MALLOC(data_len + 10)) == NULL) {
3080       return 0;
3081     }
3082
3083     copy[0] = 0x80 + (opcode & 0x0f);
3084
3085     // Frame format: http://tools.ietf.org/html/rfc6455#section-5.2
3086     if (data_len < 126) {
3087       // Inline 7-bit length field
3088       copy[1] = data_len;
3089       memcpy(copy + 2, data, data_len);
3090       copy_len = 2 + data_len;
3091     } else if (data_len <= 0xFFFF) {
3092       // 16-bit length field
3093       copy[1] = 126;
3094       * (uint16_t *) (copy + 2) = (uint16_t) htons((uint16_t) data_len);
3095       memcpy(copy + 4, data, data_len);
3096       copy_len = 4 + data_len;
3097     } else {
3098       // 64-bit length field
3099       const uint32_t hi = htonl((uint32_t) ((uint64_t) data_len >> 32));
3100       const uint32_t lo = htonl(data_len & 0xffffffff);
3101       copy[1] = 127;
3102       memcpy(copy+2,&hi,sizeof(hi));
3103       memcpy(copy+6,&lo,sizeof(lo));
3104       memcpy(copy + 10, data, data_len);
3105       copy_len = 10 + data_len;
3106     }
3107
3108     if (copy_len > 0) {
3109       mg_write(conn, copy, copy_len);
3110     }
3111     if (copy != mem) {
3112       NS_FREE(copy);
3113     }
3114
3115     // If we send closing frame, schedule a connection to be closed after
3116     // data is drained to the client.
3117     if (opcode == WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
3118       MG_CONN_2_CONN(conn)->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
3119     }
3120
3121     return MG_CONN_2_CONN(conn)->ns_conn->send_iobuf.len;
3122 }
3123
3124 size_t mg_websocket_printf(struct mg_connection *conn, int opcode,
3125                            const char *fmt, ...) {
3126   char mem[4192], *buf = mem;
3127   va_list ap;
3128   int len;
3129
3130   va_start(ap, fmt);
3131   if ((len = ns_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
3132     mg_websocket_write(conn, opcode, buf, len);
3133   }
3134   va_end(ap);
3135
3136   if (buf != mem && buf != NULL) {
3137     NS_FREE(buf);
3138   }
3139
3140   return MG_CONN_2_CONN(conn)->ns_conn->send_iobuf.len;
3141 }
3142
3143 static void send_websocket_handshake_if_requested(struct mg_connection *conn) {
3144   const char *ver = mg_get_header(conn, "Sec-WebSocket-Version"),
3145         *key = mg_get_header(conn, "Sec-WebSocket-Key");
3146   if (ver != NULL && key != NULL) {
3147     conn->is_websocket = 1;
3148     if (call_user(MG_CONN_2_CONN(conn), MG_WS_HANDSHAKE) == MG_FALSE) {
3149       send_websocket_handshake(conn, key);
3150     }
3151     call_user(MG_CONN_2_CONN(conn), MG_WS_CONNECT);
3152   }
3153 }
3154
3155 static void ping_idle_websocket_connection(struct connection *conn, time_t t) {
3156   if (t - conn->ns_conn->last_io_time > MONGOOSE_USE_WEBSOCKET_PING_INTERVAL) {
3157     mg_websocket_write(&conn->mg_conn, WEBSOCKET_OPCODE_PING, "", 0);
3158   }
3159 }
3160 #else
3161 #define ping_idle_websocket_connection(conn, t)
3162 #endif // !MONGOOSE_NO_WEBSOCKET
3163
3164 static void write_terminating_chunk(struct connection *conn) {
3165   mg_write(&conn->mg_conn, "0\r\n\r\n", 5);
3166 }
3167
3168 static int call_request_handler(struct connection *conn) {
3169   int result;
3170   conn->mg_conn.content = conn->ns_conn->recv_iobuf.buf;
3171   if ((result = call_user(conn, MG_REQUEST)) == MG_TRUE) {
3172     if (conn->ns_conn->flags & MG_USING_CHUNKED_API) {
3173       terminate_headers(&conn->mg_conn);
3174       write_terminating_chunk(conn);
3175     }
3176     close_local_endpoint(conn);
3177   }
3178   return result;
3179 }
3180
3181 const char *mg_get_mime_type(const char *path, const char *default_mime_type) {
3182   const char *ext;
3183   size_t i, path_len;
3184
3185   path_len = strlen(path);
3186
3187   for (i = 0; static_builtin_mime_types[i].extension != NULL; i++) {
3188     ext = path + (path_len - static_builtin_mime_types[i].ext_len);
3189     if (path_len > static_builtin_mime_types[i].ext_len &&
3190         mg_strcasecmp(ext, static_builtin_mime_types[i].extension) == 0) {
3191       return static_builtin_mime_types[i].mime_type;
3192     }
3193   }
3194
3195   return default_mime_type;
3196 }
3197
3198 #ifndef MONGOOSE_NO_FILESYSTEM
3199 // Convert month to the month number. Return -1 on error, or month number
3200 static int get_month_index(const char *s) {
3201   static const char *month_names[] = {
3202     "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3203     "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3204   };
3205   int i;
3206
3207   for (i = 0; i < (int) ARRAY_SIZE(month_names); i++)
3208     if (!strcmp(s, month_names[i]))
3209       return i;
3210
3211   return -1;
3212 }
3213
3214 static int num_leap_years(int year) {
3215   return year / 4 - year / 100 + year / 400;
3216 }
3217
3218 // Parse UTC date-time string, and return the corresponding time_t value.
3219 static time_t parse_date_string(const char *datetime) {
3220   static const unsigned short days_before_month[] = {
3221     0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
3222   };
3223   char month_str[32];
3224   int second, minute, hour, day, month, year, leap_days, days;
3225   time_t result = (time_t) 0;
3226
3227   if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d",
3228                &day, month_str, &year, &hour, &minute, &second) == 6) ||
3229        (sscanf(datetime, "%d %3s %d %d:%d:%d",
3230                &day, month_str, &year, &hour, &minute, &second) == 6) ||
3231        (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",
3232                &day, month_str, &year, &hour, &minute, &second) == 6) ||
3233        (sscanf(datetime, "%d-%3s-%d %d:%d:%d",
3234                &day, month_str, &year, &hour, &minute, &second) == 6)) &&
3235       year > 1970 &&
3236       (month = get_month_index(month_str)) != -1) {
3237     leap_days = num_leap_years(year) - num_leap_years(1970);
3238     year -= 1970;
3239     days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
3240     result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
3241   }
3242
3243   return result;
3244 }
3245
3246 // Look at the "path" extension and figure what mime type it has.
3247 // Store mime type in the vector.
3248 static void get_mime_type(const struct mg_server *server, const char *path,
3249                           struct vec *vec) {
3250   struct vec ext_vec, mime_vec;
3251   const char *list, *ext;
3252   size_t path_len;
3253
3254   path_len = strlen(path);
3255
3256   // Scan user-defined mime types first, in case user wants to
3257   // override default mime types.
3258   list = server->config_options[EXTRA_MIME_TYPES];
3259   while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
3260     // ext now points to the path suffix
3261     ext = path + path_len - ext_vec.len;
3262     if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
3263       *vec = mime_vec;
3264       return;
3265     }
3266   }
3267
3268   vec->ptr = mg_get_mime_type(path, "text/plain");
3269   vec->len = strlen(vec->ptr);
3270 }
3271
3272 static const char *suggest_connection_header(const struct mg_connection *conn) {
3273   return should_keep_alive(conn) ? "keep-alive" : "close";
3274 }
3275
3276 static void construct_etag(char *buf, size_t buf_len, const file_stat_t *st) {
3277   mg_snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"",
3278               (unsigned long) st->st_mtime, (int64_t) st->st_size);
3279 }
3280
3281 // Return True if we should reply 304 Not Modified.
3282 static int is_not_modified(const struct connection *conn,
3283                            const file_stat_t *stp) {
3284   char etag[64];
3285   const char *ims = mg_get_header(&conn->mg_conn, "If-Modified-Since");
3286   const char *inm = mg_get_header(&conn->mg_conn, "If-None-Match");
3287   construct_etag(etag, sizeof(etag), stp);
3288   return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
3289     (ims != NULL && stp->st_mtime <= parse_date_string(ims));
3290 }
3291
3292 // For given directory path, substitute it to valid index file.
3293 // Return 0 if index file has been found, -1 if not found.
3294 // If the file is found, it's stats is returned in stp.
3295 static int find_index_file(struct connection *conn, char *path,
3296                            size_t path_len, file_stat_t *stp) {
3297   const char *list = conn->server->config_options[INDEX_FILES];
3298   file_stat_t st;
3299   struct vec filename_vec;
3300   size_t n = strlen(path);
3301   int found = 0;
3302
3303   // The 'path' given to us points to the directory. Remove all trailing
3304   // directory separator characters from the end of the path, and
3305   // then append single directory separator character.
3306   while (n > 0 && path[n - 1] == '/') {
3307     n--;
3308   }
3309   path[n] = '/';
3310
3311   // Traverse index files list. For each entry, append it to the given
3312   // path and see if the file exists. If it exists, break the loop
3313   while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
3314
3315     if (path_len <= n + 2) {
3316       continue;
3317     }
3318
3319     // Ignore too long entries that may overflow path buffer
3320     if (filename_vec.len > (path_len - (n + 2)))
3321       continue;
3322
3323     // Prepare full path to the index file
3324     strncpy(path + n + 1, filename_vec.ptr, filename_vec.len);
3325     path[n + 1 + filename_vec.len] = '\0';
3326
3327     //DBG(("[%s]", path));
3328
3329     // Does it exist?
3330     if (!stat(path, &st)) {
3331       // Yes it does, break the loop
3332       *stp = st;
3333       found = 1;
3334       break;
3335     }
3336   }
3337
3338   // If no index file exists, restore directory path
3339   if (!found) {
3340     path[n] = '/';
3341     path[n + 1] = '\0';
3342   }
3343
3344   return found;
3345 }
3346
3347 static int parse_range_header(const char *header, int64_t *a, int64_t *b) {
3348   return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
3349 }
3350
3351 static void gmt_time_string(char *buf, size_t buf_len, time_t *t) {
3352   strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
3353 }
3354
3355 static void open_file_endpoint(struct connection *conn, const char *path,
3356                                file_stat_t *st, const char *extra_headers) {
3357   char date[64], lm[64], etag[64], range[64], headers[1000];
3358   const char *msg = "OK", *hdr;
3359   time_t t, curtime = time(NULL);
3360   int64_t r1, r2;
3361   struct vec mime_vec;
3362   int n;
3363
3364   conn->endpoint_type = EP_FILE;
3365   ns_set_close_on_exec(conn->endpoint.fd);
3366   conn->mg_conn.status_code = 200;
3367
3368   get_mime_type(conn->server, path, &mime_vec);
3369   conn->cl = st->st_size;
3370   range[0] = '\0';
3371
3372   // If Range: header specified, act accordingly
3373   r1 = r2 = 0;
3374   hdr = mg_get_header(&conn->mg_conn, "Range");
3375   if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 &&
3376       r1 >= 0 && r2 >= 0) {
3377     conn->mg_conn.status_code = 206;
3378     conn->cl = n == 2 ? (r2 > conn->cl ? conn->cl : r2) - r1 + 1: conn->cl - r1;
3379     mg_snprintf(range, sizeof(range), "Content-Range: bytes "
3380                 "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
3381                 r1, r1 + conn->cl - 1, (int64_t) st->st_size);
3382     msg = "Partial Content";
3383     lseek(conn->endpoint.fd, r1, SEEK_SET);
3384   }
3385
3386   // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
3387   // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
3388   gmt_time_string(date, sizeof(date), &curtime);
3389   t = st->st_mtime; // store in local variable for NDK compile
3390   gmt_time_string(lm, sizeof(lm), &t);
3391   construct_etag(etag, sizeof(etag), st);
3392
3393   n = mg_snprintf(headers, sizeof(headers),
3394                   "HTTP/1.1 %d %s\r\n"
3395                   "Date: %s\r\n"
3396                   "Last-Modified: %s\r\n"
3397                   "Etag: %s\r\n"
3398                   "Content-Type: %.*s\r\n"
3399                   "Content-Length: %" INT64_FMT "\r\n"
3400                   "Connection: %s\r\n"
3401                   "Accept-Ranges: bytes\r\n"
3402                   "%s%s%s\r\n",
3403                   conn->mg_conn.status_code, msg, date, lm, etag,
3404                   (int) mime_vec.len, mime_vec.ptr, conn->cl,
3405                   suggest_connection_header(&conn->mg_conn),
3406                   range, extra_headers == NULL ? "" : extra_headers,
3407                   MONGOOSE_USE_EXTRA_HTTP_HEADERS);
3408   ns_send(conn->ns_conn, headers, n);
3409
3410   if (!strcmp(conn->mg_conn.request_method, "HEAD")) {
3411     conn->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
3412     close(conn->endpoint.fd);
3413     conn->endpoint_type = EP_NONE;
3414   }
3415 }
3416
3417 void mg_send_file_data(struct mg_connection *c, int fd) {
3418   struct connection *conn = MG_CONN_2_CONN(c);
3419   conn->endpoint_type = EP_FILE;
3420   conn->endpoint.fd = fd;
3421   ns_set_close_on_exec(conn->endpoint.fd);
3422 }
3423 #endif  // MONGOOSE_NO_FILESYSTEM
3424
3425 static void call_request_handler_if_data_is_buffered(struct connection *conn) {
3426 #ifndef MONGOOSE_NO_WEBSOCKET
3427   if (conn->mg_conn.is_websocket) {
3428     do { } while (deliver_websocket_frame(conn));
3429   } else
3430 #endif
3431   if (conn->num_bytes_recv >= (conn->cl + conn->request_len) &&
3432       call_request_handler(conn) == MG_FALSE) {
3433     open_local_endpoint(conn, 1);
3434   }
3435 }
3436
3437 #if !defined(MONGOOSE_NO_DIRECTORY_LISTING) || !defined(MONGOOSE_NO_DAV)
3438
3439 #ifdef _WIN32
3440 struct dirent {
3441   char d_name[MAX_PATH_SIZE];
3442 };
3443
3444 typedef struct DIR {
3445   HANDLE   handle;
3446   WIN32_FIND_DATAW info;
3447   struct dirent result;
3448 } DIR;
3449
3450 // Implementation of POSIX opendir/closedir/readdir for Windows.
3451 static DIR *opendir(const char *name) {
3452   DIR *dir = NULL;
3453   wchar_t wpath[MAX_PATH_SIZE];
3454   DWORD attrs;
3455
3456   if (name == NULL) {
3457     SetLastError(ERROR_BAD_ARGUMENTS);
3458   } else if ((dir = (DIR *) NS_MALLOC(sizeof(*dir))) == NULL) {
3459     SetLastError(ERROR_NOT_ENOUGH_MEMORY);
3460   } else {
3461     to_wchar(name, wpath, ARRAY_SIZE(wpath));
3462     attrs = GetFileAttributesW(wpath);
3463     if (attrs != 0xFFFFFFFF &&
3464         ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
3465       (void) wcscat(wpath, L"\\*");
3466       dir->handle = FindFirstFileW(wpath, &dir->info);
3467       dir->result.d_name[0] = '\0';
3468     } else {
3469       NS_FREE(dir);
3470       dir = NULL;
3471     }
3472   }
3473
3474   return dir;
3475 }
3476
3477 static int closedir(DIR *dir) {
3478   int result = 0;
3479
3480   if (dir != NULL) {
3481     if (dir->handle != INVALID_HANDLE_VALUE)
3482       result = FindClose(dir->handle) ? 0 : -1;
3483
3484     NS_FREE(dir);
3485   } else {
3486     result = -1;
3487     SetLastError(ERROR_BAD_ARGUMENTS);
3488   }
3489
3490   return result;
3491 }
3492
3493 static struct dirent *readdir(DIR *dir) {
3494   struct dirent *result = 0;
3495
3496   if (dir) {
3497     if (dir->handle != INVALID_HANDLE_VALUE) {
3498       result = &dir->result;
3499       (void) WideCharToMultiByte(CP_UTF8, 0,
3500           dir->info.cFileName, -1, result->d_name,
3501           sizeof(result->d_name), NULL, NULL);
3502
3503       if (!FindNextFileW(dir->handle, &dir->info)) {
3504         (void) FindClose(dir->handle);
3505         dir->handle = INVALID_HANDLE_VALUE;
3506       }
3507
3508     } else {
3509       SetLastError(ERROR_FILE_NOT_FOUND);
3510     }
3511   } else {
3512     SetLastError(ERROR_BAD_ARGUMENTS);
3513   }
3514
3515   return result;
3516 }
3517 #endif // _WIN32  POSIX opendir/closedir/readdir implementation
3518
3519 static int scan_directory(struct connection *conn, const char *dir,
3520                           struct dir_entry **arr) {
3521   char path[MAX_PATH_SIZE];
3522   struct dir_entry *p;
3523   struct dirent *dp;
3524   int arr_size = 0, arr_ind = 0, inc = 100;
3525   DIR *dirp;
3526
3527   *arr = NULL;
3528   if ((dirp = (opendir(dir))) == NULL) return 0;
3529
3530   while ((dp = readdir(dirp)) != NULL) {
3531     // Do not show current dir and hidden files
3532     if (!strcmp(dp->d_name, ".") ||
3533         !strcmp(dp->d_name, "..") ||
3534         must_hide_file(conn, dp->d_name)) {
3535       continue;
3536     }
3537     mg_snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
3538
3539     // Resize the array if necessary
3540     if (arr_ind >= arr_size) {
3541       if ((p = (struct dir_entry *)
3542            NS_REALLOC(*arr, (inc + arr_size) * sizeof(**arr))) != NULL) {
3543         // Memset new chunk to zero, otherwise st_mtime will have garbage which
3544         // can make strftime() segfault, see
3545         // http://code.google.com/p/mongoose/issues/detail?id=79
3546         memset(p + arr_size, 0, sizeof(**arr) * inc);
3547
3548         *arr = p;
3549         arr_size += inc;
3550       }
3551     }
3552
3553     if (arr_ind < arr_size) {
3554       (*arr)[arr_ind].conn = conn;
3555       (*arr)[arr_ind].file_name = strdup(dp->d_name);
3556       stat(path, &(*arr)[arr_ind].st);
3557       arr_ind++;
3558     }
3559   }
3560   closedir(dirp);
3561
3562   return arr_ind;
3563 }
3564
3565 size_t mg_url_encode(const char *src, size_t s_len, char *dst, size_t dst_len) {
3566   static const char *dont_escape = "._-$,;~()";
3567   static const char *hex = "0123456789abcdef";
3568   size_t i = 0, j = 0;
3569
3570   for (i = j = 0; dst_len > 0 && i < s_len && j + 2 < dst_len - 1; i++, j++) {
3571     if (isalnum(* (const unsigned char *) (src + i)) ||
3572         strchr(dont_escape, * (const unsigned char *) (src + i)) != NULL) {
3573       dst[j] = src[i];
3574     } else if (j + 3 < dst_len) {
3575       dst[j] = '%';
3576       dst[j + 1] = hex[(* (const unsigned char *) (src + i)) >> 4];
3577       dst[j + 2] = hex[(* (const unsigned char *) (src + i)) & 0xf];
3578       j += 2;
3579     }
3580   }
3581
3582   dst[j] = '\0';
3583   return j;
3584 }
3585 #endif  // !NO_DIRECTORY_LISTING || !MONGOOSE_NO_DAV
3586
3587 #ifndef MONGOOSE_NO_DIRECTORY_LISTING
3588
3589 static void print_dir_entry(const struct dir_entry *de) {
3590   char size[64], mod[64], href[MAX_PATH_SIZE * 3];
3591   int64_t fsize = de->st.st_size;
3592   int is_dir = S_ISDIR(de->st.st_mode);
3593   const char *slash = is_dir ? "/" : "";
3594   time_t t;
3595
3596   if (is_dir) {
3597     mg_snprintf(size, sizeof(size), "%s", "[DIRECTORY]");
3598   } else {
3599      // We use (signed) cast below because MSVC 6 compiler cannot
3600      // convert unsigned __int64 to double.
3601     if (fsize < 1024) {
3602       mg_snprintf(size, sizeof(size), "%d", (int) fsize);
3603     } else if (fsize < 0x100000) {
3604       mg_snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0);
3605     } else if (fsize < 0x40000000) {
3606       mg_snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576);
3607     } else {
3608       mg_snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824);
3609     }
3610   }
3611   t = de->st.st_mtime;  // store in local variable for NDK compile
3612   strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&t));
3613   mg_url_encode(de->file_name, strlen(de->file_name), href, sizeof(href));
3614   mg_printf_data(&de->conn->mg_conn,
3615                   "<tr><td><a href=\"%s%s\">%s%s</a></td>"
3616                   "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
3617                   href, slash, de->file_name, slash, mod, size);
3618 }
3619
3620 // Sort directory entries by size, or name, or modification time.
3621 // On windows, __cdecl specification is needed in case if project is built
3622 // with __stdcall convention. qsort always requires __cdels callback.
3623 static int __cdecl compare_dir_entries(const void *p1, const void *p2) {
3624   const struct dir_entry *a = (const struct dir_entry *) p1,
3625         *b = (const struct dir_entry *) p2;
3626   const char *qs = a->conn->mg_conn.query_string ?
3627     a->conn->mg_conn.query_string : "na";
3628   int cmp_result = 0;
3629
3630   if (S_ISDIR(a->st.st_mode) && !S_ISDIR(b->st.st_mode)) {
3631     return -1;  // Always put directories on top
3632   } else if (!S_ISDIR(a->st.st_mode) && S_ISDIR(b->st.st_mode)) {
3633     return 1;   // Always put directories on top
3634   } else if (*qs == 'n') {
3635     cmp_result = strcmp(a->file_name, b->file_name);
3636   } else if (*qs == 's') {
3637     cmp_result = a->st.st_size == b->st.st_size ? 0 :
3638       a->st.st_size > b->st.st_size ? 1 : -1;
3639   } else if (*qs == 'd') {
3640     cmp_result = a->st.st_mtime == b->st.st_mtime ? 0 :
3641       a->st.st_mtime > b->st.st_mtime ? 1 : -1;
3642   }
3643
3644   return qs[1] == 'd' ? -cmp_result : cmp_result;
3645 }
3646
3647 static void send_directory_listing(struct connection *conn, const char *dir) {
3648   struct dir_entry *arr = NULL;
3649   int i, num_entries, sort_direction = conn->mg_conn.query_string != NULL &&
3650     conn->mg_conn.query_string[1] == 'd' ? 'a' : 'd';
3651
3652   mg_send_header(&conn->mg_conn, "Transfer-Encoding", "chunked");
3653   mg_send_header(&conn->mg_conn, "Content-Type", "text/html; charset=utf-8");
3654
3655   mg_printf_data(&conn->mg_conn,
3656               "<html><head><title>Index of %s</title>"
3657               "<style>th {text-align: left;}</style></head>"
3658               "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
3659               "<tr><th><a href=\"?n%c\">Name</a></th>"
3660               "<th><a href=\"?d%c\">Modified</a></th>"
3661               "<th><a href=\"?s%c\">Size</a></th></tr>"
3662               "<tr><td colspan=\"3\"><hr></td></tr>",
3663               conn->mg_conn.uri, conn->mg_conn.uri,
3664               sort_direction, sort_direction, sort_direction);
3665
3666   num_entries = scan_directory(conn, dir, &arr);
3667   if (arr) {
3668       qsort(arr, num_entries, sizeof(arr[0]), compare_dir_entries);
3669       for (i = 0; i < num_entries; i++) {
3670         print_dir_entry(&arr[i]);
3671         NS_FREE(arr[i].file_name);
3672       }
3673       NS_FREE(arr);
3674   }
3675
3676   write_terminating_chunk(conn);
3677   close_local_endpoint(conn);
3678 }
3679 #endif  // MONGOOSE_NO_DIRECTORY_LISTING
3680
3681 #ifndef MONGOOSE_NO_DAV
3682 static void print_props(struct connection *conn, const char *uri,
3683                         file_stat_t *stp) {
3684   char mtime[64];
3685   time_t t = stp->st_mtime;  // store in local variable for NDK compile
3686   gmt_time_string(mtime, sizeof(mtime), &t);
3687   mg_printf(&conn->mg_conn,
3688       "<d:response>"
3689        "<d:href>%s</d:href>"
3690        "<d:propstat>"
3691         "<d:prop>"
3692          "<d:resourcetype>%s</d:resourcetype>"
3693          "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
3694          "<d:getlastmodified>%s</d:getlastmodified>"
3695         "</d:prop>"
3696         "<d:status>HTTP/1.1 200 OK</d:status>"
3697        "</d:propstat>"
3698       "</d:response>\n",
3699       uri, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "",
3700       (int64_t) stp->st_size, mtime);
3701 }
3702
3703 static void handle_propfind(struct connection *conn, const char *path,
3704                             file_stat_t *stp, int exists) {
3705   static const char header[] = "HTTP/1.1 207 Multi-Status\r\n"
3706     "Connection: close\r\n"
3707     "Content-Type: text/xml; charset=utf-8\r\n\r\n"
3708     "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
3709     "<d:multistatus xmlns:d='DAV:'>\n";
3710   static const char footer[] = "</d:multistatus>";
3711   const char *depth = mg_get_header(&conn->mg_conn, "Depth");
3712 #ifdef MONGOOSE_NO_DIRECTORY_LISTING
3713   const char *list_dir = "no";
3714 #else
3715   const char *list_dir = conn->server->config_options[ENABLE_DIRECTORY_LISTING];
3716 #endif
3717
3718   conn->mg_conn.status_code = 207;
3719
3720   // Print properties for the requested resource itself
3721   if (!exists) {
3722     conn->mg_conn.status_code = 404;
3723     mg_printf(&conn->mg_conn, "%s", "HTTP/1.1 404 Not Found\r\n\r\n");
3724   } else if (S_ISDIR(stp->st_mode) && mg_strcasecmp(list_dir, "yes") != 0) {
3725     conn->mg_conn.status_code = 403;
3726     mg_printf(&conn->mg_conn, "%s",
3727               "HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
3728   } else {
3729     ns_send(conn->ns_conn, header, sizeof(header) - 1);
3730     print_props(conn, conn->mg_conn.uri, stp);
3731
3732     if (S_ISDIR(stp->st_mode) &&
3733              (depth == NULL || strcmp(depth, "0") != 0)) {
3734       struct dir_entry *arr = NULL;
3735       int i, num_entries = scan_directory(conn, path, &arr);
3736
3737       for (i = 0; i < num_entries; i++) {
3738         char buf[MAX_PATH_SIZE * 3];
3739         struct dir_entry *de = &arr[i];
3740         mg_url_encode(de->file_name, strlen(de->file_name), buf, sizeof(buf));
3741         print_props(conn, buf, &de->st);
3742         NS_FREE(de->file_name);
3743       }
3744       NS_FREE(arr);
3745     }
3746     ns_send(conn->ns_conn, footer, sizeof(footer) - 1);
3747   }
3748
3749   close_local_endpoint(conn);
3750 }
3751
3752 static void handle_mkcol(struct connection *conn, const char *path) {
3753   int status_code = 500;
3754
3755   if (conn->mg_conn.content_len > 0) {
3756     status_code = 415;
3757   } else if (!mkdir(path, 0755)) {
3758     status_code = 201;
3759   } else if (errno == EEXIST) {
3760     status_code = 405;
3761   } else if (errno == EACCES) {
3762     status_code = 403;
3763   } else if (errno == ENOENT) {
3764     status_code = 409;
3765   }
3766   send_http_error(conn, status_code, NULL);
3767 }
3768
3769 static int remove_directory(const char *dir) {
3770   char path[MAX_PATH_SIZE];
3771   struct dirent *dp;
3772   file_stat_t st;
3773   DIR *dirp;
3774
3775   if ((dirp = opendir(dir)) == NULL) return 0;
3776
3777   while ((dp = readdir(dirp)) != NULL) {
3778     if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue;
3779     mg_snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
3780     stat(path, &st);
3781     if (S_ISDIR(st.st_mode)) {
3782       remove_directory(path);
3783     } else {
3784       remove(path);
3785     }
3786   }
3787   closedir(dirp);
3788   rmdir(dir);
3789
3790   return 1;
3791 }
3792
3793 static void handle_delete(struct connection *conn, const char *path) {
3794   file_stat_t st;
3795
3796   if (stat(path, &st) != 0) {
3797     send_http_error(conn, 404, NULL);
3798   } else if (S_ISDIR(st.st_mode)) {
3799     remove_directory(path);
3800     send_http_error(conn, 204, NULL);
3801   } else if (remove(path) == 0) {
3802     send_http_error(conn, 204, NULL);
3803   } else {
3804     send_http_error(conn, 423, NULL);
3805   }
3806 }
3807
3808 // For a given PUT path, create all intermediate subdirectories
3809 // for given path. Return 0 if the path itself is a directory,
3810 // or -1 on error, 1 if OK.
3811 static int put_dir(const char *path) {
3812   char buf[MAX_PATH_SIZE];
3813   const char *s, *p;
3814   file_stat_t st;
3815
3816   // Create intermediate directories if they do not exist
3817   for (s = p = path + 1; (p = strchr(s, '/')) != NULL; s = ++p) {
3818     if (p - path >= (int) sizeof(buf)) return -1; // Buffer overflow
3819     memcpy(buf, path, p - path);
3820     buf[p - path] = '\0';
3821     if (stat(buf, &st) != 0 && mkdir(buf, 0755) != 0) return -1;
3822     if (p[1] == '\0') return 0;  // Path is a directory itself
3823   }
3824
3825   return 1;
3826 }
3827
3828 static void handle_put(struct connection *conn, const char *path) {
3829   file_stat_t st;
3830   const char *range, *cl_hdr = mg_get_header(&conn->mg_conn, "Content-Length");
3831   int64_t r1, r2;
3832   int rc;
3833
3834   conn->mg_conn.status_code = !stat(path, &st) ? 200 : 201;
3835   if ((rc = put_dir(path)) == 0) {
3836     mg_printf(&conn->mg_conn, "HTTP/1.1 %d OK\r\n\r\n",
3837               conn->mg_conn.status_code);
3838     close_local_endpoint(conn);
3839   } else if (rc == -1) {
3840     send_http_error(conn, 500, "put_dir: %s", strerror(errno));
3841   } else if (cl_hdr == NULL) {
3842     send_http_error(conn, 411, NULL);
3843   } else if ((conn->endpoint.fd =
3844               open(path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0644)) < 0) {
3845     send_http_error(conn, 500, "open(%s): %s", path, strerror(errno));
3846   } else {
3847     DBG(("PUT [%s] %lu", path, (unsigned long) conn->ns_conn->recv_iobuf.len));
3848     conn->endpoint_type = EP_PUT;
3849     ns_set_close_on_exec(conn->endpoint.fd);
3850     range = mg_get_header(&conn->mg_conn, "Content-Range");
3851     conn->cl = to64(cl_hdr);
3852     r1 = r2 = 0;
3853     if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
3854       conn->mg_conn.status_code = 206;
3855       lseek(conn->endpoint.fd, r1, SEEK_SET);
3856       conn->cl = r2 > r1 ? r2 - r1 + 1: conn->cl - r1;
3857     }
3858     mg_printf(&conn->mg_conn, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n",
3859               conn->mg_conn.status_code);
3860   }
3861 }
3862
3863 static void forward_put_data(struct connection *conn) {
3864   struct iobuf *io = &conn->ns_conn->recv_iobuf;
3865   size_t k = conn->cl < (int64_t) io->len ? conn->cl : (int64_t) io->len;   // To write
3866   size_t n = write(conn->endpoint.fd, io->buf, k);   // Write them!
3867   if (n > 0) {
3868     iobuf_remove(io, n);
3869     conn->cl -= n;
3870   }
3871   if (conn->cl <= 0) {
3872     close_local_endpoint(conn);
3873   }
3874 }
3875 #endif //  MONGOOSE_NO_DAV
3876
3877 static void send_options(struct connection *conn) {
3878   conn->mg_conn.status_code = 200;
3879   mg_printf(&conn->mg_conn, "%s",
3880             "HTTP/1.1 200 OK\r\nAllow: GET, POST, HEAD, CONNECT, PUT, "
3881             "DELETE, OPTIONS, PROPFIND, MKCOL\r\nDAV: 1\r\n\r\n");
3882   close_local_endpoint(conn);
3883 }
3884
3885 #ifndef MONGOOSE_NO_AUTH
3886 void mg_send_digest_auth_request(struct mg_connection *c) {
3887   struct connection *conn = MG_CONN_2_CONN(c);
3888   c->status_code = 401;
3889   mg_printf(c,
3890             "HTTP/1.1 401 Unauthorized\r\n"
3891             "Content-Length: 0\r\n"
3892             "WWW-Authenticate: Digest qop=\"auth\", "
3893             "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
3894             conn->server->config_options[AUTH_DOMAIN],
3895             (unsigned long) time(NULL));
3896   close_local_endpoint(conn);
3897 }
3898
3899 // Use the global passwords file, if specified by auth_gpass option,
3900 // or search for .htpasswd in the requested directory.
3901 static FILE *open_auth_file(struct connection *conn, const char *path,
3902                             int is_directory) {
3903   char name[MAX_PATH_SIZE];
3904   const char *p, *gpass = conn->server->config_options[GLOBAL_AUTH_FILE];
3905   FILE *fp = NULL;
3906
3907   if (gpass != NULL) {
3908     // Use global passwords file
3909     fp = fopen(gpass, "r");
3910   } else if (is_directory) {
3911     mg_snprintf(name, sizeof(name), "%s%c%s", path, '/', PASSWORDS_FILE_NAME);
3912     fp = fopen(name, "r");
3913   } else {
3914     // Try to find .htpasswd in requested directory.
3915     if ((p = strrchr(path, '/')) == NULL) p = path;
3916     mg_snprintf(name, sizeof(name), "%.*s%c%s",
3917                 (int) (p - path), path, '/', PASSWORDS_FILE_NAME);
3918     fp = fopen(name, "r");
3919   }
3920
3921   return fp;
3922 }
3923
3924 #if !defined(HAVE_MD5) && !defined(MONGOOSE_NO_AUTH)
3925 /*
3926  * This code implements the MD5 message-digest algorithm.
3927  * The algorithm is due to Ron Rivest.  This code was
3928  * written by Colin Plumb in 1993, no copyright is claimed.
3929  * This code is in the public domain; do with it what you wish.
3930  *
3931  * Equivalent code is available from RSA Data Security, Inc.
3932  * This code has been tested against that, and is equivalent,
3933  * except that you don't need to include two pages of legalese
3934  * with every copy.
3935  *
3936  * To compute the message digest of a chunk of bytes, declare an
3937  * MD5Context structure, pass it to MD5Init, call MD5Update as
3938  * needed on buffers full of bytes, and then call MD5Final, which
3939  * will fill a supplied 16-byte array with the digest.
3940  */
3941
3942 typedef struct MD5Context {
3943   uint32_t buf[4];
3944   uint32_t bits[2];
3945   unsigned char in[64];
3946 } MD5_CTX;
3947
3948 static void byteReverse(unsigned char *buf, unsigned longs) {
3949   uint32_t t;
3950
3951   // Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN
3952   if (is_big_endian()) {
3953     do {
3954       t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
3955         ((unsigned) buf[1] << 8 | buf[0]);
3956       * (uint32_t *) buf = t;
3957       buf += 4;
3958     } while (--longs);
3959   }
3960 }
3961
3962 #define F1(x, y, z) (z ^ (x & (y ^ z)))
3963 #define F2(x, y, z) F1(z, x, y)
3964 #define F3(x, y, z) (x ^ y ^ z)
3965 #define F4(x, y, z) (y ^ (x | ~z))
3966
3967 #define MD5STEP(f, w, x, y, z, data, s) \
3968   ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
3969
3970 // Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
3971 // initialization constants.
3972 static void MD5Init(MD5_CTX *ctx) {
3973   ctx->buf[0] = 0x67452301;
3974   ctx->buf[1] = 0xefcdab89;
3975   ctx->buf[2] = 0x98badcfe;
3976   ctx->buf[3] = 0x10325476;
3977
3978   ctx->bits[0] = 0;
3979   ctx->bits[1] = 0;
3980 }
3981
3982 static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
3983   register uint32_t a, b, c, d;
3984
3985   a = buf[0];
3986   b = buf[1];
3987   c = buf[2];
3988   d = buf[3];
3989
3990   MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
3991   MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
3992   MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
3993   MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
3994   MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
3995   MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
3996   MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
3997   MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
3998   MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
3999   MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
4000   MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
4001   MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
4002   MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
4003   MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
4004   MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
4005   MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
4006
4007   MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
4008   MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
4009   MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
4010   MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
4011   MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
4012   MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
4013   MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
4014   MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
4015   MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
4016   MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
4017   MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
4018   MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
4019   MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
4020   MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
4021   MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
4022   MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
4023
4024   MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
4025   MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
4026   MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
4027   MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
4028   MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
4029   MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
4030   MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
4031   MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
4032   MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
4033   MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
4034   MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
4035   MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
4036   MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
4037   MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
4038   MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
4039   MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
4040
4041   MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
4042   MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
4043   MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
4044   MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
4045   MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
4046   MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
4047   MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
4048   MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
4049   MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
4050   MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
4051   MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
4052   MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
4053   MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
4054   MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
4055   MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
4056   MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
4057
4058   buf[0] += a;
4059   buf[1] += b;
4060   buf[2] += c;
4061   buf[3] += d;
4062 }
4063
4064 static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) {
4065   uint32_t t;
4066
4067   t = ctx->bits[0];
4068   if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
4069     ctx->bits[1]++;
4070   ctx->bits[1] += len >> 29;
4071
4072   t = (t >> 3) & 0x3f;
4073
4074   if (t) {
4075     unsigned char *p = (unsigned char *) ctx->in + t;
4076
4077     t = 64 - t;
4078     if (len < t) {
4079       memcpy(p, buf, len);
4080       return;
4081     }
4082     memcpy(p, buf, t);
4083     byteReverse(ctx->in, 16);
4084     MD5Transform(ctx->buf, (uint32_t *) ctx->in);
4085     buf += t;
4086     len -= t;
4087   }
4088
4089   while (len >= 64) {
4090     memcpy(ctx->in, buf, 64);
4091     byteReverse(ctx->in, 16);
4092     MD5Transform(ctx->buf, (uint32_t *) ctx->in);
4093     buf += 64;
4094     len -= 64;
4095   }
4096
4097   memcpy(ctx->in, buf, len);
4098 }
4099
4100 static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) {
4101   unsigned count;
4102   unsigned char *p;
4103   uint32_t *a;
4104
4105   count = (ctx->bits[0] >> 3) & 0x3F;
4106
4107   p = ctx->in + count;
4108   *p++ = 0x80;
4109   count = 64 - 1 - count;
4110   if (count < 8) {
4111     memset(p, 0, count);
4112     byteReverse(ctx->in, 16);
4113     MD5Transform(ctx->buf, (uint32_t *) ctx->in);
4114     memset(ctx->in, 0, 56);
4115   } else {
4116     memset(p, 0, count - 8);
4117   }
4118   byteReverse(ctx->in, 14);
4119
4120   a = (uint32_t *)ctx->in;
4121   a[14] = ctx->bits[0];
4122   a[15] = ctx->bits[1];
4123
4124   MD5Transform(ctx->buf, (uint32_t *) ctx->in);
4125   byteReverse((unsigned char *) ctx->buf, 4);
4126   memcpy(digest, ctx->buf, 16);
4127   memset((char *) ctx, 0, sizeof(*ctx));
4128 }
4129 #endif // !HAVE_MD5
4130
4131
4132
4133 // Stringify binary data. Output buffer must be twice as big as input,
4134 // because each byte takes 2 bytes in string representation
4135 static void bin2str(char *to, const unsigned char *p, size_t len) {
4136   static const char *hex = "0123456789abcdef";
4137
4138   for (; len--; p++) {
4139     *to++ = hex[p[0] >> 4];
4140     *to++ = hex[p[0] & 0x0f];
4141   }
4142   *to = '\0';
4143 }
4144
4145 // Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
4146 char *mg_md5(char buf[33], ...) {
4147   unsigned char hash[16];
4148   const char *p;
4149   va_list ap;
4150   MD5_CTX ctx;
4151
4152   MD5Init(&ctx);
4153
4154   va_start(ap, buf);
4155   while ((p = va_arg(ap, const char *)) != NULL) {
4156     MD5Update(&ctx, (const unsigned char *) p, (unsigned) strlen(p));
4157   }
4158   va_end(ap);
4159
4160   MD5Final(hash, &ctx);
4161   bin2str(buf, hash, sizeof(hash));
4162   return buf;
4163 }
4164
4165 // Check the user's password, return 1 if OK
4166 static int check_password(const char *method, const char *ha1, const char *uri,
4167                           const char *nonce, const char *nc, const char *cnonce,
4168                           const char *qop, const char *response) {
4169   char ha2[32 + 1], expected_response[32 + 1];
4170
4171 #if 0
4172   // Check for authentication timeout
4173   if ((unsigned long) time(NULL) - (unsigned long) to64(nonce) > 3600 * 2) {
4174     return 0;
4175   }
4176 #endif
4177
4178   mg_md5(ha2, method, ":", uri, NULL);
4179   mg_md5(expected_response, ha1, ":", nonce, ":", nc,
4180       ":", cnonce, ":", qop, ":", ha2, NULL);
4181
4182   return mg_strcasecmp(response, expected_response) == 0 ? MG_TRUE : MG_FALSE;
4183 }
4184
4185
4186 // Authorize against the opened passwords file. Return 1 if authorized.
4187 int mg_authorize_digest(struct mg_connection *c, FILE *fp) {
4188   struct connection *conn = MG_CONN_2_CONN(c);
4189   const char *hdr;
4190   char line[256], f_user[256], ha1[256], f_domain[256], user[100], nonce[100],
4191        uri[MAX_REQUEST_SIZE], cnonce[100], resp[100], qop[100], nc[100];
4192
4193   if (c == NULL || fp == NULL) return 0;
4194   if ((hdr = mg_get_header(c, "Authorization")) == NULL ||
4195       mg_strncasecmp(hdr, "Digest ", 7) != 0) return 0;
4196   if (!mg_parse_header(hdr, "username", user, sizeof(user))) return 0;
4197   if (!mg_parse_header(hdr, "cnonce", cnonce, sizeof(cnonce))) return 0;
4198   if (!mg_parse_header(hdr, "response", resp, sizeof(resp))) return 0;
4199   if (!mg_parse_header(hdr, "uri", uri, sizeof(uri))) return 0;
4200   if (!mg_parse_header(hdr, "qop", qop, sizeof(qop))) return 0;
4201   if (!mg_parse_header(hdr, "nc", nc, sizeof(nc))) return 0;
4202   if (!mg_parse_header(hdr, "nonce", nonce, sizeof(nonce))) return 0;
4203
4204   while (fgets(line, sizeof(line), fp) != NULL) {
4205     if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) == 3 &&
4206         !strcmp(user, f_user) &&
4207         // NOTE(lsm): due to a bug in MSIE, we do not compare URIs
4208         !strcmp(conn->server->config_options[AUTH_DOMAIN], f_domain))
4209       return check_password(c->request_method, ha1, uri,
4210                             nonce, nc, cnonce, qop, resp);
4211   }
4212   return MG_FALSE;
4213 }
4214
4215
4216 // Return 1 if request is authorised, 0 otherwise.
4217 static int is_authorized(struct connection *conn, const char *path,
4218                          int is_directory) {
4219   FILE *fp;
4220   int authorized = MG_TRUE;
4221
4222   if ((fp = open_auth_file(conn, path, is_directory)) != NULL) {
4223     authorized = mg_authorize_digest(&conn->mg_conn, fp);
4224     fclose(fp);
4225   }
4226
4227   return authorized;
4228 }
4229
4230 static int is_authorized_for_dav(struct connection *conn) {
4231   const char *auth_file = conn->server->config_options[DAV_AUTH_FILE];
4232   const char *method = conn->mg_conn.request_method;
4233   FILE *fp;
4234   int authorized = MG_FALSE;
4235
4236   // If dav_auth_file is not set, allow non-authorized PROPFIND
4237   if (method != NULL && !strcmp(method, "PROPFIND") && auth_file == NULL) {
4238     authorized = MG_TRUE;
4239   } else if (auth_file != NULL && (fp = fopen(auth_file, "r")) != NULL) {
4240     authorized = mg_authorize_digest(&conn->mg_conn, fp);
4241     fclose(fp);
4242   }
4243
4244   return authorized;
4245 }
4246 #endif // MONGOOSE_NO_AUTH
4247
4248 static int parse_header(const char *str, size_t str_len, const char *var_name,
4249                         char *buf, size_t buf_size) {
4250   int ch = ' ', ch1 = ',', len = 0;
4251   size_t n = strlen(var_name);
4252   const char *p, *end = str + str_len, *s = NULL;
4253
4254   if (buf != NULL && buf_size > 0) buf[0] = '\0';
4255
4256   // Find where variable starts
4257   for (s = str; s != NULL && s + n < end; s++) {
4258     if ((s == str || s[-1] == ch || s[-1] == ch1) && s[n] == '=' &&
4259         !memcmp(s, var_name, n)) break;
4260   }
4261
4262   if (s != NULL && &s[n + 1] < end) {
4263     s += n + 1;
4264     if (*s == '"' || *s == '\'') ch = ch1 = *s++;
4265     p = s;
4266     while (p < end && p[0] != ch && p[0] != ch1 && len < (int) buf_size) {
4267       if (ch == ch1 && p[0] == '\\' && p[1] == ch) p++;
4268       buf[len++] = *p++;
4269     }
4270     if (len >= (int) buf_size || (ch != ' ' && *p != ch)) {
4271       len = 0;
4272     } else {
4273       if (len > 0 && s[len - 1] == ',') len--;
4274       if (len > 0 && s[len - 1] == ';') len--;
4275       buf[len] = '\0';
4276     }
4277   }
4278
4279   return len;
4280 }
4281
4282 int mg_parse_header(const char *s, const char *var_name, char *buf,
4283                     size_t buf_size) {
4284   return parse_header(s, s == NULL ? 0 : strlen(s), var_name, buf, buf_size);
4285 }
4286
4287 #ifndef MONGOOSE_NO_SSI
4288 static void send_ssi_file(struct mg_connection *, const char *, FILE *, int);
4289
4290 static void send_file_data(struct mg_connection *conn, FILE *fp) {
4291   char buf[IOBUF_SIZE];
4292   size_t n;
4293   while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
4294     mg_write(conn, buf, n);
4295   }
4296 }
4297
4298 static void do_ssi_include(struct mg_connection *conn, const char *ssi,
4299                            char *tag, int include_level) {
4300   char file_name[IOBUF_SIZE], path[MAX_PATH_SIZE], *p;
4301   char **opts = (MG_CONN_2_CONN(conn))->server->config_options;
4302   FILE *fp;
4303
4304   // sscanf() is safe here, since send_ssi_file() also uses buffer
4305   // of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
4306   if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
4307     // File name is relative to the webserver root
4308     mg_snprintf(path, sizeof(path), "%s%c%s",
4309                 opts[DOCUMENT_ROOT], '/', file_name);
4310   } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
4311     // File name is relative to the webserver working directory
4312     // or it is absolute system path
4313     mg_snprintf(path, sizeof(path), "%s", file_name);
4314   } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
4315              sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
4316     // File name is relative to the current document
4317     mg_snprintf(path, sizeof(path), "%s", ssi);
4318     if ((p = strrchr(path, '/')) != NULL) {
4319       p[1] = '\0';
4320     }
4321     mg_snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s",
4322                 file_name);
4323   } else {
4324     mg_printf(conn, "Bad SSI #include: [%s]", tag);
4325     return;
4326   }
4327
4328   if ((fp = fopen(path, "rb")) == NULL) {
4329     mg_printf(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",
4330               tag, path, strerror(errno));
4331   } else {
4332     ns_set_close_on_exec(fileno(fp));
4333     if (mg_match_prefix(opts[SSI_PATTERN], strlen(opts[SSI_PATTERN]),
4334         path) > 0) {
4335       send_ssi_file(conn, path, fp, include_level + 1);
4336     } else {
4337       send_file_data(conn, fp);
4338     }
4339     fclose(fp);
4340   }
4341 }
4342
4343 #ifndef MONGOOSE_NO_POPEN
4344 static void do_ssi_exec(struct mg_connection *conn, char *tag) {
4345   char cmd[IOBUF_SIZE];
4346   FILE *fp;
4347
4348   if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
4349     mg_printf(conn, "Bad SSI #exec: [%s]", tag);
4350   } else if ((fp = popen(cmd, "r")) == NULL) {
4351     mg_printf(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(errno));
4352   } else {
4353     send_file_data(conn, fp);
4354     pclose(fp);
4355   }
4356 }
4357 #endif // !MONGOOSE_NO_POPEN
4358
4359 static void send_ssi_file(struct mg_connection *conn, const char *path,
4360                           FILE *fp, int include_level) {
4361   char buf[IOBUF_SIZE];
4362   int ch, offset, len, in_ssi_tag;
4363
4364   if (include_level > 10) {
4365     mg_printf(conn, "SSI #include level is too deep (%s)", path);
4366     return;
4367   }
4368
4369   in_ssi_tag = len = offset = 0;
4370   while ((ch = fgetc(fp)) != EOF) {
4371     if (in_ssi_tag && ch == '>') {
4372       in_ssi_tag = 0;
4373       buf[len++] = (char) ch;
4374       buf[len] = '\0';
4375       assert(len <= (int) sizeof(buf));
4376       if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
4377         // Not an SSI tag, pass it
4378         (void) mg_write(conn, buf, (size_t) len);
4379       } else {
4380         if (!memcmp(buf + 5, "include", 7)) {
4381           do_ssi_include(conn, path, buf + 12, include_level);
4382 #if !defined(MONGOOSE_NO_POPEN)
4383         } else if (!memcmp(buf + 5, "exec", 4)) {
4384           do_ssi_exec(conn, buf + 9);
4385 #endif // !NO_POPEN
4386         } else {
4387           mg_printf(conn, "%s: unknown SSI " "command: \"%s\"", path, buf);
4388         }
4389       }
4390       len = 0;
4391     } else if (in_ssi_tag) {
4392       if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
4393         // Not an SSI tag
4394         in_ssi_tag = 0;
4395       } else if (len == (int) sizeof(buf) - 2) {
4396         mg_printf(conn, "%s: SSI tag is too large", path);
4397         len = 0;
4398       }
4399       buf[len++] = ch & 0xff;
4400     } else if (ch == '<') {
4401       in_ssi_tag = 1;
4402       if (len > 0) {
4403         mg_write(conn, buf, (size_t) len);
4404       }
4405       len = 0;
4406       buf[len++] = ch & 0xff;
4407     } else {
4408       buf[len++] = ch & 0xff;
4409       if (len == (int) sizeof(buf)) {
4410         mg_write(conn, buf, (size_t) len);
4411         len = 0;
4412       }
4413     }
4414   }
4415
4416   // Send the rest of buffered data
4417   if (len > 0) {
4418     mg_write(conn, buf, (size_t) len);
4419   }
4420 }
4421
4422 static void handle_ssi_request(struct connection *conn, const char *path) {
4423   FILE *fp;
4424   struct vec mime_vec;
4425
4426   if ((fp = fopen(path, "rb")) == NULL) {
4427     send_http_error(conn, 500, "fopen(%s): %s", path, strerror(errno));
4428   } else {
4429     ns_set_close_on_exec(fileno(fp));
4430     get_mime_type(conn->server, path, &mime_vec);
4431     conn->mg_conn.status_code = 200;
4432     mg_printf(&conn->mg_conn,
4433               "HTTP/1.1 %d OK\r\n"
4434               "Content-Type: %.*s\r\n"
4435               "Connection: close\r\n\r\n",
4436               conn->mg_conn.status_code, (int) mime_vec.len, mime_vec.ptr);
4437     send_ssi_file(&conn->mg_conn, path, fp, 0);
4438     fclose(fp);
4439     close_local_endpoint(conn);
4440   }
4441 }
4442 #endif
4443
4444 static void proxy_request(struct ns_connection *pc, struct mg_connection *c) {
4445   int i, sent_close_header = 0;
4446
4447   ns_printf(pc, "%s %s%s%s HTTP/%s\r\n", c->request_method, c->uri,
4448             c->query_string ? "?" : "",
4449             c->query_string ? c->query_string : "",
4450             c->http_version);
4451   for (i = 0; i < c->num_headers; i++) {
4452     if (mg_strcasecmp(c->http_headers[i].name, "Connection") == 0) {
4453       // Force connection close, cause we don't parse proxy replies
4454       // therefore we don't know message boundaries
4455       ns_printf(pc, "%s: %s\r\n", "Connection", "close");
4456       sent_close_header = 1;
4457     } else {
4458       ns_printf(pc, "%s: %s\r\n", c->http_headers[i].name,
4459                 c->http_headers[i].value);
4460     }
4461   }
4462   if (!sent_close_header) {
4463     ns_printf(pc, "%s: %s\r\n", "Connection", "close");
4464   }
4465   ns_printf(pc, "%s", "\r\n");
4466   ns_send(pc, c->content, c->content_len);
4467
4468 }
4469
4470 #ifdef NS_ENABLE_SSL
4471 int mg_terminate_ssl(struct mg_connection *c, const char *cert) {
4472   static const char ok[] = "HTTP/1.0 200 OK\r\n\r\n";
4473   struct connection *conn = MG_CONN_2_CONN(c);
4474   SSL_CTX *ctx;
4475
4476   DBG(("%p MITM", conn));
4477   if ((ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) return 0;
4478
4479   SSL_CTX_use_certificate_file(ctx, cert, 1);
4480   SSL_CTX_use_PrivateKey_file(ctx, cert, 1);
4481   SSL_CTX_use_certificate_chain_file(ctx, cert);
4482
4483   // When clear-text reply is pushed to client, switch to SSL mode.
4484   // TODO(lsm): check for send() failure
4485   send(conn->ns_conn->sock, ok, sizeof(ok) - 1, 0);
4486   //DBG(("%p %lu %d SEND", c, (unsigned long) sizeof(ok) - 1, n));
4487   conn->ns_conn->send_iobuf.len = 0;
4488   conn->endpoint_type = EP_USER;  // To keep-alive in close_local_endpoint()
4489   close_local_endpoint(conn);     // Clean up current CONNECT request
4490   if ((conn->ns_conn->ssl = SSL_new(ctx)) != NULL) {
4491     SSL_set_fd(conn->ns_conn->ssl, conn->ns_conn->sock);
4492   }
4493   SSL_CTX_free(ctx);
4494   return 1;
4495 }
4496 #endif
4497
4498 int mg_forward(struct mg_connection *c, const char *addr) {
4499   static const char ok[] = "HTTP/1.1 200 OK\r\n\r\n";
4500   struct connection *conn = MG_CONN_2_CONN(c);
4501   struct ns_connection *pc;
4502
4503   if ((pc = ns_connect(&conn->server->ns_mgr, addr,
4504       mg_ev_handler, conn)) == NULL) {
4505     conn->ns_conn->flags |= NSF_CLOSE_IMMEDIATELY;
4506     return 0;
4507   }
4508
4509   // Interlink two connections
4510   pc->flags |= MG_PROXY_CONN;
4511   conn->endpoint_type = EP_PROXY;
4512   conn->endpoint.nc = pc;
4513   DBG(("%p [%s] [%s] -> %p %p", conn, c->uri, addr, pc, conn->ns_conn->ssl));
4514
4515   if (strcmp(c->request_method, "CONNECT") == 0) {
4516     // For CONNECT request, reply with 200 OK. Tunnel is established.
4517     // TODO(lsm): check for send() failure
4518     (void) send(conn->ns_conn->sock, ok, sizeof(ok) - 1, 0);
4519   } else {
4520     // Strip "http://host:port" part from the URI
4521     if (memcmp(c->uri, "http://", 7) == 0) c->uri += 7;
4522     while (*c->uri != '\0' && *c->uri != '/') c->uri++;
4523     proxy_request(pc, c);
4524   }
4525   return 1;
4526 }
4527
4528 static void proxify_connection(struct connection *conn) {
4529   char proto[10], host[500], cert[500], addr[1000];
4530   unsigned short port = 80;
4531   struct mg_connection *c = &conn->mg_conn;
4532   int n = 0;
4533   const char *url = c->uri;
4534
4535   proto[0] = host[0] = cert[0] = '\0';
4536   if (sscanf(url, "%499[^: ]:%hu%n", host, &port, &n) != 2 &&
4537       sscanf(url, "%9[a-z]://%499[^: ]:%hu%n", proto, host, &port, &n) != 3 &&
4538       sscanf(url, "%9[a-z]://%499[^/ ]%n", proto, host, &n) != 2) {
4539     n = 0;
4540   }
4541
4542   snprintf(addr, sizeof(addr), "%s://%s:%hu",
4543            conn->ns_conn->ssl != NULL ? "ssl" : "tcp", host, port);
4544   if (n <= 0 || !mg_forward(c, addr)) {
4545     conn->ns_conn->flags |= NSF_CLOSE_IMMEDIATELY;
4546   }
4547 }
4548
4549 #ifndef MONGOOSE_NO_FILESYSTEM
4550 void mg_send_file_internal(struct mg_connection *c, const char *file_name,
4551                            file_stat_t *st, int exists,
4552                            const char *extra_headers) {
4553   struct connection *conn = MG_CONN_2_CONN(c);
4554   char path[MAX_PATH_SIZE];
4555   const int is_directory = S_ISDIR(st->st_mode);
4556 #ifndef MONGOOSE_NO_CGI
4557   const char *cgi_pat = conn->server->config_options[CGI_PATTERN];
4558 #else
4559   const char *cgi_pat = DEFAULT_CGI_PATTERN;
4560 #endif
4561 #ifndef MONGOOSE_NO_DIRECTORY_LISTING
4562   const char *dir_lst = conn->server->config_options[ENABLE_DIRECTORY_LISTING];
4563 #else
4564   const char *dir_lst = "yes";
4565 #endif
4566
4567   mg_snprintf(path, sizeof(path), "%s", file_name);
4568
4569   if (!exists || must_hide_file(conn, path)) {
4570     send_http_error(conn, 404, NULL);
4571   } else if (is_directory &&
4572              conn->mg_conn.uri[strlen(conn->mg_conn.uri) - 1] != '/') {
4573     conn->mg_conn.status_code = 301;
4574     mg_printf(&conn->mg_conn, "HTTP/1.1 301 Moved Permanently\r\n"
4575               "Location: %s/\r\n\r\n", conn->mg_conn.uri);
4576     close_local_endpoint(conn);
4577   } else if (is_directory && !find_index_file(conn, path, sizeof(path), st)) {
4578     if (!mg_strcasecmp(dir_lst, "yes")) {
4579 #ifndef MONGOOSE_NO_DIRECTORY_LISTING
4580       send_directory_listing(conn, path);
4581 #else
4582       send_http_error(conn, 501, NULL);
4583 #endif
4584     } else {
4585       send_http_error(conn, 403, NULL);
4586     }
4587   } else if (mg_match_prefix(cgi_pat, strlen(cgi_pat), path) > 0) {
4588 #if !defined(MONGOOSE_NO_CGI)
4589     open_cgi_endpoint(conn, path);
4590 #else
4591     send_http_error(conn, 501, NULL);
4592 #endif // !MONGOOSE_NO_CGI
4593 #ifndef MONGOOSE_NO_SSI
4594   } else if (mg_match_prefix(conn->server->config_options[SSI_PATTERN],
4595                              strlen(conn->server->config_options[SSI_PATTERN]),
4596                              path) > 0) {
4597     handle_ssi_request(conn, path);
4598 #endif
4599   } else if (is_not_modified(conn, st)) {
4600     send_http_error(conn, 304, NULL);
4601   } else if ((conn->endpoint.fd = open(path, O_RDONLY | O_BINARY, 0)) != -1) {
4602     // O_BINARY is required for Windows, otherwise in default text mode
4603     // two bytes \r\n will be read as one.
4604     open_file_endpoint(conn, path, st, extra_headers);
4605   } else {
4606     send_http_error(conn, 404, NULL);
4607   }
4608 }
4609 void mg_send_file(struct mg_connection *c, const char *file_name,
4610                   const char *extra_headers) {
4611   file_stat_t st;
4612   const int exists = stat(file_name, &st) == 0;
4613   mg_send_file_internal(c, file_name, &st, exists, extra_headers);
4614 }
4615 #endif  // !MONGOOSE_NO_FILESYSTEM
4616
4617 static void open_local_endpoint(struct connection *conn, int skip_user) {
4618 #ifndef MONGOOSE_NO_FILESYSTEM
4619   char path[MAX_PATH_SIZE];
4620   file_stat_t st;
4621   int exists = 0;
4622 #endif
4623
4624   // If EP_USER was set in a prev call, reset it
4625   conn->endpoint_type = EP_NONE;
4626
4627 #ifndef MONGOOSE_NO_AUTH
4628   if (conn->server->event_handler && call_user(conn, MG_AUTH) == MG_FALSE) {
4629     mg_send_digest_auth_request(&conn->mg_conn);
4630     return;
4631   }
4632 #endif
4633
4634   // Call URI handler if one is registered for this URI
4635   if (skip_user == 0 && conn->server->event_handler != NULL) {
4636     conn->endpoint_type = EP_USER;
4637 #if MONGOOSE_POST_SIZE_LIMIT > 1
4638     {
4639       const char *cl = mg_get_header(&conn->mg_conn, "Content-Length");
4640       if ((strcmp(conn->mg_conn.request_method, "POST") == 0 ||
4641            strcmp(conn->mg_conn.request_method, "PUT") == 0) &&
4642           (cl == NULL || to64(cl) > MONGOOSE_POST_SIZE_LIMIT)) {
4643         send_http_error(conn, 500, "POST size > %lu",
4644                         (unsigned long) MONGOOSE_POST_SIZE_LIMIT);
4645       }
4646     }
4647 #endif
4648     return;
4649   }
4650
4651   if (strcmp(conn->mg_conn.request_method, "CONNECT") == 0 ||
4652       mg_strncasecmp(conn->mg_conn.uri, "http", 4) == 0) {
4653     const char *enp = conn->server->config_options[ENABLE_PROXY];
4654     if (enp == NULL || strcmp(enp, "yes") != 0) {
4655       send_http_error(conn, 405, NULL);
4656     } else {
4657       proxify_connection(conn);
4658     }
4659     return;
4660   }
4661
4662   if (!strcmp(conn->mg_conn.request_method, "OPTIONS")) {
4663     send_options(conn);
4664     return;
4665   }
4666
4667 #ifdef MONGOOSE_NO_FILESYSTEM
4668   send_http_error(conn, 404, NULL);
4669 #else
4670   exists = convert_uri_to_file_name(conn, path, sizeof(path), &st);
4671
4672   if (!strcmp(conn->mg_conn.request_method, "OPTIONS")) {
4673     send_options(conn);
4674   } else if (conn->server->config_options[DOCUMENT_ROOT] == NULL) {
4675     send_http_error(conn, 404, NULL);
4676 #ifndef MONGOOSE_NO_AUTH
4677   } else if ((!is_dav_request(conn) && !is_authorized(conn, path,
4678                exists && S_ISDIR(st.st_mode))) ||
4679              (is_dav_request(conn) && !is_authorized_for_dav(conn))) {
4680     mg_send_digest_auth_request(&conn->mg_conn);
4681     close_local_endpoint(conn);
4682 #endif
4683 #ifndef MONGOOSE_NO_DAV
4684   } else if (must_hide_file(conn, path)) {
4685     send_http_error(conn, 404, NULL);
4686   } else if (!strcmp(conn->mg_conn.request_method, "PROPFIND")) {
4687     handle_propfind(conn, path, &st, exists);
4688   } else if (!strcmp(conn->mg_conn.request_method, "MKCOL")) {
4689     handle_mkcol(conn, path);
4690   } else if (!strcmp(conn->mg_conn.request_method, "DELETE")) {
4691     handle_delete(conn, path);
4692   } else if (!strcmp(conn->mg_conn.request_method, "PUT")) {
4693     handle_put(conn, path);
4694 #endif
4695   } else {
4696     mg_send_file_internal(&conn->mg_conn, path, &st, exists, NULL);
4697   }
4698 #endif  // MONGOOSE_NO_FILESYSTEM
4699 }
4700
4701 static void send_continue_if_expected(struct connection *conn) {
4702   static const char expect_response[] = "HTTP/1.1 100 Continue\r\n\r\n";
4703   const char *expect_hdr = mg_get_header(&conn->mg_conn, "Expect");
4704
4705   if (expect_hdr != NULL && !mg_strcasecmp(expect_hdr, "100-continue")) {
4706     ns_send(conn->ns_conn, expect_response, sizeof(expect_response) - 1);
4707   }
4708 }
4709
4710 // Conform to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
4711 static int is_valid_uri(const char *uri) {
4712   unsigned short n;
4713   return uri[0] == '/' ||
4714     strcmp(uri, "*") == 0 ||            // OPTIONS method can use asterisk URI
4715     mg_strncasecmp(uri, "http", 4) == 0 || // Naive check for the absolute URI
4716     sscanf(uri, "%*[^ :]:%hu", &n) > 0; // CONNECT method can use host:port
4717 }
4718
4719 static void try_parse(struct connection *conn) {
4720   struct iobuf *io = &conn->ns_conn->recv_iobuf;
4721
4722   if (conn->request_len == 0 &&
4723       (conn->request_len = get_request_len(io->buf, io->len)) > 0) {
4724     // If request is buffered in, remove it from the iobuf. This is because
4725     // iobuf could be reallocated, and pointers in parsed request could
4726     // become invalid.
4727     conn->request = (char *) NS_MALLOC(conn->request_len);
4728     if (conn->request == NULL) {
4729       conn->ns_conn->flags |= NSF_CLOSE_IMMEDIATELY;
4730       return;
4731     }
4732     memcpy(conn->request, io->buf, conn->request_len);
4733     //DBG(("%p [%.*s]", conn, conn->request_len, conn->request));
4734     iobuf_remove(io, conn->request_len);
4735     conn->request_len = parse_http_message(conn->request, conn->request_len,
4736                                            &conn->mg_conn);
4737     if (conn->request_len > 0) {
4738       const char *cl_hdr = mg_get_header(&conn->mg_conn, "Content-Length");
4739       conn->cl = cl_hdr == NULL ? 0 : to64(cl_hdr);
4740       conn->mg_conn.content_len = (size_t) conn->cl;
4741     }
4742   }
4743 }
4744
4745 static void do_proxy(struct connection *conn) {
4746   if (0 && conn->request_len == 0) {
4747     try_parse(conn);
4748     DBG(("%p parsing -> %d", conn, conn->request_len));
4749     if (conn->request_len > 0 && call_user(conn, MG_REQUEST) == MG_FALSE) {
4750       proxy_request(conn->endpoint.nc, &conn->mg_conn);
4751     } else if (conn->request_len < 0) {
4752       ns_forward(conn->ns_conn, conn->endpoint.nc);
4753     }
4754   } else {
4755     DBG(("%p forwarding", conn));
4756     ns_forward(conn->ns_conn, conn->endpoint.nc);
4757   }
4758 }
4759
4760 static void on_recv_data(struct connection *conn) {
4761   struct iobuf *io = &conn->ns_conn->recv_iobuf;
4762   int n;
4763
4764   if (conn->endpoint_type == EP_PROXY) {
4765     if (conn->endpoint.nc != NULL) do_proxy(conn);
4766     return;
4767   }
4768
4769   try_parse(conn);
4770   DBG(("%p %d %lu %d", conn, conn->request_len, (unsigned long)io->len,
4771        conn->ns_conn->flags));
4772   if (conn->request_len < 0 ||
4773       (conn->request_len > 0 && !is_valid_uri(conn->mg_conn.uri))) {
4774     send_http_error(conn, 400, NULL);
4775   } else if (conn->request_len == 0 && io->len > MAX_REQUEST_SIZE) {
4776     send_http_error(conn, 413, NULL);
4777   } else if (conn->request_len > 0 &&
4778              strcmp(conn->mg_conn.http_version, "1.0") != 0 &&
4779              strcmp(conn->mg_conn.http_version, "1.1") != 0) {
4780     send_http_error(conn, 505, NULL);
4781   } else if (conn->request_len > 0 && conn->endpoint_type == EP_NONE) {
4782 #ifndef MONGOOSE_NO_WEBSOCKET
4783     send_websocket_handshake_if_requested(&conn->mg_conn);
4784 #endif
4785     send_continue_if_expected(conn);
4786     open_local_endpoint(conn, 0);
4787   }
4788
4789 #ifndef MONGOOSE_NO_CGI
4790   if (conn->endpoint_type == EP_CGI && conn->endpoint.nc != NULL) {
4791     ns_forward(conn->ns_conn, conn->endpoint.nc);
4792   }
4793 #endif
4794   if (conn->endpoint_type == EP_USER) {
4795     conn->mg_conn.content = io->buf;
4796     conn->mg_conn.content_len = io->len;
4797     n = call_user(conn, MG_RECV);
4798     if (n < 0) {
4799       conn->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
4800     } else if ((size_t) n <= io->len) {
4801       iobuf_remove(io, n);
4802     }
4803     call_request_handler_if_data_is_buffered(conn);
4804   }
4805 #ifndef MONGOOSE_NO_DAV
4806   if (conn->endpoint_type == EP_PUT && io->len > 0) {
4807     forward_put_data(conn);
4808   }
4809 #endif
4810 }
4811
4812 static void call_http_client_handler(struct connection *conn) {
4813   //conn->mg_conn.status_code = code;
4814   // For responses without Content-Lengh, use the whole buffer
4815   if (conn->cl == 0) {
4816     conn->mg_conn.content_len = conn->ns_conn->recv_iobuf.len;
4817   }
4818   conn->mg_conn.content = conn->ns_conn->recv_iobuf.buf;
4819   if (call_user(conn, MG_REPLY) == MG_FALSE) {
4820     conn->ns_conn->flags |= NSF_CLOSE_IMMEDIATELY;
4821   }
4822   iobuf_remove(&conn->ns_conn->recv_iobuf, conn->mg_conn.content_len);
4823   conn->mg_conn.status_code = 0;
4824   conn->cl = conn->num_bytes_recv = conn->request_len = 0;
4825   NS_FREE(conn->request);
4826   conn->request = NULL;
4827 }
4828
4829 static void process_response(struct connection *conn) {
4830   struct iobuf *io = &conn->ns_conn->recv_iobuf;
4831
4832   try_parse(conn);
4833   DBG(("%p %d %lu", conn, conn->request_len, (unsigned long)io->len));
4834   if (conn->request_len < 0 ||
4835       (conn->request_len == 0 && io->len > MAX_REQUEST_SIZE)) {
4836     call_http_client_handler(conn);
4837   } else if ((int64_t) io->len >= conn->cl) {
4838     call_http_client_handler(conn);
4839   }
4840 }
4841
4842 struct mg_connection *mg_connect(struct mg_server *server, const char *addr) {
4843   struct ns_connection *nsconn;
4844   struct connection *conn;
4845
4846   nsconn = ns_connect(&server->ns_mgr, addr, mg_ev_handler, NULL);
4847   if (nsconn == NULL) return 0;
4848
4849   if ((conn = (struct connection *) NS_CALLOC(1, sizeof(*conn))) == NULL) {
4850     nsconn->flags |= NSF_CLOSE_IMMEDIATELY;
4851     return 0;
4852   }
4853
4854   // Interlink two structs
4855   conn->ns_conn = nsconn;
4856   nsconn->user_data = conn;
4857
4858   conn->server = server;
4859   conn->endpoint_type = EP_CLIENT;
4860   //conn->handler = handler;
4861   conn->mg_conn.server_param = server->ns_mgr.user_data;
4862   conn->ns_conn->flags = NSF_CONNECTING;
4863
4864   return &conn->mg_conn;
4865 }
4866
4867 #ifndef MONGOOSE_NO_LOGGING
4868 static void log_header(const struct mg_connection *conn, const char *header,
4869                        FILE *fp) {
4870   const char *header_value;
4871
4872   if ((header_value = mg_get_header(conn, header)) == NULL) {
4873     (void) fprintf(fp, "%s", " -");
4874   } else {
4875     (void) fprintf(fp, " \"%s\"", header_value);
4876   }
4877 }
4878
4879 static void log_access(const struct connection *conn, const char *path) {
4880   const struct mg_connection *c = &conn->mg_conn;
4881   FILE *fp = (path == NULL) ?  NULL : fopen(path, "a+");
4882   char date[64], user[100];
4883   time_t now;
4884
4885   if (fp == NULL) return;
4886   now = time(NULL);
4887   strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", localtime(&now));
4888
4889   flockfile(fp);
4890   mg_parse_header(mg_get_header(&conn->mg_conn, "Authorization"), "username",
4891                   user, sizeof(user));
4892   fprintf(fp, "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d 0",
4893           c->remote_ip, user[0] == '\0' ? "-" : user, date,
4894           c->request_method ? c->request_method : "-",
4895           c->uri ? c->uri : "-", c->query_string ? "?" : "",
4896           c->query_string ? c->query_string : "",
4897           c->http_version, c->status_code);
4898   log_header(c, "Referer", fp);
4899   log_header(c, "User-Agent", fp);
4900   fputc('\n', fp);
4901   fflush(fp);
4902
4903   funlockfile(fp);
4904   fclose(fp);
4905 }
4906 #endif
4907
4908 static void close_local_endpoint(struct connection *conn) {
4909   struct mg_connection *c = &conn->mg_conn;
4910   // Must be done before free()
4911   int keep_alive = should_keep_alive(&conn->mg_conn) &&
4912     (conn->endpoint_type == EP_FILE || conn->endpoint_type == EP_USER);
4913   DBG(("%p %d %d %d", conn, conn->endpoint_type, keep_alive,
4914        conn->ns_conn->flags));
4915
4916   switch (conn->endpoint_type) {
4917     case EP_PUT:
4918     case EP_FILE:
4919       close(conn->endpoint.fd);
4920       break;
4921     case EP_CGI:
4922     case EP_PROXY:
4923       if (conn->endpoint.nc != NULL) {
4924         DBG(("%p %p %p :-)", conn, conn->ns_conn, conn->endpoint.nc));
4925         conn->endpoint.nc->flags |= NSF_CLOSE_IMMEDIATELY;
4926         conn->endpoint.nc->user_data = NULL;
4927       }
4928       break;
4929     default: break;
4930   }
4931
4932 #ifndef MONGOOSE_NO_LOGGING
4933   if (c->status_code > 0 && conn->endpoint_type != EP_CLIENT &&
4934       c->status_code != 400) {
4935     log_access(conn, conn->server->config_options[ACCESS_LOG_FILE]);
4936   }
4937 #endif
4938
4939   // Gobble possible POST data sent to the URI handler
4940   iobuf_free(&conn->ns_conn->recv_iobuf);
4941   NS_FREE(conn->request);
4942   NS_FREE(conn->path_info);
4943   conn->endpoint.nc = NULL;
4944   conn->request = conn->path_info = NULL;
4945
4946   conn->endpoint_type = EP_NONE;
4947   conn->cl = conn->num_bytes_recv = conn->request_len = 0;
4948   conn->ns_conn->flags &= ~(NSF_FINISHED_SENDING_DATA |
4949                             NSF_BUFFER_BUT_DONT_SEND | NSF_CLOSE_IMMEDIATELY |
4950                             MG_HEADERS_SENT | MG_USING_CHUNKED_API);
4951
4952   // Do not memset() the whole structure, as some of the fields
4953   // (IP addresses & ports, server_param) must survive. Nullify the rest.
4954   c->request_method = c->uri = c->http_version = c->query_string = NULL;
4955   c->num_headers = c->status_code = c->is_websocket = c->content_len = 0;
4956   c->connection_param = c->callback_param = NULL;
4957
4958   if (keep_alive) {
4959     on_recv_data(conn);  // Can call us recursively if pipelining is used
4960   } else {
4961     conn->ns_conn->flags |= conn->ns_conn->send_iobuf.len == 0 ?
4962       NSF_CLOSE_IMMEDIATELY : NSF_FINISHED_SENDING_DATA;
4963   }
4964 }
4965
4966 static void transfer_file_data(struct connection *conn) {
4967   char buf[IOBUF_SIZE];
4968   size_t n;
4969
4970   // If output buffer is too big, don't send anything. Wait until
4971   // mongoose drains already buffered data to the client.
4972   if (conn->ns_conn->send_iobuf.len > sizeof(buf) * 2) return;
4973
4974   // Do not send anyt
4975   n = read(conn->endpoint.fd, buf, conn->cl < (int64_t) sizeof(buf) ?
4976            (int) conn->cl : (int) sizeof(buf));
4977
4978   if (n <= 0) {
4979     close_local_endpoint(conn);
4980   } else if (n > 0) {
4981     conn->cl -= n;
4982     ns_send(conn->ns_conn, buf, n);
4983     if (conn->cl <= 0) {
4984       close_local_endpoint(conn);
4985     }
4986   }
4987 }
4988
4989 time_t mg_poll_server(struct mg_server *server, int milliseconds) {
4990   return ns_mgr_poll(&server->ns_mgr, milliseconds);
4991 }
4992
4993 void mg_destroy_server(struct mg_server **server) {
4994   if (server != NULL && *server != NULL) {
4995     struct mg_server *s = *server;
4996     int i;
4997
4998     ns_mgr_free(&s->ns_mgr);
4999     for (i = 0; i < (int) ARRAY_SIZE(s->config_options); i++) {
5000       NS_FREE(s->config_options[i]);  // It is OK to free(NULL)
5001     }
5002     NS_FREE(s);
5003     *server = NULL;
5004   }
5005 }
5006
5007 struct mg_connection *mg_next(struct mg_server *s, struct mg_connection *c) {
5008   struct ns_connection *nc = ns_next(&s->ns_mgr, c == NULL ? NULL :
5009                                      MG_CONN_2_CONN(c)->ns_conn);
5010   if (nc != NULL && nc->user_data != NULL) {
5011     return & ((struct connection *) nc->user_data)->mg_conn;
5012   } else {
5013     return NULL;
5014   }
5015 }
5016
5017 static int get_var(const char *data, size_t data_len, const char *name,
5018                    char *dst, size_t dst_len, int n) {
5019   const char *p, *e = data + data_len, *s;
5020   size_t name_len;
5021   int i = 0, len = -1;
5022
5023   if (dst == NULL || dst_len == 0) {
5024     len = -2;
5025   } else if (data == NULL || name == NULL || data_len == 0) {
5026     dst[0] = '\0';
5027   } else {
5028     name_len = strlen(name);
5029     dst[0] = '\0';
5030
5031     // data is "var1=val1&var2=val2...". Find variable first
5032     for (p = data; p + name_len < e; p++) {
5033       if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
5034           !mg_strncasecmp(name, p, name_len)) {
5035
5036         if (n != i++) continue;
5037
5038         // Point p to variable value
5039         p += name_len + 1;
5040
5041         // Point s to the end of the value
5042         s = (const char *) memchr(p, '&', (size_t)(e - p));
5043         if (s == NULL) {
5044           s = e;
5045         }
5046         assert(s >= p);
5047
5048         // Decode variable into destination buffer
5049         len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
5050
5051         // Redirect error code from -1 to -2 (destination buffer too small).
5052         if (len == -1) {
5053           len = -2;
5054         }
5055         break;
5056       }
5057     }
5058   }
5059
5060   return len;
5061 }
5062
5063 int mg_get_var_n(const struct mg_connection *conn, const char *name,
5064                char *dst, size_t dst_len, int n) {
5065   int len = get_var(conn->query_string, conn->query_string == NULL ? 0 :
5066                     strlen(conn->query_string), name, dst, dst_len, n);
5067   if (len == -1) {
5068     len = get_var(conn->content, conn->content_len, name, dst, dst_len, n);
5069   }
5070   return len;
5071 }
5072
5073 int mg_get_var(const struct mg_connection *conn, const char *name,
5074                char *dst, size_t dst_len) {
5075   return mg_get_var_n(conn, name, dst, dst_len, 0);
5076 }
5077
5078 static int get_line_len(const char *buf, int buf_len) {
5079   int len = 0;
5080   while (len < buf_len && buf[len] != '\n') len++;
5081   return buf[len] == '\n' ? len + 1: -1;
5082 }
5083
5084 int mg_parse_multipart(const char *buf, int buf_len,
5085                        char *var_name, int var_name_len,
5086                        char *file_name, int file_name_len,
5087                        const char **data, int *data_len) {
5088   static const char cd[] = "Content-Disposition: ";
5089   //struct mg_connection c;
5090   int hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
5091   //char *p;
5092
5093   if (buf == NULL || buf_len <= 0) return 0;
5094   if ((hl = get_request_len(buf, buf_len)) <= 0) return 0;
5095   if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
5096
5097   // Get boundary length
5098   bl = get_line_len(buf, buf_len);
5099
5100   // Loop through headers, fetch variable name and file name
5101   var_name[0] = file_name[0] = '\0';
5102   for (n = bl; (ll = get_line_len(buf + n, hl - n)) > 0; n += ll) {
5103     if (mg_strncasecmp(cd, buf + n, cdl) == 0) {
5104       parse_header(buf + n + cdl, ll - (cdl + 2), "name",
5105                    var_name, var_name_len);
5106       parse_header(buf + n + cdl, ll - (cdl + 2), "filename",
5107                    file_name, file_name_len);
5108     }
5109   }
5110
5111   // Scan body, search for terminating boundary
5112   for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
5113     if (buf[pos] == '-' && !memcmp(buf, &buf[pos], bl - 2)) {
5114       if (data_len != NULL) *data_len = (pos - 2) - hl;
5115       if (data != NULL) *data = buf + hl;
5116       return pos;
5117     }
5118   }
5119
5120   return 0;
5121 }
5122
5123 const char **mg_get_valid_option_names(void) {
5124   return static_config_options;
5125 }
5126
5127 void mg_copy_listeners(struct mg_server *s, struct mg_server *to) {
5128   struct ns_connection *c;
5129   for (c = ns_next(&s->ns_mgr, NULL); c != NULL; c = ns_next(&s->ns_mgr, c)) {
5130     struct ns_connection *tmp;
5131     if ((c->flags & NSF_LISTENING) &&
5132         (tmp = (struct ns_connection *) NS_MALLOC(sizeof(*tmp))) != NULL) {
5133       memcpy(tmp, c, sizeof(*tmp));
5134
5135 #if defined(NS_ENABLE_SSL) && defined(HEADER_SSL_H)
5136       /* OpenSSL only. See https://github.com/cesanta/mongoose/issues/441 */
5137       if (tmp->ssl_ctx != NULL) {
5138         tmp->ssl_ctx->references++;
5139       }
5140 #endif
5141
5142       tmp->mgr = &to->ns_mgr;
5143       ns_add_conn(tmp->mgr, tmp);
5144     }
5145   }
5146 }
5147
5148 static int get_option_index(const char *name) {
5149   int i;
5150
5151   for (i = 0; static_config_options[i * 2] != NULL; i++) {
5152     if (strcmp(static_config_options[i * 2], name) == 0) {
5153       return i;
5154     }
5155   }
5156   return -1;
5157 }
5158
5159 static void set_default_option_values(char **opts) {
5160   const char *value, **all_opts = mg_get_valid_option_names();
5161   int i;
5162
5163   for (i = 0; all_opts[i * 2] != NULL; i++) {
5164     value = all_opts[i * 2 + 1];
5165     if (opts[i] == NULL && value != NULL) {
5166       opts[i] = mg_strdup(value);
5167     }
5168   }
5169 }
5170
5171 const char *mg_set_option(struct mg_server *server, const char *name,
5172                           const char *value) {
5173   int ind = get_option_index(name);
5174   const char *error_msg = NULL;
5175   char **v = NULL;
5176
5177   if (ind < 0) return  "No such option";
5178   v = &server->config_options[ind];
5179
5180   // Return success immediately if setting to the same value
5181   if ((*v == NULL && value == NULL) ||
5182       (value != NULL && *v != NULL && !strcmp(value, *v))) {
5183     return NULL;
5184   }
5185
5186   if (*v != NULL) {
5187     NS_FREE(*v);
5188     *v = NULL;
5189   }
5190
5191   if (value == NULL || value[0] == '\0') return NULL;
5192
5193   *v = mg_strdup(value);
5194   DBG(("%s [%s]", name, *v));
5195
5196   if (ind == LISTENING_PORT) {
5197     char buf[500] = "";
5198     size_t n = 0;
5199     struct vec vec;
5200
5201     /*
5202      * Ports can be specified as 0, meaning that OS has to choose any
5203      * free port that is available. In order to pass chosen port number to
5204      * the user, we rewrite all 0 port to chosen values.
5205      */
5206     while ((value = next_option(value, &vec, NULL)) != NULL) {
5207       struct ns_connection *c = ns_bind(&server->ns_mgr, vec.ptr,
5208                                         mg_ev_handler, NULL);
5209       if (c == NULL) {
5210         error_msg = "Cannot bind to port";
5211         break;
5212       } else {
5213         char buf2[50], cert[100], ca[100];
5214         union socket_address sa;
5215         int proto, use_ssl;
5216
5217         ns_parse_address(vec.ptr, &sa, &proto, &use_ssl, cert, ca);
5218         ns_sock_to_str(c->sock, buf2, sizeof(buf2),
5219                        memchr(vec.ptr, ':', vec.len) == NULL ? 2 : 3);
5220
5221         n += snprintf(buf + n, sizeof(buf) - n, "%s%s%s%s%s%s%s",
5222                       n > 0 ? "," : "",
5223                       use_ssl ? "ssl://" : "",
5224                       buf2, cert[0] ? ":" : "", cert, ca[0] ? ":" : "", ca);
5225       }
5226     }
5227     buf[sizeof(buf) - 1] = '\0';
5228     NS_FREE(*v);
5229     *v = mg_strdup(buf);
5230 #ifndef MONGOOSE_NO_FILESYSTEM
5231   } else if (ind == HEXDUMP_FILE) {
5232     server->ns_mgr.hexdump_file = *v;
5233 #endif
5234 #if !defined(_WIN32) && !defined(MONGOOSE_NO_USER)
5235   } else if (ind == RUN_AS_USER) {
5236     struct passwd *pw;
5237     if ((pw = getpwnam(value)) == NULL) {
5238       error_msg = "Unknown user";
5239     } else if (setgid(pw->pw_gid) != 0) {
5240       error_msg = "setgid() failed";
5241     } else if (setuid(pw->pw_uid) != 0) {
5242       error_msg = "setuid() failed";
5243     }
5244 #endif
5245   }
5246
5247   return error_msg;
5248 }
5249
5250 static void set_ips(struct ns_connection *nc, int is_rem) {
5251   struct connection *conn = (struct connection *) nc->user_data;
5252   struct mg_connection *c = &conn->mg_conn;
5253   char buf[100];
5254
5255   ns_sock_to_str(nc->sock, buf, sizeof(buf), is_rem ? 7 : 3);
5256   sscanf(buf, "%47[^:]:%hu",
5257          is_rem ? c->remote_ip : c->local_ip,
5258          is_rem ? &c->remote_port : &c->local_port);
5259   //DBG(("%p %s %s", conn, is_rem ? "rem" : "loc", buf));
5260 }
5261
5262 static void on_accept(struct ns_connection *nc, union socket_address *sa) {
5263   struct mg_server *server = (struct mg_server *) nc->mgr;
5264   struct connection *conn;
5265
5266   if (!check_acl(server->config_options[ACCESS_CONTROL_LIST],
5267                  ntohl(* (uint32_t *) &sa->sin.sin_addr)) ||
5268       (conn = (struct connection *) NS_CALLOC(1, sizeof(*conn))) == NULL) {
5269     nc->flags |= NSF_CLOSE_IMMEDIATELY;
5270   } else {
5271     // Circularly link two connection structures
5272     nc->user_data = conn;
5273     conn->ns_conn = nc;
5274
5275     // Initialize the rest of connection attributes
5276     conn->server = server;
5277     conn->mg_conn.server_param = nc->mgr->user_data;
5278     set_ips(nc, 1);
5279     set_ips(nc, 0);
5280   }
5281 }
5282
5283 static void process_udp(struct ns_connection *nc) {
5284   struct iobuf *io = &nc->recv_iobuf;
5285   struct connection conn;
5286
5287   memset(&conn, 0, sizeof(conn));
5288   conn.ns_conn = nc;
5289   conn.server = (struct mg_server *) nc->mgr;
5290   conn.request_len = parse_http_message(io->buf, io->len, &conn.mg_conn);
5291   on_recv_data(&conn);
5292   //ns_printf(nc, "%s", "HTTP/1.0 200 OK\r\n\r\n");
5293 }
5294
5295 #ifdef MONGOOSE_SEND_NS_EVENTS
5296 static void send_ns_event(struct ns_connection *nc, int ev, void *p) {
5297   struct connection *conn = (struct connection *) nc->user_data;
5298   if (conn != NULL) {
5299     void *param[2] = { nc, p };
5300     conn->mg_conn.callback_param = param;
5301     call_user(conn, (enum mg_event) ev);
5302   }
5303 }
5304 #else
5305 static void send_ns_event(struct ns_connection *nc, int ev, void *p) {
5306   (void) nc; (void) p; (void) ev;
5307 }
5308 #endif
5309
5310 static void mg_ev_handler(struct ns_connection *nc, int ev, void *p) {
5311   struct connection *conn = (struct connection *) nc->user_data;
5312
5313   // Send NS event to the handler. Note that call_user won't send an event
5314   // if conn == NULL. Therefore, repeat this for NS_ACCEPT event as well.
5315   send_ns_event(nc, ev, p);
5316
5317   switch (ev) {
5318     case NS_ACCEPT:
5319       on_accept(nc, (union socket_address *) p);
5320       send_ns_event(nc, ev, p);
5321       break;
5322
5323     case NS_CONNECT:
5324       if (nc->user_data != NULL) {
5325         set_ips(nc, 1);
5326         set_ips(nc, 0);
5327       }
5328       conn->mg_conn.status_code = * (int *) p;
5329       if (conn->mg_conn.status_code != 0 ||
5330           (!(nc->flags & MG_PROXY_CONN) &&
5331            call_user(conn, MG_CONNECT) == MG_FALSE)) {
5332         nc->flags |= NSF_CLOSE_IMMEDIATELY;
5333       }
5334       break;
5335
5336     case NS_RECV:
5337       if (conn != NULL) {
5338         conn->num_bytes_recv += * (int *) p;
5339       }
5340
5341       if (nc->flags & NSF_UDP) {
5342         process_udp(nc);
5343       } else if (nc->listener != NULL) {
5344         on_recv_data(conn);
5345 #ifndef MONGOOSE_NO_CGI
5346       } else if (nc->flags & MG_CGI_CONN) {
5347         on_cgi_data(nc);
5348 #endif
5349       } else if (nc->flags & MG_PROXY_CONN) {
5350         if (conn != NULL) {
5351           ns_forward(nc, conn->ns_conn);
5352         }
5353       } else {
5354         process_response(conn);
5355       }
5356       break;
5357
5358     case NS_SEND:
5359       break;
5360
5361     case NS_CLOSE:
5362       nc->user_data = NULL;
5363       if (nc->flags & (MG_CGI_CONN | MG_PROXY_CONN)) {
5364         DBG(("%p %p closing cgi/proxy conn", conn, nc));
5365         if (conn && conn->ns_conn) {
5366           conn->ns_conn->flags &= ~NSF_BUFFER_BUT_DONT_SEND;
5367           conn->ns_conn->flags |= conn->ns_conn->send_iobuf.len > 0 ?
5368             NSF_FINISHED_SENDING_DATA : NSF_CLOSE_IMMEDIATELY;
5369           conn->endpoint.nc = NULL;
5370         }
5371       } else if (conn != NULL) {
5372         DBG(("%p %p %d closing", conn, nc, conn->endpoint_type));
5373
5374         if (conn->endpoint_type == EP_CLIENT && nc->recv_iobuf.len > 0) {
5375           call_http_client_handler(conn);
5376         }
5377
5378         call_user(conn, MG_CLOSE);
5379         close_local_endpoint(conn);
5380         conn->ns_conn = NULL;
5381         NS_FREE(conn);
5382       }
5383       break;
5384
5385     case NS_POLL:
5386       if (conn != NULL) {
5387         if (call_user(conn, MG_POLL) == MG_TRUE) {
5388           if (conn->ns_conn->flags & MG_HEADERS_SENT) {
5389             write_terminating_chunk(conn);
5390           }
5391           close_local_endpoint(conn);
5392           /*
5393            * MG_POLL callback returned MG_TRUE,
5394            * i.e. data is sent, set corresponding flag
5395            */
5396           conn->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
5397         }
5398
5399         if (conn->endpoint_type == EP_FILE) {
5400           transfer_file_data(conn);
5401         }
5402       }
5403
5404       // Expire idle connections
5405       {
5406         time_t current_time = * (time_t *) p;
5407
5408         if (conn != NULL && conn->mg_conn.is_websocket) {
5409           ping_idle_websocket_connection(conn, current_time);
5410         }
5411
5412         if (nc->listener != NULL &&
5413             nc->last_io_time + MONGOOSE_IDLE_TIMEOUT_SECONDS < current_time) {
5414           mg_ev_handler(nc, NS_CLOSE, NULL);
5415           nc->flags |= NSF_CLOSE_IMMEDIATELY;
5416         }
5417       }
5418       break;
5419
5420     default:
5421       break;
5422   }
5423 }
5424
5425 static void iter2(struct ns_connection *nc, int ev, void *param) {
5426   mg_handler_t func = NULL;
5427   struct connection *conn = (struct connection *) nc->user_data;
5428   const char *msg = (const char *) param;
5429   int n;
5430   (void) ev;
5431
5432   //DBG(("%p [%s]", conn, msg));
5433   if (sscanf(msg, "%p %n", &func, &n) && func != NULL && conn != NULL) {
5434     conn->mg_conn.callback_param = (void *) (msg + n);
5435     func(&conn->mg_conn, MG_POLL);
5436   }
5437 }
5438
5439 void mg_wakeup_server_ex(struct mg_server *server, mg_handler_t cb,
5440                          const char *fmt, ...) {
5441   va_list ap;
5442   char buf[8 * 1024];
5443   int len;
5444
5445   // Encode callback (cb) into a buffer
5446   len = snprintf(buf, sizeof(buf), "%p ", cb);
5447   va_start(ap, fmt);
5448   len += vsnprintf(buf + len, sizeof(buf) - len, fmt, ap);
5449   va_end(ap);
5450
5451   // "len + 1" is to include terminating \0 in the message
5452   ns_broadcast(&server->ns_mgr, iter2, buf, len + 1);
5453 }
5454
5455 void mg_wakeup_server(struct mg_server *server) {
5456   ns_broadcast(&server->ns_mgr, NULL, (void *) "", 0);
5457 }
5458
5459 const char *mg_get_option(const struct mg_server *server, const char *name) {
5460   const char **opts = (const char **) server->config_options;
5461   int i = get_option_index(name);
5462   return i == -1 ? NULL : opts[i] == NULL ? "" : opts[i];
5463 }
5464
5465 struct mg_server *mg_create_server(void *server_data, mg_handler_t handler) {
5466   struct mg_server *server = (struct mg_server *) NS_CALLOC(1, sizeof(*server));
5467   ns_mgr_init(&server->ns_mgr, server_data);
5468   set_default_option_values(server->config_options);
5469   server->event_handler = handler;
5470   return server;
5471 }