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