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


rc_tagdetect_client
Author(s): Monika Florek-Jasinska , Raphael Schaller
autogenerated on Sat Feb 13 2021 03:42:16