Pyrogenesis  13997
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
mongoose.cpp
Go to the documentation of this file.
1 // Slightly modified version of Mongoose, by Wildfire Games, for 0 A.D.
2 // Diff against mongoose_original.c (from Hg rev 77615121d235) to see the changes.
3 //
4 // Motivation for changes:
5 // * For simplicity and consistency with the rest of the codebase, we compile
6 // as C++ instead of C, requiring a few compatibility fixes.
7 // * For quietness with our default warning flags, some warnings are
8 // explicitly disabled.
9 // * CGI and SSL are disabled since they're not needed.
10 // * ws2_32 is linked explicitly here, instead of requiring more complexity
11 // in the build system.
12 // * To avoid debug spew, we disable DEBUG.
13 // * Use memcopy to get rid of strict-aliasing warning
14 
15 #define __STDC_LIMIT_MACROS
16 
17 #ifdef _MSC_VER
18 # pragma warning(disable:4127) // conditional expression is constant
19 # pragma warning(disable:4100) // unreferenced formal parameter
20 # pragma warning(disable:4245) // signed/unsigned mismatch
21 # pragma warning(disable:4505) // unreferenced local function has been removed
22 # pragma comment(lib, "ws2_32.lib")
23 #endif
24 
25 #if defined(__GNUC__)
26 # define GCC_VERSION (__GNUC__*100 + __GNUC_MINOR__)
27 
28 # if GCC_VERSION >= 402 // older GCCs don't support the diagnostic pragma at all
29 # pragma GCC diagnostic ignored "-Wunused-function"
30 # endif
31 # if GCC_VERSION >= 406 // new warning in 4.6
32 # pragma GCC diagnostic ignored "-Wunused-but-set-variable"
33 # endif
34 #endif
35 
36 #define NO_CGI
37 #define NO_SSL
38 
39 #undef DEBUG
40 
41 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
42 // Fix undefined PF_INET on FreeBSD
43 #include <sys/socket.h>
44 #endif
45 
46 // Copyright (c) 2004-2011 Sergey Lyubka
47 //
48 // Permission is hereby granted, free of charge, to any person obtaining a copy
49 // of this software and associated documentation files (the "Software"), to deal
50 // in the Software without restriction, including without limitation the rights
51 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
52 // copies of the Software, and to permit persons to whom the Software is
53 // furnished to do so, subject to the following conditions:
54 //
55 // The above copyright notice and this permission notice shall be included in
56 // all copies or substantial portions of the Software.
57 //
58 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
59 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
60 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
61 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
62 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
63 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
64 // THE SOFTWARE.
65 
66 #if defined(_WIN32)
67 #define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005
68 #else
69 #define _XOPEN_SOURCE 600 // For flockfile() on Linux
70 #define _LARGEFILE_SOURCE // Enable 64-bit file offsets
71 #define __STDC_FORMAT_MACROS // <inttypes.h> wants this for C++
72 #endif
73 
74 #if defined(__SYMBIAN32__)
75 #define NO_SSL // SSL is not supported
76 #define NO_CGI // CGI is not supported
77 #define PATH_MAX FILENAME_MAX
78 #endif // __SYMBIAN32__
79 
80 #ifndef _WIN32_WCE // Some ANSI #includes are not available on Windows CE
81 #include <sys/types.h>
82 #include <sys/stat.h>
83 #include <errno.h>
84 #include <signal.h>
85 #include <fcntl.h>
86 #endif // !_WIN32_WCE
87 
88 #include <time.h>
89 #include <stdlib.h>
90 #include <stdarg.h>
91 #include <assert.h>
92 #include <string.h>
93 #include <ctype.h>
94 #include <limits.h>
95 #include <stddef.h>
96 #include <stdio.h>
97 
98 #if defined(_WIN32) && !defined(__SYMBIAN32__) // Windows specific
99 #define _WIN32_WINNT 0x0400 // To make it link in VS2005
100 #include <windows.h>
101 
102 #ifndef PATH_MAX
103 #define PATH_MAX MAX_PATH
104 #endif
105 
106 #ifndef _WIN32_WCE
107 #include <process.h>
108 #include <direct.h>
109 #include <io.h>
110 #else // _WIN32_WCE
111 #include <winsock2.h>
112 #define NO_CGI // WinCE has no pipes
113 
114 typedef long off_t;
115 #define BUFSIZ 4096
116 
117 #define errno GetLastError()
118 #define strerror(x) _ultoa(x, (char *) _alloca(sizeof(x) *3 ), 10)
119 #endif // _WIN32_WCE
120 
121 #define MAKEUQUAD(lo, hi) ((uint64_t)(((uint32_t)(lo)) | \
122  ((uint64_t)((uint32_t)(hi))) << 32))
123 #define RATE_DIFF 10000000 // 100 nsecs
124 #define EPOCH_DIFF MAKEUQUAD(0xd53e8000, 0x019db1de)
125 #define SYS2UNIX_TIME(lo, hi) \
126  (time_t) ((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF)
127 
128 // Visual Studio 6 does not know __func__ or __FUNCTION__
129 // The rest of MS compilers use __FUNCTION__, not C99 __func__
130 // Also use _strtoui64 on modern M$ compilers
131 #if defined(_MSC_VER) && _MSC_VER < 1300
132 #define STRX(x) #x
133 #define STR(x) STRX(x)
134 #define __func__ "line " STR(__LINE__)
135 #define strtoull(x, y, z) strtoul(x, y, z)
136 #define strtoll(x, y, z) strtol(x, y, z)
137 #else
138 #define __func__ __FUNCTION__
139 #define strtoull(x, y, z) _strtoui64(x, y, z)
140 #define strtoll(x, y, z) _strtoi64(x, y, z)
141 #endif // _MSC_VER
142 
143 #define ERRNO GetLastError()
144 #define NO_SOCKLEN_T
145 #define SSL_LIB "ssleay32.dll"
146 #define CRYPTO_LIB "libeay32.dll"
147 #define DIRSEP '\\'
148 #define IS_DIRSEP_CHAR(c) ((c) == '/' || (c) == '\\')
149 #define O_NONBLOCK 0
150 #if !defined(EWOULDBLOCK)
151 #define EWOULDBLOCK WSAEWOULDBLOCK
152 #endif // !EWOULDBLOCK
153 #define _POSIX_
154 #define INT64_FMT "I64d"
155 
156 #define WINCDECL __cdecl
157 #define SHUT_WR 1
158 #define snprintf _snprintf
159 #define vsnprintf _vsnprintf
160 #define sleep(x) Sleep((x) * 1000)
161 
162 #define pipe(x) _pipe(x, BUFSIZ, _O_BINARY)
163 #define popen(x, y) _popen(x, y)
164 #define pclose(x) _pclose(x)
165 #define close(x) _close(x)
166 #define dlsym(x,y) GetProcAddress((HINSTANCE) (x), (y))
167 #define RTLD_LAZY 0
168 #define fseeko(x, y, z) fseek((x), (y), (z))
169 #define fdopen(x, y) _fdopen((x), (y))
170 #define write(x, y, z) _write((x), (y), (unsigned) z)
171 #define read(x, y, z) _read((x), (y), (unsigned) z)
172 #define flockfile(x) (void) 0
173 #define funlockfile(x) (void) 0
174 
175 #if !defined(fileno)
176 #define fileno(x) _fileno(x)
177 #endif // !fileno MINGW #defines fileno
178 
179 typedef HANDLE pthread_mutex_t;
180 typedef struct {HANDLE signal, broadcast;} pthread_cond_t;
181 typedef DWORD pthread_t;
182 #define pid_t HANDLE // MINGW typedefs pid_t to int. Using #define here.
183 
184 struct timespec {
185  long tv_nsec;
186  long tv_sec;
187 };
188 
189 static int pthread_mutex_lock(pthread_mutex_t *);
191 static FILE *mg_fopen(const char *path, const char *mode);
192 
193 #if defined(HAVE_STDINT)
194 #include <stdint.h>
195 #else
196 typedef unsigned int uint32_t;
197 typedef unsigned short uint16_t;
198 typedef unsigned __int64 uint64_t;
199 typedef __int64 int64_t;
200 #define INT64_MAX 9223372036854775807
201 #endif // HAVE_STDINT
202 
203 // POSIX dirent interface
204 struct dirent {
205  char d_name[PATH_MAX];
206 };
207 
208 typedef struct DIR {
209  HANDLE handle;
210  WIN32_FIND_DATAW info;
211  struct dirent result;
212 } DIR;
213 
214 #else // UNIX specific
215 #include <sys/wait.h>
216 #include <sys/socket.h>
217 #include <sys/select.h>
218 #include <netinet/in.h>
219 #include <arpa/inet.h>
220 #include <sys/time.h>
221 #include <stdint.h>
222 #include <inttypes.h>
223 #include <netdb.h>
224 
225 #include <pwd.h>
226 #include <unistd.h>
227 #include <dirent.h>
228 #if !defined(NO_SSL_DL) && !defined(NO_SSL)
229 #include <dlfcn.h>
230 #endif
231 #include <pthread.h>
232 #if defined(__MACH__)
233 #define SSL_LIB "libssl.dylib"
234 #define CRYPTO_LIB "libcrypto.dylib"
235 #else
236 #if !defined(SSL_LIB)
237 #define SSL_LIB "libssl.so"
238 #endif
239 #if !defined(CRYPTO_LIB)
240 #define CRYPTO_LIB "libcrypto.so"
241 #endif
242 #endif
243 #define DIRSEP '/'
244 #define IS_DIRSEP_CHAR(c) ((c) == '/')
245 #ifndef O_BINARY
246 #define O_BINARY 0
247 #endif // O_BINARY
248 #define closesocket(a) close(a)
249 #define mg_fopen(x, y) fopen(x, y)
250 #define mg_mkdir(x, y) mkdir(x, y)
251 #define mg_remove(x) remove(x)
252 #define mg_rename(x, y) rename(x, y)
253 #define ERRNO errno
254 #define INVALID_SOCKET (-1)
255 #define INT64_FMT PRId64
256 typedef int SOCKET;
257 #define WINCDECL
258 
259 #endif // End of Windows and UNIX specific includes
260 
261 #include "mongoose.h"
262 
263 #define MONGOOSE_VERSION "3.1"
264 #define PASSWORDS_FILE_NAME ".htpasswd"
265 #define CGI_ENVIRONMENT_SIZE 4096
266 #define MAX_CGI_ENVIR_VARS 64
267 #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
268 
269 #ifdef _WIN32
270 static pthread_t pthread_self(void) {
271  return GetCurrentThreadId();
272 }
273 #endif // _WIN32
274 
275 #if defined(DEBUG)
276 #define DEBUG_TRACE(x) do { \
277  flockfile(stdout); \
278  printf("*** %lu.%p.%s.%d: ", \
279  (unsigned long) time(NULL), (void *) pthread_self(), \
280  __func__, __LINE__); \
281  printf x; \
282  putchar('\n'); \
283  fflush(stdout); \
284  funlockfile(stdout); \
285 } while (0)
286 #else
287 #define DEBUG_TRACE(x)
288 #endif // DEBUG
289 
290 // Darwin prior to 7.0 and Win32 do not have socklen_t
291 #ifdef NO_SOCKLEN_T
292 typedef int socklen_t;
293 #endif // NO_SOCKLEN_T
294 
295 typedef void * (*mg_thread_func_t)(void *);
296 
297 static const char *http_500_error = "Internal Server Error";
298 
299 // Snatched from OpenSSL includes. I put the prototypes here to be independent
300 // from the OpenSSL source installation. Having this, mongoose + SSL can be
301 // built on any system with binary SSL libraries installed.
302 typedef struct ssl_st SSL;
303 typedef struct ssl_method_st SSL_METHOD;
304 typedef struct ssl_ctx_st SSL_CTX;
305 
306 #define SSL_ERROR_WANT_READ 2
307 #define SSL_ERROR_WANT_WRITE 3
308 #define SSL_FILETYPE_PEM 1
309 #define CRYPTO_LOCK 1
310 
311 #if defined(NO_SSL_DL)
312 extern void SSL_free(SSL *);
313 extern int SSL_accept(SSL *);
314 extern int SSL_connect(SSL *);
315 extern int SSL_read(SSL *, void *, int);
316 extern int SSL_write(SSL *, const void *, int);
317 extern int SSL_get_error(const SSL *, int);
318 extern int SSL_set_fd(SSL *, int);
319 extern SSL *SSL_new(SSL_CTX *);
320 extern SSL_CTX *SSL_CTX_new(SSL_METHOD *);
321 extern SSL_METHOD *SSLv23_server_method(void);
322 extern int SSL_library_init(void);
323 extern void SSL_load_error_strings(void);
324 extern int SSL_CTX_use_PrivateKey_file(SSL_CTX *, const char *, int);
325 extern int SSL_CTX_use_certificate_file(SSL_CTX *, const char *, int);
326 extern int SSL_CTX_use_certificate_chain_file(SSL_CTX *, const char *);
328 extern void SSL_CTX_free(SSL_CTX *);
329 extern unsigned long ERR_get_error(void);
330 extern char *ERR_error_string(unsigned long, char *);
331 extern int CRYPTO_num_locks(void);
332 extern void CRYPTO_set_locking_callback(void (*)(int, int, const char *, int));
333 extern void CRYPTO_set_id_callback(unsigned long (*)(void));
334 #else
335 // Dynamically loaded SSL functionality
336 struct ssl_func {
337  const char *name; // SSL function name
338  void (*ptr)(void); // Function pointer
339 };
340 
341 #define SSL_free (* (void (*)(SSL *)) ssl_sw[0].ptr)
342 #define SSL_accept (* (int (*)(SSL *)) ssl_sw[1].ptr)
343 #define SSL_connect (* (int (*)(SSL *)) ssl_sw[2].ptr)
344 #define SSL_read (* (int (*)(SSL *, void *, int)) ssl_sw[3].ptr)
345 #define SSL_write (* (int (*)(SSL *, const void *,int)) ssl_sw[4].ptr)
346 #define SSL_get_error (* (int (*)(SSL *, int)) ssl_sw[5].ptr)
347 #define SSL_set_fd (* (int (*)(SSL *, SOCKET)) ssl_sw[6].ptr)
348 #define SSL_new (* (SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
349 #define SSL_CTX_new (* (SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
350 #define SSLv23_server_method (* (SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
351 #define SSL_library_init (* (int (*)(void)) ssl_sw[10].ptr)
352 #define SSL_CTX_use_PrivateKey_file (* (int (*)(SSL_CTX *, \
353  const char *, int)) ssl_sw[11].ptr)
354 #define SSL_CTX_use_certificate_file (* (int (*)(SSL_CTX *, \
355  const char *, int)) ssl_sw[12].ptr)
356 #define SSL_CTX_set_default_passwd_cb \
357  (* (void (*)(SSL_CTX *, mg_callback_t)) ssl_sw[13].ptr)
358 #define SSL_CTX_free (* (void (*)(SSL_CTX *)) ssl_sw[14].ptr)
359 #define SSL_load_error_strings (* (void (*)(void)) ssl_sw[15].ptr)
360 #define SSL_CTX_use_certificate_chain_file \
361  (* (int (*)(SSL_CTX *, const char *)) ssl_sw[16].ptr)
362 
363 #define CRYPTO_num_locks (* (int (*)(void)) crypto_sw[0].ptr)
364 #define CRYPTO_set_locking_callback \
365  (* (void (*)(void (*)(int, int, const char *, int))) crypto_sw[1].ptr)
366 #define CRYPTO_set_id_callback \
367  (* (void (*)(unsigned long (*)(void))) crypto_sw[2].ptr)
368 #define ERR_get_error (* (unsigned long (*)(void)) crypto_sw[3].ptr)
369 #define ERR_error_string (* (char * (*)(unsigned long,char *)) crypto_sw[4].ptr)
370 
371 // set_ssl_option() function updates this array.
372 // It loads SSL library dynamically and changes NULLs to the actual addresses
373 // of respective functions. The macros above (like SSL_connect()) are really
374 // just calling these functions indirectly via the pointer.
375 static struct ssl_func ssl_sw[] = {
376  {"SSL_free", NULL},
377  {"SSL_accept", NULL},
378  {"SSL_connect", NULL},
379  {"SSL_read", NULL},
380  {"SSL_write", NULL},
381  {"SSL_get_error", NULL},
382  {"SSL_set_fd", NULL},
383  {"SSL_new", NULL},
384  {"SSL_CTX_new", NULL},
385  {"SSLv23_server_method", NULL},
386  {"SSL_library_init", NULL},
387  {"SSL_CTX_use_PrivateKey_file", NULL},
388  {"SSL_CTX_use_certificate_file",NULL},
389  {"SSL_CTX_set_default_passwd_cb",NULL},
390  {"SSL_CTX_free", NULL},
391  {"SSL_load_error_strings", NULL},
392  {"SSL_CTX_use_certificate_chain_file", NULL},
393  {NULL, NULL}
394 };
395 
396 // Similar array as ssl_sw. These functions could be located in different lib.
397 static struct ssl_func crypto_sw[] = {
398  {"CRYPTO_num_locks", NULL},
399  {"CRYPTO_set_locking_callback", NULL},
400  {"CRYPTO_set_id_callback", NULL},
401  {"ERR_get_error", NULL},
402  {"ERR_error_string", NULL},
403  {NULL, NULL}
404 };
405 #endif // NO_SSL_DL
406 
407 static const char *month_names[] = {
408  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
409  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
410 };
411 
412 // Unified socket address. For IPv6 support, add IPv6 address structure
413 // in the union u.
414 struct usa {
415  socklen_t len;
416  union {
417  struct sockaddr sa;
418  struct sockaddr_in sin;
419  } u;
420 };
421 
422 // Describes a string (chunk of memory).
423 struct vec {
424  const char *ptr;
425  size_t len;
426 };
427 
428 // Structure used by mg_stat() function. Uses 64 bit file length.
429 struct mgstat {
430  int is_directory; // Directory marker
431  int64_t size; // File size
432  time_t mtime; // Modification time
433 };
434 
435 // Describes listening socket, or socket which was accept()-ed by the master
436 // thread and queued for future handling by the worker thread.
437 struct socket {
438  struct socket *next; // Linkage
439  SOCKET sock; // Listening socket
440  struct usa lsa; // Local socket address
441  struct usa rsa; // Remote socket address
442  int is_ssl; // Is socket SSL-ed
443  int is_proxy;
444 };
445 
446 enum {
455 };
456 
457 static const char *config_options[] = {
458  "C", "cgi_extensions", ".cgi,.pl,.php",
459  "E", "cgi_environment", NULL,
460  "G", "put_delete_passwords_file", NULL,
461  "I", "cgi_interpreter", NULL,
462  "P", "protect_uri", NULL,
463  "R", "authentication_domain", "mydomain.com",
464  "S", "ssi_extensions", ".shtml,.shtm",
465  "a", "access_log_file", NULL,
466  "c", "ssl_chain_file", NULL,
467  "d", "enable_directory_listing", "yes",
468  "e", "error_log_file", NULL,
469  "g", "global_passwords_file", NULL,
470  "i", "index_files", "index.html,index.htm,index.cgi",
471  "k", "enable_keep_alive", "no",
472  "l", "access_control_list", NULL,
473  "M", "max_request_size", "16384",
474  "m", "extra_mime_types", NULL,
475  "p", "listening_ports", "8080",
476  "r", "document_root", ".",
477  "s", "ssl_certificate", NULL,
478  "t", "num_threads", "10",
479  "u", "run_as_user", NULL,
480  NULL
481 };
482 #define ENTRIES_PER_CONFIG_OPTION 3
483 
484 struct mg_context {
485  volatile int stop_flag; // Should we stop event loop
486  SSL_CTX *ssl_ctx; // SSL context
487  char *config[NUM_OPTIONS]; // Mongoose configuration parameters
488  mg_callback_t user_callback; // User-defined callback function
489  void *user_data; // User-defined data
490 
492 
493  volatile int num_threads; // Number of threads
494  pthread_mutex_t mutex; // Protects (max|num)_threads
495  pthread_cond_t cond; // Condvar for tracking workers terminations
496 
497  struct socket queue[20]; // Accepted sockets
498  volatile int sq_head; // Head of the socket queue
499  volatile int sq_tail; // Tail of the socket queue
500  pthread_cond_t sq_full; // Singaled when socket is produced
501  pthread_cond_t sq_empty; // Signaled when socket is consumed
502 };
503 
505  struct mg_connection *peer; // Remote target in proxy mode
507  struct mg_context *ctx;
508  SSL *ssl; // SSL descriptor
509  struct socket client; // Connected client
510  time_t birth_time; // Time connection was accepted
511  int64_t num_bytes_sent; // Total bytes sent to client
512  int64_t content_len; // Content-Length header value
513  int64_t consumed_content; // How many bytes of content is already read
514  char *buf; // Buffer for received data
515  int buf_size; // Buffer size
516  int request_len; // Size of the request + headers in a buffer
517  int data_len; // Total size of data in a buffer
518 };
519 
520 const char **mg_get_valid_option_names(void) {
521  return config_options;
522 }
523 
524 static void *call_user(struct mg_connection *conn, enum mg_event event) {
525  conn->request_info.user_data = conn->ctx->user_data;
526  return conn->ctx->user_callback == NULL ? NULL :
527  conn->ctx->user_callback(event, conn, &conn->request_info);
528 }
529 
530 static int get_option_index(const char *name) {
531  int i;
532 
533  for (i = 0; config_options[i] != NULL; i += ENTRIES_PER_CONFIG_OPTION) {
534  if (strcmp(config_options[i], name) == 0 ||
535  strcmp(config_options[i + 1], name) == 0) {
536  return i / ENTRIES_PER_CONFIG_OPTION;
537  }
538  }
539  return -1;
540 }
541 
542 const char *mg_get_option(const struct mg_context *ctx, const char *name) {
543  int i;
544  if ((i = get_option_index(name)) == -1) {
545  return NULL;
546  } else if (ctx->config[i] == NULL) {
547  return "";
548  } else {
549  return ctx->config[i];
550  }
551 }
552 
553 // Print error message to the opened error log stream.
554 static void cry(struct mg_connection *conn, const char *fmt, ...) {
555  char buf[BUFSIZ];
556  va_list ap;
557  FILE *fp;
558  time_t timestamp;
559 
560  va_start(ap, fmt);
561  (void) vsnprintf(buf, sizeof(buf), fmt, ap);
562  va_end(ap);
563 
564  // Do not lock when getting the callback value, here and below.
565  // I suppose this is fine, since function cannot disappear in the
566  // same way string option can.
567  conn->request_info.log_message = buf;
568  if (call_user(conn, MG_EVENT_LOG) == NULL) {
569  fp = conn->ctx->config[ERROR_LOG_FILE] == NULL ? NULL :
570  mg_fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");
571 
572  if (fp != NULL) {
573  flockfile(fp);
574  timestamp = time(NULL);
575 
576  (void) fprintf(fp,
577  "[%010lu] [error] [client %s] ",
578  (unsigned long) timestamp,
579  inet_ntoa(conn->client.rsa.u.sin.sin_addr));
580 
581  if (conn->request_info.request_method != NULL) {
582  (void) fprintf(fp, "%s %s: ",
584  conn->request_info.uri);
585  }
586 
587  (void) fprintf(fp, "%s", buf);
588  fputc('\n', fp);
589  funlockfile(fp);
590  if (fp != stderr) {
591  fclose(fp);
592  }
593  }
594  }
595  conn->request_info.log_message = NULL;
596 }
597 
598 // Return OpenSSL error message
599 static const char *ssl_error(void) {
600  unsigned long err;
601  err = ERR_get_error();
602  return err == 0 ? "" : ERR_error_string(err, NULL);
603 }
604 
605 // Return fake connection structure. Used for logging, if connection
606 // is not applicable at the moment of logging.
607 static struct mg_connection *fc(struct mg_context *ctx) {
608  static struct mg_connection fake_connection;
609  fake_connection.ctx = ctx;
610  return &fake_connection;
611 }
612 
613 const char *mg_version(void) {
614  return MONGOOSE_VERSION;
615 }
616 
617 static void mg_strlcpy(register char *dst, register const char *src, size_t n) {
618  for (; *src != '\0' && n > 1; n--) {
619  *dst++ = *src++;
620  }
621  *dst = '\0';
622 }
623 
624 static int lowercase(const char *s) {
625  return tolower(* (const unsigned char *) s);
626 }
627 
628 static int mg_strncasecmp(const char *s1, const char *s2, size_t len) {
629  int diff = 0;
630 
631  if (len > 0)
632  do {
633  diff = lowercase(s1++) - lowercase(s2++);
634  } while (diff == 0 && s1[-1] != '\0' && --len > 0);
635 
636  return diff;
637 }
638 
639 static int mg_strcasecmp(const char *s1, const char *s2) {
640  int diff;
641 
642  do {
643  diff = lowercase(s1++) - lowercase(s2++);
644  } while (diff == 0 && s1[-1] != '\0');
645 
646  return diff;
647 }
648 
649 static char * mg_strndup(const char *ptr, size_t len) {
650  char *p;
651 
652  if ((p = (char *) malloc(len + 1)) != NULL) {
653  mg_strlcpy(p, ptr, len + 1);
654  }
655 
656  return p;
657 }
658 
659 static char * mg_strdup(const char *str) {
660  return mg_strndup(str, strlen(str));
661 }
662 
663 // Like snprintf(), but never returns negative value, or the value
664 // that is larger than a supplied buffer.
665 // Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability
666 // in his audit report.
667 static int mg_vsnprintf(struct mg_connection *conn, char *buf, size_t buflen,
668  const char *fmt, va_list ap) {
669  int n;
670 
671  if (buflen == 0)
672  return 0;
673 
674  n = vsnprintf(buf, buflen, fmt, ap);
675 
676  if (n < 0) {
677  cry(conn, "vsnprintf error");
678  n = 0;
679  } else if (n >= (int) buflen) {
680  cry(conn, "truncating vsnprintf buffer: [%.*s]",
681  n > 200 ? 200 : n, buf);
682  n = (int) buflen - 1;
683  }
684  buf[n] = '\0';
685 
686  return n;
687 }
688 
689 static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
690  const char *fmt, ...) {
691  va_list ap;
692  int n;
693 
694  va_start(ap, fmt);
695  n = mg_vsnprintf(conn, buf, buflen, fmt, ap);
696  va_end(ap);
697 
698  return n;
699 }
700 
701 // Skip the characters until one of the delimiters characters found.
702 // 0-terminate resulting word. Skip the delimiter and following whitespaces if any.
703 // Advance pointer to buffer to the next word. Return found 0-terminated word.
704 // Delimiters can be quoted with quotechar.
705 static char *skip_quoted(char **buf, const char *delimiters, const char *whitespace, char quotechar) {
706  char *p, *begin_word, *end_word, *end_whitespace;
707 
708  begin_word = *buf;
709  end_word = begin_word + strcspn(begin_word, delimiters);
710 
711  // Check for quotechar
712  if (end_word > begin_word) {
713  p = end_word - 1;
714  while (*p == quotechar) {
715  // If there is anything beyond end_word, copy it
716  if (*end_word == '\0') {
717  *p = '\0';
718  break;
719  } else {
720  size_t end_off = strcspn(end_word + 1, delimiters);
721  memmove (p, end_word, end_off + 1);
722  p += end_off; // p must correspond to end_word - 1
723  end_word += end_off + 1;
724  }
725  }
726  for (p++; p < end_word; p++) {
727  *p = '\0';
728  }
729  }
730 
731  if (*end_word == '\0') {
732  *buf = end_word;
733  } else {
734  end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
735 
736  for (p = end_word; p < end_whitespace; p++) {
737  *p = '\0';
738  }
739 
740  *buf = end_whitespace;
741  }
742 
743  return begin_word;
744 }
745 
746 // Simplified version of skip_quoted without quote char
747 // and whitespace == delimiters
748 static char *skip(char **buf, const char *delimiters) {
749  return skip_quoted(buf, delimiters, delimiters, 0);
750 }
751 
752 
753 // Return HTTP header value, or NULL if not found.
754 static const char *get_header(const struct mg_request_info *ri,
755  const char *name) {
756  int i;
757 
758  for (i = 0; i < ri->num_headers; i++)
759  if (!mg_strcasecmp(name, ri->http_headers[i].name))
760  return ri->http_headers[i].value;
761 
762  return NULL;
763 }
764 
765 const char *mg_get_header(const struct mg_connection *conn, const char *name) {
766  return get_header(&conn->request_info, name);
767 }
768 
769 // A helper function for traversing comma separated list of values.
770 // It returns a list pointer shifted to the next value, of NULL if the end
771 // of the list found.
772 // Value is stored in val vector. If value has form "x=y", then eq_val
773 // vector is initialized to point to the "y" part, and val vector length
774 // is adjusted to point only to "x".
775 static const char *next_option(const char *list, struct vec *val,
776  struct vec *eq_val) {
777  if (list == NULL || *list == '\0') {
778  // End of the list
779  list = NULL;
780  } else {
781  val->ptr = list;
782  if ((list = strchr(val->ptr, ',')) != NULL) {
783  // Comma found. Store length and shift the list ptr
784  val->len = list - val->ptr;
785  list++;
786  } else {
787  // This value is the last one
788  list = val->ptr + strlen(val->ptr);
789  val->len = list - val->ptr;
790  }
791 
792  if (eq_val != NULL) {
793  // Value has form "x=y", adjust pointers and lengths
794  // so that val points to "x", and eq_val points to "y".
795  eq_val->len = 0;
796  eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);
797  if (eq_val->ptr != NULL) {
798  eq_val->ptr++; // Skip over '=' character
799  eq_val->len = val->ptr + val->len - eq_val->ptr;
800  val->len = (eq_val->ptr - val->ptr) - 1;
801  }
802  }
803  }
804 
805  return list;
806 }
807 
808 static int match_extension(const char *path, const char *ext_list) {
809  struct vec ext_vec;
810  size_t path_len;
811 
812  path_len = strlen(path);
813 
814  while ((ext_list = next_option(ext_list, &ext_vec, NULL)) != NULL)
815  if (ext_vec.len < path_len &&
816  mg_strncasecmp(path + path_len - ext_vec.len,
817  ext_vec.ptr, ext_vec.len) == 0)
818  return 1;
819 
820  return 0;
821 }
822 
823 // HTTP 1.1 assumes keep alive if "Connection:" header is not set
824 // This function must tolerate situations when connection info is not
825 // set up, for example if request parsing failed.
826 static int should_keep_alive(const struct mg_connection *conn) {
827  const char *http_version = conn->request_info.http_version;
828  const char *header = mg_get_header(conn, "Connection");
829  return (header == NULL && http_version && !strcmp(http_version, "1.1")) ||
830  (header != NULL && !mg_strcasecmp(header, "keep-alive"));
831 }
832 
833 static const char *suggest_connection_header(const struct mg_connection *conn) {
834  return should_keep_alive(conn) ? "keep-alive" : "close";
835 }
836 
837 static void send_http_error(struct mg_connection *conn, int status,
838  const char *reason, const char *fmt, ...) {
839  char buf[BUFSIZ];
840  va_list ap;
841  int len;
842 
843  conn->request_info.status_code = status;
844 
845  if (call_user(conn, MG_HTTP_ERROR) == NULL) {
846  buf[0] = '\0';
847  len = 0;
848 
849  // Errors 1xx, 204 and 304 MUST NOT send a body
850  if (status > 199 && status != 204 && status != 304) {
851  len = mg_snprintf(conn, buf, sizeof(buf), "Error %d: %s", status, reason);
852  cry(conn, "%s", buf);
853  buf[len++] = '\n';
854 
855  va_start(ap, fmt);
856  len += mg_vsnprintf(conn, buf + len, sizeof(buf) - len, fmt, ap);
857  va_end(ap);
858  }
859  DEBUG_TRACE(("[%s]", buf));
860 
861  mg_printf(conn, "HTTP/1.1 %d %s\r\n"
862  "Content-Type: text/plain\r\n"
863  "Content-Length: %d\r\n"
864  "Connection: %s\r\n\r\n", status, reason, len,
866  conn->num_bytes_sent += mg_printf(conn, "%s", buf);
867  }
868 }
869 
870 #if defined(_WIN32) && !defined(__SYMBIAN32__)
871 static int pthread_mutex_init(pthread_mutex_t *mutex, void *unused) {
872  unused = NULL;
873  *mutex = CreateMutex(NULL, FALSE, NULL);
874  return *mutex == NULL ? -1 : 0;
875 }
876 
877 static int pthread_mutex_destroy(pthread_mutex_t *mutex) {
878  return CloseHandle(*mutex) == 0 ? -1 : 0;
879 }
880 
881 static int pthread_mutex_lock(pthread_mutex_t *mutex) {
882  return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;
883 }
884 
885 static int pthread_mutex_unlock(pthread_mutex_t *mutex) {
886  return ReleaseMutex(*mutex) == 0 ? -1 : 0;
887 }
888 
889 static int pthread_cond_init(pthread_cond_t *cv, const void *unused) {
890  unused = NULL;
891  cv->signal = CreateEvent(NULL, FALSE, FALSE, NULL);
892  cv->broadcast = CreateEvent(NULL, TRUE, FALSE, NULL);
893  return cv->signal != NULL && cv->broadcast != NULL ? 0 : -1;
894 }
895 
896 static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex) {
897  HANDLE handles[] = {cv->signal, cv->broadcast};
898  ReleaseMutex(*mutex);
899  WaitForMultipleObjects(2, handles, FALSE, INFINITE);
900  return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;
901 }
902 
903 static int pthread_cond_signal(pthread_cond_t *cv) {
904  return SetEvent(cv->signal) == 0 ? -1 : 0;
905 }
906 
907 static int pthread_cond_broadcast(pthread_cond_t *cv) {
908  // Implementation with PulseEvent() has race condition, see
909  // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
910  return PulseEvent(cv->broadcast) == 0 ? -1 : 0;
911 }
912 
913 static int pthread_cond_destroy(pthread_cond_t *cv) {
914  return CloseHandle(cv->signal) && CloseHandle(cv->broadcast) ? 0 : -1;
915 }
916 
917 // For Windows, change all slashes to backslashes in path names.
918 static void change_slashes_to_backslashes(char *path) {
919  int i;
920 
921  for (i = 0; path[i] != '\0'; i++) {
922  if (path[i] == '/')
923  path[i] = '\\';
924  // i > 0 check is to preserve UNC paths, like \\server\file.txt
925  if (path[i] == '\\' && i > 0)
926  while (path[i + 1] == '\\' || path[i + 1] == '/')
927  (void) memmove(path + i + 1,
928  path + i + 2, strlen(path + i + 1));
929  }
930 }
931 
932 // Encode 'path' which is assumed UTF-8 string, into UNICODE string.
933 // wbuf and wbuf_len is a target buffer and its length.
934 static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len) {
935  char buf[PATH_MAX], buf2[PATH_MAX], *p;
936 
937  mg_strlcpy(buf, path, sizeof(buf));
938  change_slashes_to_backslashes(buf);
939 
940  // Point p to the end of the file name
941  p = buf + strlen(buf) - 1;
942 
943  // Trim trailing backslash character
944  while (p > buf && *p == '\\' && p[-1] != ':') {
945  *p-- = '\0';
946  }
947 
948  // Protect from CGI code disclosure.
949  // This is very nasty hole. Windows happily opens files with
950  // some garbage in the end of file name. So fopen("a.cgi ", "r")
951  // actually opens "a.cgi", and does not return an error!
952  if (*p == 0x20 || // No space at the end
953  (*p == 0x2e && p > buf) || // No '.' but allow '.' as full path
954  *p == 0x2b || // No '+'
955  (*p & ~0x7f)) { // And generally no non-ascii chars
956  (void) fprintf(stderr, "Rejecting suspicious path: [%s]", buf);
957  wbuf[0] = L'\0';
958  } else {
959  // Convert to Unicode and back. If doubly-converted string does not
960  // match the original, something is fishy, reject.
961  MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
962  WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
963  NULL, NULL);
964  if (strcmp(buf, buf2) != 0) {
965  wbuf[0] = L'\0';
966  }
967  }
968 }
969 
970 #if defined(_WIN32_WCE)
971 static time_t time(time_t *ptime) {
972  time_t t;
973  SYSTEMTIME st;
974  FILETIME ft;
975 
976  GetSystemTime(&st);
977  SystemTimeToFileTime(&st, &ft);
978  t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
979 
980  if (ptime != NULL) {
981  *ptime = t;
982  }
983 
984  return t;
985 }
986 
987 static struct tm *localtime(const time_t *ptime, struct tm *ptm) {
988  int64_t t = ((int64_t) *ptime) * RATE_DIFF + EPOCH_DIFF;
989  FILETIME ft, lft;
990  SYSTEMTIME st;
991  TIME_ZONE_INFORMATION tzinfo;
992 
993  if (ptm == NULL) {
994  return NULL;
995  }
996 
997  * (int64_t *) &ft = t;
998  FileTimeToLocalFileTime(&ft, &lft);
999  FileTimeToSystemTime(&lft, &st);
1000  ptm->tm_year = st.wYear - 1900;
1001  ptm->tm_mon = st.wMonth - 1;
1002  ptm->tm_wday = st.wDayOfWeek;
1003  ptm->tm_mday = st.wDay;
1004  ptm->tm_hour = st.wHour;
1005  ptm->tm_min = st.wMinute;
1006  ptm->tm_sec = st.wSecond;
1007  ptm->tm_yday = 0; // hope nobody uses this
1008  ptm->tm_isdst =
1009  GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
1010 
1011  return ptm;
1012 }
1013 
1014 static struct tm *gmtime(const time_t *ptime, struct tm *ptm) {
1015  // FIXME(lsm): fix this.
1016  return localtime(ptime, ptm);
1017 }
1018 
1019 static size_t strftime(char *dst, size_t dst_size, const char *fmt,
1020  const struct tm *tm) {
1021  (void) snprintf(dst, dst_size, "implement strftime() for WinCE");
1022  return 0;
1023 }
1024 #endif
1025 
1026 static int mg_rename(const char* oldname, const char* newname) {
1027  wchar_t woldbuf[PATH_MAX];
1028  wchar_t wnewbuf[PATH_MAX];
1029 
1030  to_unicode(oldname, woldbuf, ARRAY_SIZE(woldbuf));
1031  to_unicode(newname, wnewbuf, ARRAY_SIZE(wnewbuf));
1032 
1033  return MoveFileW(woldbuf, wnewbuf) ? 0 : -1;
1034 }
1035 
1036 
1037 static FILE *mg_fopen(const char *path, const char *mode) {
1038  wchar_t wbuf[PATH_MAX], wmode[20];
1039 
1040  to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
1041  MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
1042 
1043  return _wfopen(wbuf, wmode);
1044 }
1045 
1046 static int mg_stat(const char *path, struct mgstat *stp) {
1047  int ok = -1; // Error
1048  wchar_t wbuf[PATH_MAX];
1049  WIN32_FILE_ATTRIBUTE_DATA info;
1050 
1051  to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
1052 
1053  if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
1054  stp->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
1055  stp->mtime = SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
1056  info.ftLastWriteTime.dwHighDateTime);
1057  stp->is_directory =
1058  info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
1059  ok = 0; // Success
1060  }
1061 
1062  return ok;
1063 }
1064 
1065 static int mg_remove(const char *path) {
1066  wchar_t wbuf[PATH_MAX];
1067  to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
1068  return DeleteFileW(wbuf) ? 0 : -1;
1069 }
1070 
1071 static int mg_mkdir(const char *path, int mode) {
1072  char buf[PATH_MAX];
1073  wchar_t wbuf[PATH_MAX];
1074 
1075  mode = 0; // Unused
1076  mg_strlcpy(buf, path, sizeof(buf));
1077  change_slashes_to_backslashes(buf);
1078 
1079  (void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, sizeof(wbuf));
1080 
1081  return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
1082 }
1083 
1084 // Implementation of POSIX opendir/closedir/readdir for Windows.
1085 static DIR * opendir(const char *name) {
1086  DIR *dir = NULL;
1087  wchar_t wpath[PATH_MAX];
1088  DWORD attrs;
1089 
1090  if (name == NULL) {
1091  SetLastError(ERROR_BAD_ARGUMENTS);
1092  } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) {
1093  SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1094  } else {
1095  to_unicode(name, wpath, ARRAY_SIZE(wpath));
1096  attrs = GetFileAttributesW(wpath);
1097  if (attrs != 0xFFFFFFFF &&
1098  ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
1099  (void) wcscat(wpath, L"\\*");
1100  dir->handle = FindFirstFileW(wpath, &dir->info);
1101  dir->result.d_name[0] = '\0';
1102  } else {
1103  free(dir);
1104  dir = NULL;
1105  }
1106  }
1107 
1108  return dir;
1109 }
1110 
1111 static int closedir(DIR *dir) {
1112  int result = 0;
1113 
1114  if (dir != NULL) {
1115  if (dir->handle != INVALID_HANDLE_VALUE)
1116  result = FindClose(dir->handle) ? 0 : -1;
1117 
1118  free(dir);
1119  } else {
1120  result = -1;
1121  SetLastError(ERROR_BAD_ARGUMENTS);
1122  }
1123 
1124  return result;
1125 }
1126 
1127 struct dirent * readdir(DIR *dir) {
1128  struct dirent *result = 0;
1129 
1130  if (dir) {
1131  if (dir->handle != INVALID_HANDLE_VALUE) {
1132  result = &dir->result;
1133  (void) WideCharToMultiByte(CP_UTF8, 0,
1134  dir->info.cFileName, -1, result->d_name,
1135  sizeof(result->d_name), NULL, NULL);
1136 
1137  if (!FindNextFileW(dir->handle, &dir->info)) {
1138  (void) FindClose(dir->handle);
1139  dir->handle = INVALID_HANDLE_VALUE;
1140  }
1141 
1142  } else {
1143  SetLastError(ERROR_FILE_NOT_FOUND);
1144  }
1145  } else {
1146  SetLastError(ERROR_BAD_ARGUMENTS);
1147  }
1148 
1149  return result;
1150 }
1151 
1152 #define set_close_on_exec(fd) // No FD_CLOEXEC on Windows
1153 
1154 static int start_thread(struct mg_context *ctx, mg_thread_func_t f, void *p) {
1155  return _beginthread((void (__cdecl *)(void *)) f, 0, p) == -1L ? -1 : 0;
1156 }
1157 
1158 static HANDLE dlopen(const char *dll_name, int flags) {
1159  wchar_t wbuf[PATH_MAX];
1160  flags = 0; // Unused
1161  to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
1162  return LoadLibraryW(wbuf);
1163 }
1164 
1165 #if !defined(NO_CGI)
1166 #define SIGKILL 0
1167 static int kill(pid_t pid, int sig_num) {
1168  (void) TerminateProcess(pid, sig_num);
1169  (void) CloseHandle(pid);
1170  return 0;
1171 }
1172 
1173 static pid_t spawn_process(struct mg_connection *conn, const char *prog,
1174  char *envblk, char *envp[], int fd_stdin,
1175  int fd_stdout, const char *dir) {
1176  HANDLE me;
1177  char *p, *interp, cmdline[PATH_MAX], buf[PATH_MAX];
1178  FILE *fp;
1179  STARTUPINFOA si;
1180  PROCESS_INFORMATION pi;
1181 
1182  envp = NULL; // Unused
1183 
1184  (void) memset(&si, 0, sizeof(si));
1185  (void) memset(&pi, 0, sizeof(pi));
1186 
1187  // TODO(lsm): redirect CGI errors to the error log file
1188  si.cb = sizeof(si);
1189  si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
1190  si.wShowWindow = SW_HIDE;
1191 
1192  me = GetCurrentProcess();
1193  (void) DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdin), me,
1194  &si.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS);
1195  (void) DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdout), me,
1196  &si.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS);
1197 
1198  // If CGI file is a script, try to read the interpreter line
1199  interp = conn->ctx->config[CGI_INTERPRETER];
1200  if (interp == NULL) {
1201  buf[2] = '\0';
1202  mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%c%s", dir, DIRSEP, prog);
1203  if ((fp = fopen(cmdline, "r")) != NULL) {
1204  (void) fgets(buf, sizeof(buf), fp);
1205  if (buf[0] != '#' || buf[1] != '!') {
1206  // First line does not start with "#!". Do not set interpreter.
1207  buf[2] = '\0';
1208  } else {
1209  // Trim whitespaces in interpreter name
1210  for (p = &buf[strlen(buf) - 1]; p > buf && isspace(*p); p--) {
1211  *p = '\0';
1212  }
1213  }
1214  (void) fclose(fp);
1215  }
1216  interp = buf + 2;
1217  }
1218 
1219  (void) mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%s%s%c%s",
1220  interp, interp[0] == '\0' ? "" : " ", dir, DIRSEP, prog);
1221 
1222  DEBUG_TRACE(("Running [%s]", cmdline));
1223  if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE,
1224  CREATE_NEW_PROCESS_GROUP, envblk, dir, &si, &pi) == 0) {
1225  cry(conn, "%s: CreateProcess(%s): %d",
1226  __func__, cmdline, ERRNO);
1227  pi.hProcess = (pid_t) -1;
1228  } else {
1229  (void) close(fd_stdin);
1230  (void) close(fd_stdout);
1231  }
1232 
1233  (void) CloseHandle(si.hStdOutput);
1234  (void) CloseHandle(si.hStdInput);
1235  (void) CloseHandle(pi.hThread);
1236 
1237  return (pid_t) pi.hProcess;
1238 }
1239 #endif // !NO_CGI
1240 
1241 static int set_non_blocking_mode(SOCKET sock) {
1242  unsigned long on = 1;
1243  return ioctlsocket(sock, FIONBIO, &on);
1244 }
1245 
1246 #else
1247 static int mg_stat(const char *path, struct mgstat *stp) {
1248  struct stat st;
1249  int ok;
1250 
1251  if (stat(path, &st) == 0) {
1252  ok = 0;
1253  stp->size = st.st_size;
1254  stp->mtime = st.st_mtime;
1255  stp->is_directory = S_ISDIR(st.st_mode);
1256  } else {
1257  ok = -1;
1258  }
1259 
1260  return ok;
1261 }
1262 
1263 static void set_close_on_exec(int fd) {
1264  (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
1265 }
1266 
1267 static int start_thread(struct mg_context *ctx, mg_thread_func_t func,
1268  void *param) {
1269  pthread_t thread_id;
1270  pthread_attr_t attr;
1271  int retval;
1272 
1273  (void) pthread_attr_init(&attr);
1274  (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1275  // TODO(lsm): figure out why mongoose dies on Linux if next line is enabled
1276  // (void) pthread_attr_setstacksize(&attr, sizeof(struct mg_connection) * 5);
1277 
1278  if ((retval = pthread_create(&thread_id, &attr, func, param)) != 0) {
1279  cry(fc(ctx), "%s: %s", __func__, strerror(retval));
1280  }
1281 
1282  return retval;
1283 }
1284 
1285 #ifndef NO_CGI
1286 static pid_t spawn_process(struct mg_connection *conn, const char *prog,
1287  char *envblk, char *envp[], int fd_stdin,
1288  int fd_stdout, const char *dir) {
1289  pid_t pid;
1290  const char *interp;
1291 
1292  envblk = NULL; // Unused
1293 
1294  if ((pid = fork()) == -1) {
1295  // Parent
1296  send_http_error(conn, 500, http_500_error, "fork(): %s", strerror(ERRNO));
1297  } else if (pid == 0) {
1298  // Child
1299  if (chdir(dir) != 0) {
1300  cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
1301  } else if (dup2(fd_stdin, 0) == -1) {
1302  cry(conn, "%s: dup2(%d, 0): %s", __func__, fd_stdin, strerror(ERRNO));
1303  } else if (dup2(fd_stdout, 1) == -1) {
1304  cry(conn, "%s: dup2(%d, 1): %s", __func__, fd_stdout, strerror(ERRNO));
1305  } else {
1306  (void) dup2(fd_stdout, 2);
1307  (void) close(fd_stdin);
1308  (void) close(fd_stdout);
1309 
1310  // Execute CGI program. No need to lock: new process
1311  interp = conn->ctx->config[CGI_INTERPRETER];
1312  if (interp == NULL) {
1313  (void) execle(prog, prog, NULL, envp);
1314  cry(conn, "%s: execle(%s): %s", __func__, prog, strerror(ERRNO));
1315  } else {
1316  (void) execle(interp, interp, prog, NULL, envp);
1317  cry(conn, "%s: execle(%s %s): %s", __func__, interp, prog,
1318  strerror(ERRNO));
1319  }
1320  }
1321  exit(EXIT_FAILURE);
1322  } else {
1323  // Parent. Close stdio descriptors
1324  (void) close(fd_stdin);
1325  (void) close(fd_stdout);
1326  }
1327 
1328  return pid;
1329 }
1330 #endif // !NO_CGI
1331 
1332 static int set_non_blocking_mode(SOCKET sock) {
1333  int flags;
1334 
1335  flags = fcntl(sock, F_GETFL, 0);
1336  (void) fcntl(sock, F_SETFL, flags | O_NONBLOCK);
1337 
1338  return 0;
1339 }
1340 #endif // _WIN32
1341 
1342 // Write data to the IO channel - opened file descriptor, socket or SSL
1343 // descriptor. Return number of bytes written.
1344 static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf,
1345  int64_t len) {
1346  int64_t sent;
1347  int n, k;
1348 
1349  sent = 0;
1350  while (sent < len) {
1351 
1352  // How many bytes we send in this iteration
1353  k = len - sent > INT_MAX ? INT_MAX : (int) (len - sent);
1354 
1355  if (ssl != NULL) {
1356  n = SSL_write(ssl, buf + sent, k);
1357  } else if (fp != NULL) {
1358  n = fwrite(buf + sent, 1, (size_t)k, fp);
1359  if (ferror(fp))
1360  n = -1;
1361  } else {
1362  n = send(sock, buf + sent, (size_t)k, 0);
1363  }
1364 
1365  if (n < 0)
1366  break;
1367 
1368  sent += n;
1369  }
1370 
1371  return sent;
1372 }
1373 
1374 // Read from IO channel - opened file descriptor, socket, or SSL descriptor.
1375 // Return number of bytes read.
1376 static int pull(FILE *fp, SOCKET sock, SSL *ssl, char *buf, int len) {
1377  int nread;
1378 
1379  if (ssl != NULL) {
1380  nread = SSL_read(ssl, buf, len);
1381  } else if (fp != NULL) {
1382  // Use read() instead of fread(), because if we're reading from the CGI
1383  // pipe, fread() may block until IO buffer is filled up. We cannot afford
1384  // to block and must pass all read bytes immediately to the client.
1385  nread = read(fileno(fp), buf, (size_t) len);
1386  if (ferror(fp))
1387  nread = -1;
1388  } else {
1389  nread = recv(sock, buf, (size_t) len, 0);
1390  }
1391 
1392  return nread;
1393 }
1394 
1395 int mg_read(struct mg_connection *conn, void *buf, size_t len) {
1396  int n, buffered_len, nread;
1397  const char *buffered;
1398 
1399  assert((conn->content_len == -1 && conn->consumed_content == 0) ||
1400  conn->consumed_content <= conn->content_len);
1401  DEBUG_TRACE(("%p %zu %lld %lld", buf, len,
1402  conn->content_len, conn->consumed_content));
1403  nread = 0;
1404  if (conn->consumed_content < conn->content_len) {
1405 
1406  // Adjust number of bytes to read.
1407  int64_t to_read = conn->content_len - conn->consumed_content;
1408  if (to_read < (int64_t) len) {
1409  len = (int) to_read;
1410  }
1411 
1412  // How many bytes of data we have buffered in the request buffer?
1413  buffered = conn->buf + conn->request_len + conn->consumed_content;
1414  buffered_len = conn->data_len - conn->request_len;
1415  assert(buffered_len >= 0);
1416 
1417  // Return buffered data back if we haven't done that yet.
1418  if (conn->consumed_content < (int64_t) buffered_len) {
1419  buffered_len -= (int) conn->consumed_content;
1420  if (len < (size_t) buffered_len) {
1421  buffered_len = len;
1422  }
1423  memcpy(buf, buffered, (size_t)buffered_len);
1424  len -= buffered_len;
1425  buf = (char *) buf + buffered_len;
1426  conn->consumed_content += buffered_len;
1427  nread = buffered_len;
1428  }
1429 
1430  // We have returned all buffered data. Read new data from the remote socket.
1431  while (len > 0) {
1432  n = pull(NULL, conn->client.sock, conn->ssl, (char *) buf, (int) len);
1433  if (n <= 0) {
1434  break;
1435  }
1436  buf = (char *) buf + n;
1437  conn->consumed_content += n;
1438  nread += n;
1439  len -= n;
1440  }
1441  }
1442  return nread;
1443 }
1444 
1445 int mg_write(struct mg_connection *conn, const void *buf, size_t len) {
1446  return (int) push(NULL, conn->client.sock, conn->ssl,
1447  (const char *) buf, (int64_t) len);
1448 }
1449 
1450 int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
1451  char buf[BUFSIZ];
1452  int len;
1453  va_list ap;
1454 
1455  va_start(ap, fmt);
1456  len = mg_vsnprintf(conn, buf, sizeof(buf), fmt, ap);
1457  va_end(ap);
1458 
1459  return mg_write(conn, buf, (size_t)len);
1460 }
1461 
1462 // URL-decode input buffer into destination buffer.
1463 // 0-terminate the destination buffer. Return the length of decoded data.
1464 // form-url-encoded data differs from URI encoding in a way that it
1465 // uses '+' as character for space, see RFC 1866 section 8.2.1
1466 // http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
1467 static size_t url_decode(const char *src, size_t src_len, char *dst,
1468  size_t dst_len, int is_form_url_encoded) {
1469  size_t i, j;
1470  int a, b;
1471 #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
1472 
1473  for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
1474  if (src[i] == '%' &&
1475  isxdigit(* (const unsigned char *) (src + i + 1)) &&
1476  isxdigit(* (const unsigned char *) (src + i + 2))) {
1477  a = tolower(* (const unsigned char *) (src + i + 1));
1478  b = tolower(* (const unsigned char *) (src + i + 2));
1479  dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
1480  i += 2;
1481  } else if (is_form_url_encoded && src[i] == '+') {
1482  dst[j] = ' ';
1483  } else {
1484  dst[j] = src[i];
1485  }
1486  }
1487 
1488  dst[j] = '\0'; // Null-terminate the destination
1489 
1490  return j;
1491 }
1492 
1493 // Scan given buffer and fetch the value of the given variable.
1494 // It can be specified in query string, or in the POST data.
1495 // Return NULL if the variable not found, or allocated 0-terminated value.
1496 // It is caller's responsibility to free the returned value.
1497 int mg_get_var(const char *buf, size_t buf_len, const char *name,
1498  char *dst, size_t dst_len) {
1499  const char *p, *e, *s;
1500  size_t name_len, len;
1501 
1502  name_len = strlen(name);
1503  e = buf + buf_len;
1504  len = -1;
1505  dst[0] = '\0';
1506 
1507  // buf is "var1=val1&var2=val2...". Find variable first
1508  for (p = buf; p != NULL && p + name_len < e; p++) {
1509  if ((p == buf || p[-1] == '&') && p[name_len] == '=' &&
1510  !mg_strncasecmp(name, p, name_len)) {
1511 
1512  // Point p to variable value
1513  p += name_len + 1;
1514 
1515  // Point s to the end of the value
1516  s = (const char *) memchr(p, '&', (size_t)(e - p));
1517  if (s == NULL) {
1518  s = e;
1519  }
1520  assert(s >= p);
1521 
1522  // Decode variable into destination buffer
1523  if ((size_t) (s - p) < dst_len) {
1524  len = url_decode(p, (size_t)(s - p), dst, dst_len, 1);
1525  }
1526  break;
1527  }
1528  }
1529 
1530  return len;
1531 }
1532 
1533 int mg_get_cookie(const struct mg_connection *conn, const char *cookie_name,
1534  char *dst, size_t dst_size) {
1535  const char *s, *p, *end;
1536  int name_len, len = -1;
1537 
1538  dst[0] = '\0';
1539  if ((s = mg_get_header(conn, "Cookie")) == NULL) {
1540  return 0;
1541  }
1542 
1543  name_len = strlen(cookie_name);
1544  end = s + strlen(s);
1545 
1546  for (; (s = strstr(s, cookie_name)) != NULL; s += name_len)
1547  if (s[name_len] == '=') {
1548  s += name_len + 1;
1549  if ((p = strchr(s, ' ')) == NULL)
1550  p = end;
1551  if (p[-1] == ';')
1552  p--;
1553  if (*s == '"' && p[-1] == '"' && p > s + 1) {
1554  s++;
1555  p--;
1556  }
1557  if ((size_t) (p - s) < dst_size) {
1558  len = (p - s) + 1;
1559  mg_strlcpy(dst, s, (size_t)len);
1560  }
1561  break;
1562  }
1563 
1564  return len;
1565 }
1566 
1567 // Mongoose allows to specify multiple directories to serve,
1568 // like /var/www,/~bob=/home/bob. That means that root directory depends on URI.
1569 // This function returns root dir for given URI.
1570 static int get_document_root(const struct mg_connection *conn,
1571  struct vec *document_root) {
1572  const char *root, *uri;
1573  int len_of_matched_uri;
1574  struct vec uri_vec, path_vec;
1575 
1576  uri = conn->request_info.uri;
1577  len_of_matched_uri = 0;
1578  root = next_option(conn->ctx->config[DOCUMENT_ROOT], document_root, NULL);
1579 
1580  while ((root = next_option(root, &uri_vec, &path_vec)) != NULL) {
1581  if (memcmp(uri, uri_vec.ptr, uri_vec.len) == 0) {
1582  *document_root = path_vec;
1583  len_of_matched_uri = uri_vec.len;
1584  break;
1585  }
1586  }
1587 
1588  return len_of_matched_uri;
1589 }
1590 
1591 static void convert_uri_to_file_name(struct mg_connection *conn,
1592  const char *uri, char *buf,
1593  size_t buf_len) {
1594  struct vec vec = {0};
1595  int match_len;
1596 
1597  match_len = get_document_root(conn, &vec);
1598  mg_snprintf(conn, buf, buf_len, "%.*s%s", (int) vec.len, vec.ptr, uri + match_len);
1599 
1600 #if defined(_WIN32) && !defined(__SYMBIAN32__)
1601  change_slashes_to_backslashes(buf);
1602 #endif // _WIN32
1603 
1604  DEBUG_TRACE(("[%s] -> [%s], [%.*s]", uri, buf, (int) vec.len, vec.ptr));
1605 }
1606 
1607 static int sslize(struct mg_connection *conn, int (*func)(SSL *)) {
1608  return (conn->ssl = SSL_new(conn->ctx->ssl_ctx)) != NULL &&
1609  SSL_set_fd(conn->ssl, conn->client.sock) == 1 &&
1610  func(conn->ssl) == 1;
1611 }
1612 
1613 static struct mg_connection *mg_connect(struct mg_connection *conn,
1614  const char *host, int port, int use_ssl) {
1615  struct mg_connection *newconn = NULL;
1616  struct sockaddr_in sin;
1617  struct hostent *he;
1618  int sock;
1619 
1620  if (conn->ctx->ssl_ctx == NULL && use_ssl) {
1621  cry(conn, "%s: SSL is not initialized", __func__);
1622  } else if ((he = gethostbyname(host)) == NULL) {
1623  cry(conn, "%s: gethostbyname(%s): %s", __func__, host, strerror(ERRNO));
1624  } else if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
1625  cry(conn, "%s: socket: %s", __func__, strerror(ERRNO));
1626  } else {
1627  sin.sin_family = AF_INET;
1628  sin.sin_port = htons((uint16_t) port);
1629  sin.sin_addr = * (struct in_addr *) he->h_addr_list[0];
1630  if (connect(sock, (struct sockaddr *) &sin, sizeof(sin)) != 0) {
1631  cry(conn, "%s: connect(%s:%d): %s", __func__, host, port,
1632  strerror(ERRNO));
1633  closesocket(sock);
1634  } else if ((newconn = (struct mg_connection *)
1635  calloc(1, sizeof(*newconn))) == NULL) {
1636  cry(conn, "%s: calloc: %s", __func__, strerror(ERRNO));
1637  closesocket(sock);
1638  } else {
1639  newconn->client.sock = sock;
1640  newconn->client.rsa.u.sin = sin;
1641  if (use_ssl) {
1642  sslize(newconn, SSL_connect);
1643  }
1644  }
1645  }
1646 
1647  return newconn;
1648 }
1649 
1650 // Check whether full request is buffered. Return:
1651 // -1 if request is malformed
1652 // 0 if request is not yet fully buffered
1653 // >0 actual request length, including last \r\n\r\n
1654 static int get_request_len(const char *buf, int buflen) {
1655  const char *s, *e;
1656  int len = 0;
1657 
1658  DEBUG_TRACE(("buf: %p, len: %d", buf, buflen));
1659  for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
1660  // Control characters are not allowed but >=128 is.
1661  if (!isprint(* (const unsigned char *) s) && *s != '\r' &&
1662  *s != '\n' && * (const unsigned char *) s < 128) {
1663  len = -1;
1664  } else if (s[0] == '\n' && s[1] == '\n') {
1665  len = (int) (s - buf) + 2;
1666  } else if (s[0] == '\n' && &s[1] < e &&
1667  s[1] == '\r' && s[2] == '\n') {
1668  len = (int) (s - buf) + 3;
1669  }
1670 
1671  return len;
1672 }
1673 
1674 // Convert month to the month number. Return -1 on error, or month number
1675 static int get_month_index(const char *s) {
1676  size_t i;
1677 
1678  for (i = 0; i < ARRAY_SIZE(month_names); i++)
1679  if (!strcmp(s, month_names[i]))
1680  return (int) i;
1681 
1682  return -1;
1683 }
1684 
1685 // Parse UTC date-time string, and return the corresponding time_t value.
1686 static time_t parse_date_string(const char *datetime) {
1687  static const unsigned short days_before_month[] = {
1688  0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
1689  };
1690  char month_str[32];
1691  int second, minute, hour, day, month, year, leap_days, days;
1692  time_t result = (time_t) 0;
1693 
1694  if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d",
1695  &day, month_str, &year, &hour, &minute, &second) == 6) ||
1696  (sscanf(datetime, "%d %3s %d %d:%d:%d",
1697  &day, month_str, &year, &hour, &minute, &second) == 6) ||
1698  (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",
1699  &day, month_str, &year, &hour, &minute, &second) == 6) ||
1700  (sscanf(datetime, "%d-%3s-%d %d:%d:%d",
1701  &day, month_str, &year, &hour, &minute, &second) == 6)) &&
1702  year > 1970 &&
1703  (month = get_month_index(month_str)) != -1) {
1704  year -= 1970;
1705  leap_days = year / 4 - year / 100 + year / 400;
1706  days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
1707  result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
1708  }
1709 
1710  return result;
1711 }
1712 
1713 // Protect against directory disclosure attack by removing '..',
1714 // excessive '/' and '\' characters
1716  char *p = s;
1717 
1718  while (*s != '\0') {
1719  *p++ = *s++;
1720  if (s[-1] == '/' || s[-1] == '\\') {
1721  // Skip all following slashes and backslashes
1722  while (*s == '/' || *s == '\\') {
1723  s++;
1724  }
1725 
1726  // Skip all double-dots
1727  while (*s == '.' && s[1] == '.') {
1728  s += 2;
1729  }
1730  }
1731  }
1732  *p = '\0';
1733 }
1734 
1735 static const struct {
1736  const char *extension;
1737  size_t ext_len;
1738  const char *mime_type;
1740 } builtin_mime_types[] = {
1741  {".html", 5, "text/html", 9},
1742  {".htm", 4, "text/html", 9},
1743  {".shtm", 5, "text/html", 9},
1744  {".shtml", 6, "text/html", 9},
1745  {".css", 4, "text/css", 8},
1746  {".js", 3, "application/x-javascript", 24},
1747  {".ico", 4, "image/x-icon", 12},
1748  {".gif", 4, "image/gif", 9},
1749  {".jpg", 4, "image/jpeg", 10},
1750  {".jpeg", 5, "image/jpeg", 10},
1751  {".png", 4, "image/png", 9},
1752  {".svg", 4, "image/svg+xml", 13},
1753  {".torrent", 8, "application/x-bittorrent", 24},
1754  {".wav", 4, "audio/x-wav", 11},
1755  {".mp3", 4, "audio/x-mp3", 11},
1756  {".mid", 4, "audio/mid", 9},
1757  {".m3u", 4, "audio/x-mpegurl", 15},
1758  {".ram", 4, "audio/x-pn-realaudio", 20},
1759  {".xml", 4, "text/xml", 8},
1760  {".xslt", 5, "application/xml", 15},
1761  {".ra", 3, "audio/x-pn-realaudio", 20},
1762  {".doc", 4, "application/msword", 19},
1763  {".exe", 4, "application/octet-stream", 24},
1764  {".zip", 4, "application/x-zip-compressed", 28},
1765  {".xls", 4, "application/excel", 17},
1766  {".tgz", 4, "application/x-tar-gz", 20},
1767  {".tar", 4, "application/x-tar", 17},
1768  {".gz", 3, "application/x-gunzip", 20},
1769  {".arj", 4, "application/x-arj-compressed", 28},
1770  {".rar", 4, "application/x-arj-compressed", 28},
1771  {".rtf", 4, "application/rtf", 15},
1772  {".pdf", 4, "application/pdf", 15},
1773  {".swf", 4, "application/x-shockwave-flash",29},
1774  {".mpg", 4, "video/mpeg", 10},
1775  {".mpeg", 5, "video/mpeg", 10},
1776  {".mp4", 4, "video/mp4", 9},
1777  {".m4v", 4, "video/x-m4v", 11},
1778  {".asf", 4, "video/x-ms-asf", 14},
1779  {".avi", 4, "video/x-msvideo", 15},
1780  {".bmp", 4, "image/bmp", 9},
1781  {NULL, 0, NULL, 0}
1782 };
1783 
1784 // Look at the "path" extension and figure what mime type it has.
1785 // Store mime type in the vector.
1786 static void get_mime_type(struct mg_context *ctx, const char *path,
1787  struct vec *vec) {
1788  struct vec ext_vec, mime_vec;
1789  const char *list, *ext;
1790  size_t i, path_len;
1791 
1792  path_len = strlen(path);
1793 
1794  // Scan user-defined mime types first, in case user wants to
1795  // override default mime types.
1796  list = ctx->config[EXTRA_MIME_TYPES];
1797  while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
1798  // ext now points to the path suffix
1799  ext = path + path_len - ext_vec.len;
1800  if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
1801  *vec = mime_vec;
1802  return;
1803  }
1804  }
1805 
1806  // Now scan built-in mime types
1807  for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
1808  ext = path + (path_len - builtin_mime_types[i].ext_len);
1809  if (path_len > builtin_mime_types[i].ext_len &&
1810  mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
1811  vec->ptr = builtin_mime_types[i].mime_type;
1812  vec->len = builtin_mime_types[i].mime_type_len;
1813  return;
1814  }
1815  }
1816 
1817  // Nothing found. Fall back to "text/plain"
1818  vec->ptr = "text/plain";
1819  vec->len = 10;
1820 }
1821 
1822 #ifndef HAVE_MD5
1823 typedef struct MD5Context {
1824  uint32_t buf[4];
1826  unsigned char in[64];
1827 } MD5_CTX;
1828 
1829 #if defined(__BYTE_ORDER) && (__BYTE_ORDER == 1234)
1830 #define byteReverse(buf, len) // Do nothing
1831 #else
1832 static void byteReverse(unsigned char *buf, unsigned longs) {
1833  uint32_t t;
1834  do {
1835  t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
1836  ((unsigned) buf[1] << 8 | buf[0]);
1837  *(uint32_t *) buf = t;
1838  buf += 4;
1839  } while (--longs);
1840 }
1841 #endif
1842 
1843 #define F1(x, y, z) (z ^ (x & (y ^ z)))
1844 #define F2(x, y, z) F1(z, x, y)
1845 #define F3(x, y, z) (x ^ y ^ z)
1846 #define F4(x, y, z) (y ^ (x | ~z))
1847 
1848 #define MD5STEP(f, w, x, y, z, data, s) \
1849  ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
1850 
1851 // Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
1852 // initialization constants.
1853 static void MD5Init(MD5_CTX *ctx) {
1854  ctx->buf[0] = 0x67452301;
1855  ctx->buf[1] = 0xefcdab89;
1856  ctx->buf[2] = 0x98badcfe;
1857  ctx->buf[3] = 0x10325476;
1858 
1859  ctx->bits[0] = 0;
1860  ctx->bits[1] = 0;
1861 }
1862 
1863 static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
1864  register uint32_t a, b, c, d;
1865 
1866  a = buf[0];
1867  b = buf[1];
1868  c = buf[2];
1869  d = buf[3];
1870 
1871  MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
1872  MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
1873  MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
1874  MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
1875  MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
1876  MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
1877  MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
1878  MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
1879  MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
1880  MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
1881  MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
1882  MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
1883  MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
1884  MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
1885  MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
1886  MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
1887 
1888  MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
1889  MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
1890  MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
1891  MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
1892  MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
1893  MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
1894  MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
1895  MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
1896  MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
1897  MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
1898  MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
1899  MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
1900  MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
1901  MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
1902  MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
1903  MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
1904 
1905  MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
1906  MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
1907  MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
1908  MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
1909  MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
1910  MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
1911  MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
1912  MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
1913  MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
1914  MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
1915  MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
1916  MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
1917  MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
1918  MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
1919  MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
1920  MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
1921 
1922  MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
1923  MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
1924  MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
1925  MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
1926  MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
1927  MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
1928  MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
1929  MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
1930  MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
1931  MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
1932  MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
1933  MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
1934  MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
1935  MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
1936  MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
1937  MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
1938 
1939  buf[0] += a;
1940  buf[1] += b;
1941  buf[2] += c;
1942  buf[3] += d;
1943 }
1944 
1945 static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) {
1946  uint32_t t;
1947 
1948  t = ctx->bits[0];
1949  if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
1950  ctx->bits[1]++;
1951  ctx->bits[1] += len >> 29;
1952 
1953  t = (t >> 3) & 0x3f;
1954 
1955  if (t) {
1956  unsigned char *p = (unsigned char *) ctx->in + t;
1957 
1958  t = 64 - t;
1959  if (len < t) {
1960  memcpy(p, buf, len);
1961  return;
1962  }
1963  memcpy(p, buf, t);
1964  byteReverse(ctx->in, 16);
1965  MD5Transform(ctx->buf, (uint32_t *) ctx->in);
1966  buf += t;
1967  len -= t;
1968  }
1969 
1970  while (len >= 64) {
1971  memcpy(ctx->in, buf, 64);
1972  byteReverse(ctx->in, 16);
1973  MD5Transform(ctx->buf, (uint32_t *) ctx->in);
1974  buf += 64;
1975  len -= 64;
1976  }
1977 
1978  memcpy(ctx->in, buf, len);
1979 }
1980 
1981 static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) {
1982  unsigned count;
1983  unsigned char *p;
1984 
1985  count = (ctx->bits[0] >> 3) & 0x3F;
1986 
1987  p = ctx->in + count;
1988  *p++ = 0x80;
1989  count = 64 - 1 - count;
1990  if (count < 8) {
1991  memset(p, 0, count);
1992  byteReverse(ctx->in, 16);
1993  MD5Transform(ctx->buf, (uint32_t *) ctx->in);
1994  memset(ctx->in, 0, 56);
1995  } else {
1996  memset(p, 0, count - 8);
1997  }
1998  byteReverse(ctx->in, 14);
1999 
2000  memcpy(ctx->in + 14 * sizeof(uint32_t), ctx->bits, sizeof(ctx->bits));
2001 
2002  MD5Transform(ctx->buf, (uint32_t *) ctx->in);
2003  byteReverse((unsigned char *) ctx->buf, 4);
2004  memcpy(digest, ctx->buf, 16);
2005  memset((char *) ctx, 0, sizeof(*ctx));
2006 }
2007 #endif // !HAVE_MD5
2008 
2009 // Stringify binary data. Output buffer must be twice as big as input,
2010 // because each byte takes 2 bytes in string representation
2011 static void bin2str(char *to, const unsigned char *p, size_t len) {
2012  static const char *hex = "0123456789abcdef";
2013 
2014  for (; len--; p++) {
2015  *to++ = hex[p[0] >> 4];
2016  *to++ = hex[p[0] & 0x0f];
2017  }
2018  *to = '\0';
2019 }
2020 
2021 // Return stringified MD5 hash for list of vectors. Buffer must be 33 bytes.
2022 void mg_md5(char *buf, ...) {
2023  unsigned char hash[16];
2024  const char *p;
2025  va_list ap;
2026  MD5_CTX ctx;
2027 
2028  MD5Init(&ctx);
2029 
2030  va_start(ap, buf);
2031  while ((p = va_arg(ap, const char *)) != NULL) {
2032  MD5Update(&ctx, (const unsigned char *) p, (unsigned) strlen(p));
2033  }
2034  va_end(ap);
2035 
2036  MD5Final(hash, &ctx);
2037  bin2str(buf, hash, sizeof(hash));
2038 }
2039 
2040 // Check the user's password, return 1 if OK
2041 static int check_password(const char *method, const char *ha1, const char *uri,
2042  const char *nonce, const char *nc, const char *cnonce,
2043  const char *qop, const char *response) {
2044  char ha2[32 + 1], expected_response[32 + 1];
2045 
2046  // Some of the parameters may be NULL
2047  if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL ||
2048  qop == NULL || response == NULL) {
2049  return 0;
2050  }
2051 
2052  // NOTE(lsm): due to a bug in MSIE, we do not compare the URI
2053  // TODO(lsm): check for authentication timeout
2054  if (// strcmp(dig->uri, c->ouri) != 0 ||
2055  strlen(response) != 32
2056  // || now - strtoul(dig->nonce, NULL, 10) > 3600
2057  ) {
2058  return 0;
2059  }
2060 
2061  mg_md5(ha2, method, ":", uri, NULL);
2062  mg_md5(expected_response, ha1, ":", nonce, ":", nc,
2063  ":", cnonce, ":", qop, ":", ha2, NULL);
2064 
2065  return mg_strcasecmp(response, expected_response) == 0;
2066 }
2067 
2068 // Use the global passwords file, if specified by auth_gpass option,
2069 // or search for .htpasswd in the requested directory.
2070 static FILE *open_auth_file(struct mg_connection *conn, const char *path) {
2071  struct mg_context *ctx = conn->ctx;
2072  char name[PATH_MAX];
2073  const char *p, *e;
2074  struct mgstat st;
2075  FILE *fp;
2076 
2077  if (ctx->config[GLOBAL_PASSWORDS_FILE] != NULL) {
2078  // Use global passwords file
2079  fp = mg_fopen(ctx->config[GLOBAL_PASSWORDS_FILE], "r");
2080  if (fp == NULL)
2081  cry(fc(ctx), "fopen(%s): %s",
2082  ctx->config[GLOBAL_PASSWORDS_FILE], strerror(ERRNO));
2083  } else if (!mg_stat(path, &st) && st.is_directory) {
2084  (void) mg_snprintf(conn, name, sizeof(name), "%s%c%s",
2085  path, DIRSEP, PASSWORDS_FILE_NAME);
2086  fp = mg_fopen(name, "r");
2087  } else {
2088  // Try to find .htpasswd in requested directory.
2089  for (p = path, e = p + strlen(p) - 1; e > p; e--)
2090  if (IS_DIRSEP_CHAR(*e))
2091  break;
2092  (void) mg_snprintf(conn, name, sizeof(name), "%.*s%c%s",
2093  (int) (e - p), p, DIRSEP, PASSWORDS_FILE_NAME);
2094  fp = mg_fopen(name, "r");
2095  }
2096 
2097  return fp;
2098 }
2099 
2100 // Parsed Authorization header
2101 struct ah {
2102  char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
2103 };
2104 
2105 static int parse_auth_header(struct mg_connection *conn, char *buf,
2106  size_t buf_size, struct ah *ah) {
2107  char *name, *value, *s;
2108  const char *auth_header;
2109 
2110  if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||
2111  mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
2112  return 0;
2113  }
2114 
2115  // Make modifiable copy of the auth header
2116  (void) mg_strlcpy(buf, auth_header + 7, buf_size);
2117 
2118  s = buf;
2119  (void) memset(ah, 0, sizeof(*ah));
2120 
2121  // Parse authorization header
2122  for (;;) {
2123  // Gobble initial spaces
2124  while (isspace(* (unsigned char *) s)) {
2125  s++;
2126  }
2127  name = skip_quoted(&s, "=", " ", 0);
2128  // Value is either quote-delimited, or ends at first comma or space.
2129  if (s[0] == '\"') {
2130  s++;
2131  value = skip_quoted(&s, "\"", " ", '\\');
2132  if (s[0] == ',') {
2133  s++;
2134  }
2135  } else {
2136  value = skip_quoted(&s, ", ", " ", 0); // IE uses commas, FF uses spaces
2137  }
2138  if (*name == '\0') {
2139  break;
2140  }
2141 
2142  if (!strcmp(name, "username")) {
2143  ah->user = value;
2144  } else if (!strcmp(name, "cnonce")) {
2145  ah->cnonce = value;
2146  } else if (!strcmp(name, "response")) {
2147  ah->response = value;
2148  } else if (!strcmp(name, "uri")) {
2149  ah->uri = value;
2150  } else if (!strcmp(name, "qop")) {
2151  ah->qop = value;
2152  } else if (!strcmp(name, "nc")) {
2153  ah->nc = value;
2154  } else if (!strcmp(name, "nonce")) {
2155  ah->nonce = value;
2156  }
2157  }
2158 
2159  // CGI needs it as REMOTE_USER
2160  if (ah->user != NULL) {
2161  conn->request_info.remote_user = mg_strdup(ah->user);
2162  } else {
2163  return 0;
2164  }
2165 
2166  return 1;
2167 }
2168 
2169 // Authorize against the opened passwords file. Return 1 if authorized.
2170 static int authorize(struct mg_connection *conn, FILE *fp) {
2171  struct ah ah;
2172  char line[256], f_user[256], ha1[256], f_domain[256], buf[BUFSIZ];
2173 
2174  if (!parse_auth_header(conn, buf, sizeof(buf), &ah)) {
2175  return 0;
2176  }
2177 
2178  // Loop over passwords file
2179  while (fgets(line, sizeof(line), fp) != NULL) {
2180  if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) != 3) {
2181  continue;
2182  }
2183 
2184  if (!strcmp(ah.user, f_user) &&
2185  !strcmp(conn->ctx->config[AUTHENTICATION_DOMAIN], f_domain))
2186  return check_password(
2188  ha1, ah.uri, ah.nonce, ah.nc, ah.cnonce, ah.qop,
2189  ah.response);
2190  }
2191 
2192  return 0;
2193 }
2194 
2195 // Return 1 if request is authorised, 0 otherwise.
2196 static int check_authorization(struct mg_connection *conn, const char *path) {
2197  FILE *fp;
2198  char fname[PATH_MAX];
2199  struct vec uri_vec, filename_vec;
2200  const char *list;
2201  int authorized;
2202 
2203  fp = NULL;
2204  authorized = 1;
2205 
2206  list = conn->ctx->config[PROTECT_URI];
2207  while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
2208  if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {
2209  (void) mg_snprintf(conn, fname, sizeof(fname), "%.*s",
2210  (int) filename_vec.len, filename_vec.ptr);
2211  if ((fp = mg_fopen(fname, "r")) == NULL) {
2212  cry(conn, "%s: cannot open %s: %s", __func__, fname, strerror(errno));
2213  }
2214  break;
2215  }
2216  }
2217 
2218  if (fp == NULL) {
2219  fp = open_auth_file(conn, path);
2220  }
2221 
2222  if (fp != NULL) {
2223  authorized = authorize(conn, fp);
2224  (void) fclose(fp);
2225  }
2226 
2227  return authorized;
2228 }
2229 
2230 static void send_authorization_request(struct mg_connection *conn) {
2231  conn->request_info.status_code = 401;
2232  (void) mg_printf(conn,
2233  "HTTP/1.1 401 Unauthorized\r\n"
2234  "Content-Length: 0\r\n"
2235  "WWW-Authenticate: Digest qop=\"auth\", "
2236  "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
2238  (unsigned long) time(NULL));
2239 }
2240 
2241 static int is_authorized_for_put(struct mg_connection *conn) {
2242  FILE *fp;
2243  int ret = 0;
2244 
2245  fp = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL ? NULL :
2247 
2248  if (fp != NULL) {
2249  ret = authorize(conn, fp);
2250  (void) fclose(fp);
2251  }
2252 
2253  return ret;
2254 }
2255 
2256 int mg_modify_passwords_file(const char *fname, const char *domain,
2257  const char *user, const char *pass) {
2258  int found;
2259  char line[512], u[512], d[512], ha1[33], tmp[PATH_MAX];
2260  FILE *fp, *fp2;
2261 
2262  found = 0;
2263  fp = fp2 = NULL;
2264 
2265  // Regard empty password as no password - remove user record.
2266  if (pass != NULL && pass[0] == '\0') {
2267  pass = NULL;
2268  }
2269 
2270  (void) snprintf(tmp, sizeof(tmp), "%s.tmp", fname);
2271 
2272  // Create the file if does not exist
2273  if ((fp = mg_fopen(fname, "a+")) != NULL) {
2274  (void) fclose(fp);
2275  }
2276 
2277  // Open the given file and temporary file
2278  if ((fp = mg_fopen(fname, "r")) == NULL) {
2279  return 0;
2280  } else if ((fp2 = mg_fopen(tmp, "w+")) == NULL) {
2281  fclose(fp);
2282  return 0;
2283  }
2284 
2285  // Copy the stuff to temporary file
2286  while (fgets(line, sizeof(line), fp) != NULL) {
2287  if (sscanf(line, "%[^:]:%[^:]:%*s", u, d) != 2) {
2288  continue;
2289  }
2290 
2291  if (!strcmp(u, user) && !strcmp(d, domain)) {
2292  found++;
2293  if (pass != NULL) {
2294  mg_md5(ha1, user, ":", domain, ":", pass, NULL);
2295  fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
2296  }
2297  } else {
2298  (void) fprintf(fp2, "%s", line);
2299  }
2300  }
2301 
2302  // If new user, just add it
2303  if (!found && pass != NULL) {
2304  mg_md5(ha1, user, ":", domain, ":", pass, NULL);
2305  (void) fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
2306  }
2307 
2308  // Close files
2309  (void) fclose(fp);
2310  (void) fclose(fp2);
2311 
2312  // Put the temp file in place of real file
2313  (void) mg_remove(fname);
2314  (void) mg_rename(tmp, fname);
2315 
2316  return 1;
2317 }
2318 
2319 struct de {
2321  char *file_name;
2322  struct mgstat st;
2323 };
2324 
2325 static void url_encode(const char *src, char *dst, size_t dst_len) {
2326  static const char *dont_escape = "._-$,;~()";
2327  static const char *hex = "0123456789abcdef";
2328  const char *end = dst + dst_len - 1;
2329 
2330  for (; *src != '\0' && dst < end; src++, dst++) {
2331  if (isalnum(*(const unsigned char *) src) ||
2332  strchr(dont_escape, * (const unsigned char *) src) != NULL) {
2333  *dst = *src;
2334  } else if (dst + 2 < end) {
2335  dst[0] = '%';
2336  dst[1] = hex[(* (const unsigned char *) src) >> 4];
2337  dst[2] = hex[(* (const unsigned char *) src) & 0xf];
2338  dst += 2;
2339  }
2340  }
2341 
2342  *dst = '\0';
2343 }
2344 
2345 static void print_dir_entry(struct de *de) {
2346  char size[64], mod[64], href[PATH_MAX];
2347 
2348  if (de->st.is_directory) {
2349  (void) mg_snprintf(de->conn, size, sizeof(size), "%s", "[DIRECTORY]");
2350  } else {
2351  // We use (signed) cast below because MSVC 6 compiler cannot
2352  // convert unsigned __int64 to double. Sigh.
2353  if (de->st.size < 1024) {
2354  (void) mg_snprintf(de->conn, size, sizeof(size),
2355  "%lu", (unsigned long) de->st.size);
2356  } else if (de->st.size < 1024 * 1024) {
2357  (void) mg_snprintf(de->conn, size, sizeof(size),
2358  "%.1fk", (double) de->st.size / 1024.0);
2359  } else if (de->st.size < 1024 * 1024 * 1024) {
2360  (void) mg_snprintf(de->conn, size, sizeof(size),
2361  "%.1fM", (double) de->st.size / 1048576);
2362  } else {
2363  (void) mg_snprintf(de->conn, size, sizeof(size),
2364  "%.1fG", (double) de->st.size / 1073741824);
2365  }
2366  }
2367  (void) strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&de->st.mtime));
2368  url_encode(de->file_name, href, sizeof(href));
2369  de->conn->num_bytes_sent += mg_printf(de->conn,
2370  "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
2371  "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
2372  de->conn->request_info.uri, href, de->st.is_directory ? "/" : "",
2373  de->file_name, de->st.is_directory ? "/" : "", mod, size);
2374 }
2375 
2376 // This function is called from send_directory() and used for
2377 // sorting directory entries by size, or name, or modification time.
2378 // On windows, __cdecl specification is needed in case if project is built
2379 // with __stdcall convention. qsort always requires __cdels callback.
2380 static int WINCDECL compare_dir_entries(const void *p1, const void *p2) {
2381  const struct de *a = (const struct de *) p1, *b = (const struct de *) p2;
2382  const char *query_string = a->conn->request_info.query_string;
2383  int cmp_result = 0;
2384 
2385  if (query_string == NULL) {
2386  query_string = "na";
2387  }
2388 
2389  if (a->st.is_directory && !b->st.is_directory) {
2390  return -1; // Always put directories on top
2391  } else if (!a->st.is_directory && b->st.is_directory) {
2392  return 1; // Always put directories on top
2393  } else if (*query_string == 'n') {
2394  cmp_result = strcmp(a->file_name, b->file_name);
2395  } else if (*query_string == 's') {
2396  cmp_result = a->st.size == b->st.size ? 0 :
2397  a->st.size > b->st.size ? 1 : -1;
2398  } else if (*query_string == 'd') {
2399  cmp_result = a->st.mtime == b->st.mtime ? 0 :
2400  a->st.mtime > b->st.mtime ? 1 : -1;
2401  }
2402 
2403  return query_string[1] == 'd' ? -cmp_result : cmp_result;
2404 }
2405 
2406 static int scan_directory(struct mg_connection *conn, const char *dir,
2407  void *data, void (*cb)(struct de *, void *)) {
2408  char path[PATH_MAX];
2409  struct dirent *dp;
2410  DIR *dirp;
2411  struct de de;
2412 
2413  if ((dirp = opendir(dir)) == NULL) {
2414  return 0;
2415  } else {
2416  de.conn = conn;
2417 
2418  while ((dp = readdir(dirp)) != NULL) {
2419  // Do not show current dir and passwords file
2420  if (!strcmp(dp->d_name, ".") ||
2421  !strcmp(dp->d_name, "..") ||
2422  !strcmp(dp->d_name, PASSWORDS_FILE_NAME))
2423  continue;
2424 
2425  mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, DIRSEP, dp->d_name);
2426 
2427  // If we don't memset stat structure to zero, mtime will have
2428  // garbage and strftime() will segfault later on in
2429  // print_dir_entry(). memset is required only if mg_stat()
2430  // fails. For more details, see
2431  // http://code.google.com/p/mongoose/issues/detail?id=79
2432  if (mg_stat(path, &de.st) != 0) {
2433  memset(&de.st, 0, sizeof(de.st));
2434  }
2435  de.file_name = dp->d_name;
2436 
2437  cb(&de, data);
2438  }
2439  (void) closedir(dirp);
2440  }
2441  return 1;
2442 }
2443 
2445  struct de *entries;
2448 };
2449 
2450 static void dir_scan_callback(struct de *de, void *data) {
2451  struct dir_scan_data *dsd = (struct dir_scan_data *) data;
2452 
2453  if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
2454  dsd->arr_size *= 2;
2455  dsd->entries = (struct de *) realloc(dsd->entries, dsd->arr_size *
2456  sizeof(dsd->entries[0]));
2457  }
2458  if (dsd->entries == NULL) {
2459  // TODO(lsm): propagate an error to the caller
2460  dsd->num_entries = 0;
2461  } else {
2462  dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
2463  dsd->entries[dsd->num_entries].st = de->st;
2464  dsd->entries[dsd->num_entries].conn = de->conn;
2465  dsd->num_entries++;
2466  }
2467 }
2468 
2469 static void handle_directory_request(struct mg_connection *conn,
2470  const char *dir) {
2471  int i, sort_direction;
2472  struct dir_scan_data data = { NULL, 0, 128 };
2473 
2474  if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
2475  send_http_error(conn, 500, "Cannot open directory",
2476  "Error: opendir(%s): %s", dir, strerror(ERRNO));
2477  return;
2478  }
2479 
2480  sort_direction = conn->request_info.query_string != NULL &&
2481  conn->request_info.query_string[1] == 'd' ? 'a' : 'd';
2482 
2483  mg_printf(conn, "%s",
2484  "HTTP/1.1 200 OK\r\n"
2485  "Connection: close\r\n"
2486  "Content-Type: text/html; charset=utf-8\r\n\r\n");
2487 
2488  conn->num_bytes_sent += mg_printf(conn,
2489  "<html><head><title>Index of %s</title>"
2490  "<style>th {text-align: left;}</style></head>"
2491  "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
2492  "<tr><th><a href=\"?n%c\">Name</a></th>"
2493  "<th><a href=\"?d%c\">Modified</a></th>"
2494  "<th><a href=\"?s%c\">Size</a></th></tr>"
2495  "<tr><td colspan=\"3\"><hr></td></tr>",
2496  conn->request_info.uri, conn->request_info.uri,
2497  sort_direction, sort_direction, sort_direction);
2498 
2499  // Print first entry - link to a parent directory
2500  conn->num_bytes_sent += mg_printf(conn,
2501  "<tr><td><a href=\"%s%s\">%s</a></td>"
2502  "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
2503  conn->request_info.uri, "..", "Parent directory", "-", "-");
2504 
2505  // Sort and print directory entries
2506  qsort(data.entries, (size_t) data.num_entries, sizeof(data.entries[0]),
2508  for (i = 0; i < data.num_entries; i++) {
2509  print_dir_entry(&data.entries[i]);
2510  free(data.entries[i].file_name);
2511  }
2512  free(data.entries);
2513 
2514  conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
2515  conn->request_info.status_code = 200;
2516 }
2517 
2518 // Send len bytes from the opened file to the client.
2519 static void send_file_data(struct mg_connection *conn, FILE *fp, int64_t len) {
2520  char buf[BUFSIZ];
2521  int to_read, num_read, num_written;
2522 
2523  while (len > 0) {
2524  // Calculate how much to read from the file in the buffer
2525  to_read = sizeof(buf);
2526  if ((int64_t) to_read > len)
2527  to_read = (int) len;
2528 
2529  // Read from file, exit the loop on error
2530  if ((num_read = fread(buf, 1, (size_t)to_read, fp)) == 0)
2531  break;
2532 
2533  // Send read bytes to the client, exit the loop on error
2534  if ((num_written = mg_write(conn, buf, (size_t)num_read)) != num_read)
2535  break;
2536 
2537  // Both read and were successful, adjust counters
2538  conn->num_bytes_sent += num_written;
2539  len -= num_written;
2540  }
2541 }
2542 
2543 static int parse_range_header(const char *header, int64_t *a, int64_t *b) {
2544  return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
2545 }
2546 
2547 static void gmt_time_string(char *buf, size_t buf_len, time_t *t) {
2548  strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
2549 }
2550 
2551 static void handle_file_request(struct mg_connection *conn, const char *path,
2552  struct mgstat *stp) {
2553  char date[64], lm[64], etag[64], range[64];
2554  const char *msg = "OK", *hdr;
2555  time_t curtime = time(NULL);
2556  int64_t cl, r1, r2;
2557  struct vec mime_vec;
2558  FILE *fp;
2559  int n;
2560 
2561  get_mime_type(conn->ctx, path, &mime_vec);
2562  cl = stp->size;
2563  conn->request_info.status_code = 200;
2564  range[0] = '\0';
2565 
2566  if ((fp = mg_fopen(path, "rb")) == NULL) {
2567  send_http_error(conn, 500, http_500_error,
2568  "fopen(%s): %s", path, strerror(ERRNO));
2569  return;
2570  }
2571  set_close_on_exec(fileno(fp));
2572 
2573  // If Range: header specified, act accordingly
2574  r1 = r2 = 0;
2575  hdr = mg_get_header(conn, "Range");
2576  if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0) {
2577  conn->request_info.status_code = 206;
2578  (void) fseeko(fp, (off_t) r1, SEEK_SET);
2579  cl = n == 2 ? r2 - r1 + 1: cl - r1;
2580  (void) mg_snprintf(conn, range, sizeof(range),
2581  "Content-Range: bytes "
2582  "%" INT64_FMT "-%"
2583  INT64_FMT "/%" INT64_FMT "\r\n",
2584  r1, r1 + cl - 1, stp->size);
2585  msg = "Partial Content";
2586  }
2587 
2588  // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
2589  // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
2590  gmt_time_string(date, sizeof(date), &curtime);
2591  gmt_time_string(lm, sizeof(lm), &stp->mtime);
2592  (void) mg_snprintf(conn, etag, sizeof(etag), "%lx.%lx",
2593  (unsigned long) stp->mtime, (unsigned long) stp->size);
2594 
2595  (void) mg_printf(conn,
2596  "HTTP/1.1 %d %s\r\n"
2597  "Date: %s\r\n"
2598  "Last-Modified: %s\r\n"
2599  "Etag: \"%s\"\r\n"
2600  "Content-Type: %.*s\r\n"
2601  "Content-Length: %" INT64_FMT "\r\n"
2602  "Connection: %s\r\n"
2603  "Accept-Ranges: bytes\r\n"
2604  "%s\r\n",
2605  conn->request_info.status_code, msg, date, lm, etag,
2606  (int) mime_vec.len, mime_vec.ptr, cl, suggest_connection_header(conn), range);
2607 
2608  if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
2609  send_file_data(conn, fp, cl);
2610  }
2611  (void) fclose(fp);
2612 }
2613 
2614 void mg_send_file(struct mg_connection *conn, const char *path) {
2615  struct mgstat st;
2616  if (mg_stat(path, &st) == 0) {
2617  handle_file_request(conn, path, &st);
2618  } else {
2619  send_http_error(conn, 404, "Not Found", "%s", "File not found");
2620  }
2621 }
2622 
2623 
2624 // Parse HTTP headers from the given buffer, advance buffer to the point
2625 // where parsing stopped.
2626 static void parse_http_headers(char **buf, struct mg_request_info *ri) {
2627  int i;
2628 
2629  for (i = 0; i < (int) ARRAY_SIZE(ri->http_headers); i++) {
2630  ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);
2631  ri->http_headers[i].value = skip(buf, "\r\n");
2632  if (ri->http_headers[i].name[0] == '\0')
2633  break;
2634  ri->num_headers = i + 1;
2635  }
2636 }
2637 
2638 static int is_valid_http_method(const char *method) {
2639  return !strcmp(method, "GET") || !strcmp(method, "POST") ||
2640  !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||
2641  !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||
2642  !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND");
2643 }
2644 
2645 // Parse HTTP request, fill in mg_request_info structure.
2646 static int parse_http_request(char *buf, struct mg_request_info *ri) {
2647  int status = 0;
2648 
2649  // RFC says that all initial whitespaces should be ingored
2650  while (*buf != '\0' && isspace(* (unsigned char *) buf)) {
2651  buf++;
2652  }
2653 
2654  ri->request_method = skip(&buf, " ");
2655  ri->uri = skip(&buf, " ");
2656  ri->http_version = skip(&buf, "\r\n");
2657 
2659  strncmp(ri->http_version, "HTTP/", 5) == 0) {
2660  ri->http_version += 5; // Skip "HTTP/"
2661  parse_http_headers(&buf, ri);
2662  status = 1;
2663  }
2664 
2665  return status;
2666 }
2667 
2668 // Keep reading the input (either opened file descriptor fd, or socket sock,
2669 // or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
2670 // buffer (which marks the end of HTTP request). Buffer buf may already
2671 // have some data. The length of the data is stored in nread.
2672 // Upon every read operation, increase nread by the number of bytes read.
2673 static int read_request(FILE *fp, SOCKET sock, SSL *ssl, char *buf, int bufsiz,
2674  int *nread) {
2675  int n, request_len;
2676 
2677  request_len = 0;
2678  while (*nread < bufsiz && request_len == 0) {
2679  n = pull(fp, sock, ssl, buf + *nread, bufsiz - *nread);
2680  if (n <= 0) {
2681  break;
2682  } else {
2683  *nread += n;
2684  request_len = get_request_len(buf, *nread);
2685  }
2686  }
2687 
2688  return request_len;
2689 }
2690 
2691 // For given directory path, substitute it to valid index file.
2692 // Return 0 if index file has been found, -1 if not found.
2693 // If the file is found, it's stats is returned in stp.
2694 static int substitute_index_file(struct mg_connection *conn, char *path,
2695  size_t path_len, struct mgstat *stp) {
2696  const char *list = conn->ctx->config[INDEX_FILES];
2697  struct mgstat st;
2698  struct vec filename_vec;
2699  size_t n = strlen(path);
2700  int found = 0;
2701 
2702  // The 'path' given to us points to the directory. Remove all trailing
2703  // directory separator characters from the end of the path, and
2704  // then append single directory separator character.
2705  while (n > 0 && IS_DIRSEP_CHAR(path[n - 1])) {
2706  n--;
2707  }
2708  path[n] = DIRSEP;
2709 
2710  // Traverse index files list. For each entry, append it to the given
2711  // path and see if the file exists. If it exists, break the loop
2712  while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
2713 
2714  // Ignore too long entries that may overflow path buffer
2715  if (filename_vec.len > path_len - n)
2716  continue;
2717 
2718  // Prepare full path to the index file
2719  (void) mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
2720 
2721  // Does it exist?
2722  if (mg_stat(path, &st) == 0) {
2723  // Yes it does, break the loop
2724  *stp = st;
2725  found = 1;
2726  break;
2727  }
2728  }
2729 
2730  // If no index file exists, restore directory path
2731  if (!found) {
2732  path[n] = '\0';
2733  }
2734 
2735  return found;
2736 }
2737 
2738 // Return True if we should reply 304 Not Modified.
2739 static int is_not_modified(const struct mg_connection *conn,
2740  const struct mgstat *stp) {
2741  const char *ims = mg_get_header(conn, "If-Modified-Since");
2742  return ims != NULL && stp->mtime <= parse_date_string(ims);
2743 }
2744 
2745 static int forward_body_data(struct mg_connection *conn, FILE *fp,
2746  SOCKET sock, SSL *ssl) {
2747  const char *expect, *buffered;
2748  char buf[BUFSIZ];
2749  int to_read, nread, buffered_len, success = 0;
2750 
2751  expect = mg_get_header(conn, "Expect");
2752  assert(fp != NULL);
2753 
2754  if (conn->content_len == -1) {
2755  send_http_error(conn, 411, "Length Required", "");
2756  } else if (expect != NULL && mg_strcasecmp(expect, "100-continue")) {
2757  send_http_error(conn, 417, "Expectation Failed", "");
2758  } else {
2759  if (expect != NULL) {
2760  (void) mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
2761  }
2762 
2763  buffered = conn->buf + conn->request_len;
2764  buffered_len = conn->data_len - conn->request_len;
2765  assert(buffered_len >= 0);
2766  assert(conn->consumed_content == 0);
2767 
2768  if (buffered_len > 0) {
2769  if ((int64_t) buffered_len > conn->content_len) {
2770  buffered_len = (int) conn->content_len;
2771  }
2772  push(fp, sock, ssl, buffered, (int64_t) buffered_len);
2773  conn->consumed_content += buffered_len;
2774  }
2775 
2776  while (conn->consumed_content < conn->content_len) {
2777  to_read = sizeof(buf);
2778  if ((int64_t) to_read > conn->content_len - conn->consumed_content) {
2779  to_read = (int) (conn->content_len - conn->consumed_content);
2780  }
2781  nread = pull(NULL, conn->client.sock, conn->ssl, buf, to_read);
2782  if (nread <= 0 || push(fp, sock, ssl, buf, nread) != nread) {
2783  break;
2784  }
2785  conn->consumed_content += nread;
2786  }
2787 
2788  if (conn->consumed_content == conn->content_len) {
2789  success = 1;
2790  }
2791 
2792  // Each error code path in this function must send an error
2793  if (!success) {
2794  send_http_error(conn, 577, http_500_error, "");
2795  }
2796  }
2797 
2798  return success;
2799 }
2800 
2801 #if !defined(NO_CGI)
2802 // This structure helps to create an environment for the spawned CGI program.
2803 // Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
2804 // last element must be NULL.
2805 // However, on Windows there is a requirement that all these VARIABLE=VALUE\0
2806 // strings must reside in a contiguous buffer. The end of the buffer is
2807 // marked by two '\0' characters.
2808 // We satisfy both worlds: we create an envp array (which is vars), all
2809 // entries are actually pointers inside buf.
2810 struct cgi_env_block {
2811  struct mg_connection *conn;
2812  char buf[CGI_ENVIRONMENT_SIZE]; // Environment buffer
2813  int len; // Space taken
2814  char *vars[MAX_CGI_ENVIR_VARS]; // char **envp
2815  int nvars; // Number of variables
2816 };
2817 
2818 // Append VARIABLE=VALUE\0 string to the buffer, and add a respective
2819 // pointer into the vars array.
2820 static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {
2821  int n, space;
2822  char *added;
2823  va_list ap;
2824 
2825  // Calculate how much space is left in the buffer
2826  space = sizeof(block->buf) - block->len - 2;
2827  assert(space >= 0);
2828 
2829  // Make a pointer to the free space int the buffer
2830  added = block->buf + block->len;
2831 
2832  // Copy VARIABLE=VALUE\0 string into the free space
2833  va_start(ap, fmt);
2834  n = mg_vsnprintf(block->conn, added, (size_t) space, fmt, ap);
2835  va_end(ap);
2836 
2837  // Make sure we do not overflow buffer and the envp array
2838  if (n > 0 && n < space &&
2839  block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
2840  // Append a pointer to the added string into the envp array
2841  block->vars[block->nvars++] = block->buf + block->len;
2842  // Bump up used length counter. Include \0 terminator
2843  block->len += n + 1;
2844  }
2845 
2846  return added;
2847 }
2848 
2849 static void prepare_cgi_environment(struct mg_connection *conn,
2850  const char *prog,
2851  struct cgi_env_block *blk) {
2852  const char *s, *slash;
2853  struct vec var_vec, root;
2854  char *p;
2855  int i;
2856 
2857  blk->len = blk->nvars = 0;
2858  blk->conn = conn;
2859 
2860  get_document_root(conn, &root);
2861 
2862  addenv(blk, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
2863  addenv(blk, "SERVER_ROOT=%.*s", root.len, root.ptr);
2864  addenv(blk, "DOCUMENT_ROOT=%.*s", root.len, root.ptr);
2865 
2866  // Prepare the environment block
2867  addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
2868  addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
2869  addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP
2870  addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.u.sin.sin_port));
2871  addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method);
2872  addenv(blk, "REMOTE_ADDR=%s",
2873  inet_ntoa(conn->client.rsa.u.sin.sin_addr));
2874  addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port);
2875  addenv(blk, "REQUEST_URI=%s", conn->request_info.uri);
2876 
2877  // SCRIPT_NAME
2878  assert(conn->request_info.uri[0] == '/');
2879  slash = strrchr(conn->request_info.uri, '/');
2880  if ((s = strrchr(prog, '/')) == NULL)
2881  s = prog;
2882  addenv(blk, "SCRIPT_NAME=%.*s%s", slash - conn->request_info.uri,
2883  conn->request_info.uri, s);
2884 
2885  addenv(blk, "SCRIPT_FILENAME=%s", prog);
2886  addenv(blk, "PATH_TRANSLATED=%s", prog);
2887  addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
2888 
2889  if ((s = mg_get_header(conn, "Content-Type")) != NULL)
2890  addenv(blk, "CONTENT_TYPE=%s", s);
2891 
2892  if (conn->request_info.query_string != NULL)
2893  addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string);
2894 
2895  if ((s = mg_get_header(conn, "Content-Length")) != NULL)
2896  addenv(blk, "CONTENT_LENGTH=%s", s);
2897 
2898  if ((s = getenv("PATH")) != NULL)
2899  addenv(blk, "PATH=%s", s);
2900 
2901 #if defined(_WIN32)
2902  if ((s = getenv("COMSPEC")) != NULL)
2903  addenv(blk, "COMSPEC=%s", s);
2904  if ((s = getenv("SYSTEMROOT")) != NULL)
2905  addenv(blk, "SYSTEMROOT=%s", s);
2906 #else
2907  if ((s = getenv("LD_LIBRARY_PATH")) != NULL)
2908  addenv(blk, "LD_LIBRARY_PATH=%s", s);
2909 #endif // _WIN32
2910 
2911  if ((s = getenv("PERLLIB")) != NULL)
2912  addenv(blk, "PERLLIB=%s", s);
2913 
2914  if (conn->request_info.remote_user != NULL) {
2915  addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user);
2916  addenv(blk, "%s", "AUTH_TYPE=Digest");
2917  }
2918 
2919  // Add all headers as HTTP_* variables
2920  for (i = 0; i < conn->request_info.num_headers; i++) {
2921  p = addenv(blk, "HTTP_%s=%s",
2922  conn->request_info.http_headers[i].name,
2923  conn->request_info.http_headers[i].value);
2924 
2925  // Convert variable name into uppercase, and change - to _
2926  for (; *p != '=' && *p != '\0'; p++) {
2927  if (*p == '-')
2928  *p = '_';
2929  *p = (char) toupper(* (unsigned char *) p);
2930  }
2931  }
2932 
2933  // Add user-specified variables
2934  s = conn->ctx->config[CGI_ENVIRONMENT];
2935  while ((s = next_option(s, &var_vec, NULL)) != NULL) {
2936  addenv(blk, "%.*s", var_vec.len, var_vec.ptr);
2937  }
2938 
2939  blk->vars[blk->nvars++] = NULL;
2940  blk->buf[blk->len++] = '\0';
2941 
2942  assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
2943  assert(blk->len > 0);
2944  assert(blk->len < (int) sizeof(blk->buf));
2945 }
2946 
2947 static void handle_cgi_request(struct mg_connection *conn, const char *prog) {
2948  int headers_len, data_len, i, fd_stdin[2], fd_stdout[2];
2949  const char *status;
2950  char buf[BUFSIZ], *pbuf, dir[PATH_MAX], *p;
2951  struct mg_request_info ri;
2952  struct cgi_env_block blk;
2953  FILE *in, *out;
2954  pid_t pid;
2955 
2956  prepare_cgi_environment(conn, prog, &blk);
2957 
2958  // CGI must be executed in its own directory. 'dir' must point to the
2959  // directory containing executable program, 'p' must point to the
2960  // executable program name relative to 'dir'.
2961  (void) mg_snprintf(conn, dir, sizeof(dir), "%s", prog);
2962  if ((p = strrchr(dir, DIRSEP)) != NULL) {
2963  *p++ = '\0';
2964  } else {
2965  dir[0] = '.', dir[1] = '\0';
2966  p = (char *) prog;
2967  }
2968 
2969  pid = (pid_t) -1;
2970  fd_stdin[0] = fd_stdin[1] = fd_stdout[0] = fd_stdout[1] = -1;
2971  in = out = NULL;
2972 
2973  if (pipe(fd_stdin) != 0 || pipe(fd_stdout) != 0) {
2974  send_http_error(conn, 500, http_500_error,
2975  "Cannot create CGI pipe: %s", strerror(ERRNO));
2976  goto done;
2977  } else if ((pid = spawn_process(conn, p, blk.buf, blk.vars,
2978  fd_stdin[0], fd_stdout[1], dir)) == (pid_t) -1) {
2979  goto done;
2980  } else if ((in = fdopen(fd_stdin[1], "wb")) == NULL ||
2981  (out = fdopen(fd_stdout[0], "rb")) == NULL) {
2982  send_http_error(conn, 500, http_500_error,
2983  "fopen: %s", strerror(ERRNO));
2984  goto done;
2985  }
2986 
2987  setbuf(in, NULL);
2988  setbuf(out, NULL);
2989 
2990  // spawn_process() must close those!
2991  // If we don't mark them as closed, close() attempt before
2992  // return from this function throws an exception on Windows.
2993  // Windows does not like when closed descriptor is closed again.
2994  fd_stdin[0] = fd_stdout[1] = -1;
2995 
2996  // Send POST data to the CGI process if needed
2997  if (!strcmp(conn->request_info.request_method, "POST") &&
2998  !forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
2999  goto done;
3000  }
3001 
3002  // Now read CGI reply into a buffer. We need to set correct
3003  // status code, thus we need to see all HTTP headers first.
3004  // Do not send anything back to client, until we buffer in all
3005  // HTTP headers.
3006  data_len = 0;
3007  headers_len = read_request(out, INVALID_SOCKET, NULL,
3008  buf, sizeof(buf), &data_len);
3009  if (headers_len <= 0) {
3010  send_http_error(conn, 500, http_500_error,
3011  "CGI program sent malformed HTTP headers: [%.*s]",
3012  data_len, buf);
3013  goto done;
3014  }
3015  pbuf = buf;
3016  buf[headers_len - 1] = '\0';
3017  parse_http_headers(&pbuf, &ri);
3018 
3019  // Make up and send the status line
3020  status = get_header(&ri, "Status");
3021  conn->request_info.status_code = status == NULL ? 200 : atoi(status);
3022  (void) mg_printf(conn, "HTTP/1.1 %d OK\r\n", conn->request_info.status_code);
3023 
3024  // Send headers
3025  for (i = 0; i < ri.num_headers; i++) {
3026  mg_printf(conn, "%s: %s\r\n",
3027  ri.http_headers[i].name, ri.http_headers[i].value);
3028  }
3029  (void) mg_write(conn, "\r\n", 2);
3030 
3031  // Send chunk of data that may be read after the headers
3032  conn->num_bytes_sent += mg_write(conn, buf + headers_len,
3033  (size_t)(data_len - headers_len));
3034 
3035  // Read the rest of CGI output and send to the client
3036  send_file_data(conn, out, INT64_MAX);
3037 
3038 done:
3039  if (pid != (pid_t) -1) {
3040  kill(pid, SIGKILL);
3041  }
3042  if (fd_stdin[0] != -1) {
3043  (void) close(fd_stdin[0]);
3044  }
3045  if (fd_stdout[1] != -1) {
3046  (void) close(fd_stdout[1]);
3047  }
3048 
3049  if (in != NULL) {
3050  (void) fclose(in);
3051  } else if (fd_stdin[1] != -1) {
3052  (void) close(fd_stdin[1]);
3053  }
3054 
3055  if (out != NULL) {
3056  (void) fclose(out);
3057  } else if (fd_stdout[0] != -1) {
3058  (void) close(fd_stdout[0]);
3059  }
3060 }
3061 #endif // !NO_CGI
3062 
3063 // For a given PUT path, create all intermediate subdirectories
3064 // for given path. Return 0 if the path itself is a directory,
3065 // or -1 on error, 1 if OK.
3066 static int put_dir(const char *path) {
3067  char buf[PATH_MAX];
3068  const char *s, *p;
3069  struct mgstat st;
3070  int len, res = 1;
3071 
3072  for (s = p = path + 2; (p = strchr(s, DIRSEP)) != NULL; s = ++p) {
3073  len = p - path;
3074  if (len >= (int) sizeof(buf)) {
3075  res = -1;
3076  break;
3077  }
3078  memcpy(buf, path, len);
3079  buf[len] = '\0';
3080 
3081  // Try to create intermediate directory
3082  DEBUG_TRACE(("mkdir(%s)", buf));
3083  if (mg_stat(buf, &st) == -1 && mg_mkdir(buf, 0755) != 0) {
3084  res = -1;
3085  break;
3086  }
3087 
3088  // Is path itself a directory?
3089  if (p[1] == '\0') {
3090  res = 0;
3091  }
3092  }
3093 
3094  return res;
3095 }
3096 
3097 static void put_file(struct mg_connection *conn, const char *path) {
3098  struct mgstat st;
3099  const char *range;
3100  int64_t r1, r2;
3101  FILE *fp;
3102  int rc;
3103 
3104  conn->request_info.status_code = mg_stat(path, &st) == 0 ? 200 : 201;
3105 
3106  if ((rc = put_dir(path)) == 0) {
3107  mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", conn->request_info.status_code);
3108  } else if (rc == -1) {
3109  send_http_error(conn, 500, http_500_error,
3110  "put_dir(%s): %s", path, strerror(ERRNO));
3111  } else if ((fp = mg_fopen(path, "wb+")) == NULL) {
3112  send_http_error(conn, 500, http_500_error,
3113  "fopen(%s): %s", path, strerror(ERRNO));
3114  } else {
3115  set_close_on_exec(fileno(fp));
3116  range = mg_get_header(conn, "Content-Range");
3117  r1 = r2 = 0;
3118  if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
3119  conn->request_info.status_code = 206;
3120  // TODO(lsm): handle seek error
3121  (void) fseeko(fp, (off_t) r1, SEEK_SET);
3122  }
3123  if (forward_body_data(conn, fp, INVALID_SOCKET, NULL))
3124  (void) mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n",
3125  conn->request_info.status_code);
3126  (void) fclose(fp);
3127  }
3128 }
3129 
3130 static void send_ssi_file(struct mg_connection *, const char *, FILE *, int);
3131 
3132 static void do_ssi_include(struct mg_connection *conn, const char *ssi,
3133  char *tag, int include_level) {
3134  char file_name[BUFSIZ], path[PATH_MAX], *p;
3135  struct vec root = {0};
3136  int is_ssi;
3137  FILE *fp;
3138 
3139  get_document_root(conn, &root);
3140 
3141  // sscanf() is safe here, since send_ssi_file() also uses buffer
3142  // of size BUFSIZ to get the tag. So strlen(tag) is always < BUFSIZ.
3143  if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
3144  // File name is relative to the webserver root
3145  (void) mg_snprintf(conn, path, sizeof(path), "%.*s%c%s",
3146  (int) root.len, root.ptr, DIRSEP, file_name);
3147  } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1) {
3148  // File name is relative to the webserver working directory
3149  // or it is absolute system path
3150  (void) mg_snprintf(conn, path, sizeof(path), "%s", file_name);
3151  } else if (sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
3152  // File name is relative to the currect document
3153  (void) mg_snprintf(conn, path, sizeof(path), "%s", ssi);
3154  if ((p = strrchr(path, DIRSEP)) != NULL) {
3155  p[1] = '\0';
3156  }
3157  (void) mg_snprintf(conn, path + strlen(path),
3158  sizeof(path) - strlen(path), "%s", file_name);
3159  } else {
3160  cry(conn, "Bad SSI #include: [%s]", tag);
3161  return;
3162  }
3163 
3164  if ((fp = mg_fopen(path, "rb")) == NULL) {
3165  cry(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",
3166  tag, path, strerror(ERRNO));
3167  } else {
3168  set_close_on_exec(fileno(fp));
3169  is_ssi = match_extension(path, conn->ctx->config[SSI_EXTENSIONS]);
3170  if (is_ssi) {
3171  send_ssi_file(conn, path, fp, include_level + 1);
3172  } else {
3173  send_file_data(conn, fp, INT64_MAX);
3174  }
3175  (void) fclose(fp);
3176  }
3177 }
3178 
3179 #if !defined(NO_POPEN)
3180 static void do_ssi_exec(struct mg_connection *conn, char *tag) {
3181  char cmd[BUFSIZ];
3182  FILE *fp;
3183 
3184  if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
3185  cry(conn, "Bad SSI #exec: [%s]", tag);
3186  } else if ((fp = popen(cmd, "r")) == NULL) {
3187  cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
3188  } else {
3189  send_file_data(conn, fp, INT64_MAX);
3190  (void) pclose(fp);
3191  }
3192 }
3193 #endif // !NO_POPEN
3194 
3195 static void send_ssi_file(struct mg_connection *conn, const char *path,
3196  FILE *fp, int include_level) {
3197  char buf[BUFSIZ];
3198  int ch, len, in_ssi_tag;
3199 
3200  if (include_level > 10) {
3201  cry(conn, "SSI #include level is too deep (%s)", path);
3202  return;
3203  }
3204 
3205  in_ssi_tag = 0;
3206  len = 0;
3207 
3208  while ((ch = fgetc(fp)) != EOF) {
3209  if (in_ssi_tag && ch == '>') {
3210  in_ssi_tag = 0;
3211  buf[len++] = (char) ch;
3212  buf[len] = '\0';
3213  assert(len <= (int) sizeof(buf));
3214  if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
3215  // Not an SSI tag, pass it
3216  (void) mg_write(conn, buf, (size_t)len);
3217  } else {
3218  if (!memcmp(buf + 5, "include", 7)) {
3219  do_ssi_include(conn, path, buf + 12, include_level);
3220 #if !defined(NO_POPEN)
3221  } else if (!memcmp(buf + 5, "exec", 4)) {
3222  do_ssi_exec(conn, buf + 9);
3223 #endif // !NO_POPEN
3224  } else {
3225  cry(conn, "%s: unknown SSI " "command: \"%s\"", path, buf);
3226  }
3227  }
3228  len = 0;
3229  } else if (in_ssi_tag) {
3230  if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
3231  // Not an SSI tag
3232  in_ssi_tag = 0;
3233  } else if (len == (int) sizeof(buf) - 2) {
3234  cry(conn, "%s: SSI tag is too large", path);
3235  len = 0;
3236  }
3237  buf[len++] = ch & 0xff;
3238  } else if (ch == '<') {
3239  in_ssi_tag = 1;
3240  if (len > 0) {
3241  (void) mg_write(conn, buf, (size_t)len);
3242  }
3243  len = 0;
3244  buf[len++] = ch & 0xff;
3245  } else {
3246  buf[len++] = ch & 0xff;
3247  if (len == (int) sizeof(buf)) {
3248  (void) mg_write(conn, buf, (size_t)len);
3249  len = 0;
3250  }
3251  }
3252  }
3253 
3254  // Send the rest of buffered data
3255  if (len > 0) {
3256  (void) mg_write(conn, buf, (size_t)len);
3257  }
3258 }
3259 
3260 static void handle_ssi_file_request(struct mg_connection *conn,
3261  const char *path) {
3262  FILE *fp;
3263 
3264  if ((fp = mg_fopen(path, "rb")) == NULL) {
3265  send_http_error(conn, 500, http_500_error, "fopen(%s): %s", path,
3266  strerror(ERRNO));
3267  } else {
3268  set_close_on_exec(fileno(fp));
3269  mg_printf(conn, "HTTP/1.1 200 OK\r\n"
3270  "Content-Type: text/html\r\nConnection: %s\r\n\r\n",
3272  send_ssi_file(conn, path, fp, 0);
3273  (void) fclose(fp);
3274  }
3275 }
3276 
3277 static void send_options(struct mg_connection *conn) {
3278  conn->request_info.status_code = 200;
3279 
3280  (void) mg_printf(conn,
3281  "HTTP/1.1 200 OK\r\n"
3282  "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS\r\n"
3283  "DAV: 1\r\n\r\n");
3284 }
3285 
3286 // Writes PROPFIND properties for a collection element
3287 static void print_props(struct mg_connection *conn, const char* uri,
3288  struct mgstat* st) {
3289  char mtime[64];
3290  gmt_time_string(mtime, sizeof(mtime), &st->mtime);
3291  conn->num_bytes_sent += mg_printf(conn,
3292  "<d:response>"
3293  "<d:href>%s</d:href>"
3294  "<d:propstat>"
3295  "<d:prop>"
3296  "<d:resourcetype>%s</d:resourcetype>"
3297  "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
3298  "<d:getlastmodified>%s</d:getlastmodified>"
3299  "</d:prop>"
3300  "<d:status>HTTP/1.1 200 OK</d:status>"
3301  "</d:propstat>"
3302  "</d:response>\n",
3303  uri,
3304  st->is_directory ? "<d:collection/>" : "",
3305  st->size,
3306  mtime);
3307 }
3308 
3309 static void print_dav_dir_entry(struct de *de, void *data) {
3310  char href[PATH_MAX];
3311  struct mg_connection *conn = (struct mg_connection *) data;
3312  mg_snprintf(conn, href, sizeof(href), "%s%s",
3313  conn->request_info.uri, de->file_name);
3314  print_props(conn, href, &de->st);
3315 }
3316 
3317 static void handle_propfind(struct mg_connection *conn, const char* path,
3318  struct mgstat* st) {
3319  const char *depth = mg_get_header(conn, "Depth");
3320 
3321  conn->request_info.status_code = 207;
3322  mg_printf(conn, "HTTP/1.1 207 Multi-Status\r\n"
3323  "Connection: close\r\n"
3324  "Content-Type: text/xml; charset=utf-8\r\n\r\n");
3325 
3326  conn->num_bytes_sent += mg_printf(conn,
3327  "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
3328  "<d:multistatus xmlns:d='DAV:'>\n");
3329 
3330  // Print properties for the requested resource itself
3331  print_props(conn, conn->request_info.uri, st);
3332 
3333  // If it is a directory, print directory entries too if Depth is not 0
3334  if (st->is_directory &&
3335  !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") &&
3336  (depth == NULL || strcmp(depth, "0") != 0)) {
3337  scan_directory(conn, path, conn, &print_dav_dir_entry);
3338  }
3339 
3340  conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
3341 }
3342 
3343 // This is the heart of the Mongoose's logic.
3344 // This function is called when the request is read, parsed and validated,
3345 // and Mongoose must decide what action to take: serve a file, or
3346 // a directory, or call embedded function, etcetera.
3347 static void handle_request(struct mg_connection *conn) {
3348  struct mg_request_info *ri = &conn->request_info;
3349  char path[PATH_MAX];
3350  int uri_len;
3351  struct mgstat st;
3352 
3353  if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL) {
3354  * conn->request_info.query_string++ = '\0';
3355  }
3356  uri_len = strlen(ri->uri);
3357  url_decode(ri->uri, (size_t)uri_len, ri->uri, (size_t)(uri_len + 1), 0);
3359  convert_uri_to_file_name(conn, ri->uri, path, sizeof(path));
3360 
3361  DEBUG_TRACE(("%s", ri->uri));
3362  if (!check_authorization(conn, path)) {
3364  } else if (call_user(conn, MG_NEW_REQUEST) != NULL) {
3365  // Do nothing, callback has served the request
3366  } else if (!strcmp(ri->request_method, "OPTIONS")) {
3367  send_options(conn);
3368  } else if (strstr(path, PASSWORDS_FILE_NAME)) {
3369  // Do not allow to view passwords files
3370  send_http_error(conn, 403, "Forbidden", "Access Forbidden");
3371  } else if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
3372  send_http_error(conn, 404, "Not Found", "Not Found");
3373  } else if ((!strcmp(ri->request_method, "PUT") ||
3374  !strcmp(ri->request_method, "DELETE")) &&
3375  (conn->ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL ||
3376  !is_authorized_for_put(conn))) {
3378  } else if (!strcmp(ri->request_method, "PUT")) {
3379  put_file(conn, path);
3380  } else if (!strcmp(ri->request_method, "DELETE")) {
3381  if (mg_remove(path) == 0) {
3382  send_http_error(conn, 200, "OK", "");
3383  } else {
3384  send_http_error(conn, 500, http_500_error, "remove(%s): %s", path,
3385  strerror(ERRNO));
3386  }
3387  } else if (mg_stat(path, &st) != 0) {
3388  send_http_error(conn, 404, "Not Found", "%s", "File not found");
3389  } else if (st.is_directory && ri->uri[uri_len - 1] != '/') {
3390  (void) mg_printf(conn,
3391  "HTTP/1.1 301 Moved Permanently\r\n"
3392  "Location: %s/\r\n\r\n", ri->uri);
3393  } else if (!strcmp(ri->request_method, "PROPFIND")) {
3394  handle_propfind(conn, path, &st);
3395  } else if (st.is_directory &&
3396  !substitute_index_file(conn, path, sizeof(path), &st)) {
3397  if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")) {
3398  handle_directory_request(conn, path);
3399  } else {
3400  send_http_error(conn, 403, "Directory Listing Denied",
3401  "Directory listing denied");
3402  }
3403 #if !defined(NO_CGI)
3404  } else if (match_extension(path, conn->ctx->config[CGI_EXTENSIONS])) {
3405  if (strcmp(ri->request_method, "POST") &&
3406  strcmp(ri->request_method, "GET")) {
3407  send_http_error(conn, 501, "Not Implemented",
3408  "Method %s is not implemented", ri->request_method);
3409  } else {
3410  handle_cgi_request(conn, path);
3411  }
3412 #endif // !NO_CGI
3413  } else if (match_extension(path, conn->ctx->config[SSI_EXTENSIONS])) {
3414  handle_ssi_file_request(conn, path);
3415  } else if (is_not_modified(conn, &st)) {
3416  send_http_error(conn, 304, "Not Modified", "");
3417  } else {
3418  handle_file_request(conn, path, &st);
3419  }
3420 }
3421 
3422 static void close_all_listening_sockets(struct mg_context *ctx) {
3423  struct socket *sp, *tmp;
3424  for (sp = ctx->listening_sockets; sp != NULL; sp = tmp) {
3425  tmp = sp->next;
3426  (void) closesocket(sp->sock);
3427  free(sp);
3428  }
3429 }
3430 
3431 // Valid listening port specification is: [ip_address:]port[s|p]
3432 // Examples: 80, 443s, 127.0.0.1:3128p, 1.2.3.4:8080sp
3433 static int parse_port_string(const struct vec *vec, struct socket *so) {
3434  struct usa *usa = &so->lsa;
3435  int a, b, c, d, port, len;
3436 
3437  // MacOS needs that. If we do not zero it, subsequent bind() will fail.
3438  memset(so, 0, sizeof(*so));
3439 
3440  if (sscanf(vec->ptr, "%d.%d.%d.%d:%d%n", &a, &b, &c, &d, &port, &len) == 5) {
3441  // IP address to bind to is specified
3442  usa->u.sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
3443  } else if (sscanf(vec->ptr, "%d%n", &port, &len) == 1) {
3444  // Only port number is specified. Bind to all addresses
3445  usa->u.sin.sin_addr.s_addr = htonl(INADDR_ANY);
3446  } else {
3447  return 0;
3448  }
3449  assert(len > 0 && len <= (int) vec->len);
3450 
3451  if (strchr("sp,", vec->ptr[len]) == NULL) {
3452  return 0;
3453  }
3454 
3455  so->is_ssl = vec->ptr[len] == 's';
3456  so->is_proxy = vec->ptr[len] == 'p';
3457  usa->len = sizeof(usa->u.sin);
3458  usa->u.sin.sin_family = AF_INET;
3459  usa->u.sin.sin_port = htons((uint16_t) port);
3460 
3461  return 1;
3462 }
3463 
3464 static int set_ports_option(struct mg_context *ctx) {
3465  const char *list = ctx->config[LISTENING_PORTS];
3466  int on = 1, success = 1;
3467  SOCKET sock;
3468  struct vec vec;
3469  struct socket so, *listener;
3470 
3471  while (success && (list = next_option(list, &vec, NULL)) != NULL) {
3472  if (!parse_port_string(&vec, &so)) {
3473  cry(fc(ctx), "%s: %.*s: invalid port spec. Expecting list of: %s",
3474  __func__, (int) vec.len, vec.ptr, "[IP_ADDRESS:]PORT[s|p]");
3475  success = 0;
3476  } else if (so.is_ssl && ctx->ssl_ctx == NULL) {
3477  cry(fc(ctx), "Cannot add SSL socket, is -ssl_certificate option set?");
3478  success = 0;
3479  } else if ((sock = socket(PF_INET, SOCK_STREAM, 6)) == INVALID_SOCKET ||
3480 #if !defined(_WIN32)
3481  // On Windows, SO_REUSEADDR is recommended only for
3482  // broadcast UDP sockets
3483  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on,
3484  sizeof(on)) != 0 ||
3485 #endif // !_WIN32
3486  // Set TCP keep-alive. This is needed because if HTTP-level
3487  // keep-alive is enabled, and client resets the connection,
3488  // server won't get TCP FIN or RST and will keep the connection
3489  // open forever. With TCP keep-alive, next keep-alive
3490  // handshake will figure out that the client is down and
3491  // will close the server end.
3492  // Thanks to Igor Klopov who suggested the patch.
3493  setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (const char*) &on,
3494  sizeof(on)) != 0 ||
3495  bind(sock, &so.lsa.u.sa, so.lsa.len) != 0 ||
3496  listen(sock, 100) != 0) {
3497  closesocket(sock);
3498  cry(fc(ctx), "%s: cannot bind to %.*s: %s", __func__,
3499  (int) vec.len, vec.ptr, strerror(ERRNO));
3500  success = 0;
3501  } else if ((listener = (struct socket *)
3502  calloc(1, sizeof(*listener))) == NULL) {
3503  closesocket(sock);
3504  cry(fc(ctx), "%s: %s", __func__, strerror(ERRNO));
3505  success = 0;
3506  } else {
3507  *listener = so;
3508  listener->sock = sock;
3509  set_close_on_exec(listener->sock);
3510  listener->next = ctx->listening_sockets;
3511  ctx->listening_sockets = listener;
3512  }
3513  }
3514 
3515  if (!success) {
3517  }
3518 
3519  return success;
3520 }
3521 
3522 static void log_header(const struct mg_connection *conn, const char *header,
3523  FILE *fp) {
3524  const char *header_value;
3525 
3526  if ((header_value = mg_get_header(conn, header)) == NULL) {
3527  (void) fprintf(fp, "%s", " -");
3528  } else {
3529  (void) fprintf(fp, " \"%s\"", header_value);
3530  }
3531 }
3532 
3533 static void log_access(const struct mg_connection *conn) {
3534  const struct mg_request_info *ri;
3535  FILE *fp;
3536  char date[64];
3537 
3538  fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL ? NULL :
3539  mg_fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");
3540 
3541  if (fp == NULL)
3542  return;
3543 
3544  (void) strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z",
3545  localtime(&conn->birth_time));
3546 
3547  ri = &conn->request_info;
3548 
3549  flockfile(fp);
3550 
3551  (void) fprintf(fp,
3552  "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT,
3553  inet_ntoa(conn->client.rsa.u.sin.sin_addr),
3554  ri->remote_user == NULL ? "-" : ri->remote_user,
3555  date,
3556  ri->request_method ? ri->request_method : "-",
3557  ri->uri ? ri->uri : "-",
3558  ri->http_version,
3559  conn->request_info.status_code, conn->num_bytes_sent);
3560  log_header(conn, "Referer", fp);
3561  log_header(conn, "User-Agent", fp);
3562  (void) fputc('\n', fp);
3563  (void) fflush(fp);
3564 
3565  funlockfile(fp);
3566  (void) fclose(fp);
3567 }
3568 
3569 static int isbyte(int n) {
3570  return n >= 0 && n <= 255;
3571 }
3572 
3573 // Verify given socket address against the ACL.
3574 // Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
3575 static int check_acl(struct mg_context *ctx, const struct usa *usa) {
3576  int a, b, c, d, n, mask, allowed;
3577  char flag;
3578  uint32_t acl_subnet, acl_mask, remote_ip;
3579  struct vec vec;
3580  const char *list = ctx->config[ACCESS_CONTROL_LIST];
3581 
3582  if (list == NULL) {
3583  return 1;
3584  }
3585 
3586  (void) memcpy(&remote_ip, &usa->u.sin.sin_addr, sizeof(remote_ip));
3587 
3588  // If any ACL is set, deny by default
3589  allowed = '-';
3590 
3591  while ((list = next_option(list, &vec, NULL)) != NULL) {
3592  mask = 32;
3593 
3594  if (sscanf(vec.ptr, "%c%d.%d.%d.%d%n", &flag, &a, &b, &c, &d, &n) != 5) {
3595  cry(fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__);
3596  return -1;
3597  } else if (flag != '+' && flag != '-') {
3598  cry(fc(ctx), "%s: flag must be + or -: [%s]", __func__, vec.ptr);
3599  return -1;
3600  } else if (!isbyte(a)||!isbyte(b)||!isbyte(c)||!isbyte(d)) {
3601  cry(fc(ctx), "%s: bad ip address: [%s]", __func__, vec.ptr);
3602  return -1;
3603  } else if (sscanf(vec.ptr + n, "/%d", &mask) == 0) {
3604  // Do nothing, no mask specified
3605  } else if (mask < 0 || mask > 32) {
3606  cry(fc(ctx), "%s: bad subnet mask: %d [%s]", __func__, n, vec.ptr);
3607  return -1;
3608  }
3609 
3610  acl_subnet = (a << 24) | (b << 16) | (c << 8) | d;
3611  acl_mask = mask ? 0xffffffffU << (32 - mask) : 0;
3612 
3613  if (acl_subnet == (ntohl(remote_ip) & acl_mask)) {
3614  allowed = flag;
3615  }
3616  }
3617 
3618  return allowed == '+';
3619 }
3620 
3621 static void add_to_set(SOCKET fd, fd_set *set, int *max_fd) {
3622  FD_SET(fd, set);
3623  if (fd > (SOCKET) *max_fd) {
3624  *max_fd = (int) fd;
3625  }
3626 }
3627 
3628 #if !defined(_WIN32)
3629 static int set_uid_option(struct mg_context *ctx) {
3630  struct passwd *pw;
3631  const char *uid = ctx->config[RUN_AS_USER];
3632  int success = 0;
3633 
3634  if (uid == NULL) {
3635  success = 1;
3636  } else {
3637  if ((pw = getpwnam(uid)) == NULL) {
3638  cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
3639  } else if (setgid(pw->pw_gid) == -1) {
3640  cry(fc(ctx), "%s: setgid(%s): %s", __func__, uid, strerror(errno));
3641  } else if (setuid(pw->pw_uid) == -1) {
3642  cry(fc(ctx), "%s: setuid(%s): %s", __func__, uid, strerror(errno));
3643  } else {
3644  success = 1;
3645  }
3646  }
3647 
3648  return success;
3649 }
3650 #endif // !_WIN32
3651 
3652 #if !defined(NO_SSL)
3654 
3655 static void ssl_locking_callback(int mode, int mutex_num, const char *file,
3656  int line) {
3657  line = 0; // Unused
3658  file = NULL; // Unused
3659 
3660  if (mode & CRYPTO_LOCK) {
3661  (void) pthread_mutex_lock(&ssl_mutexes[mutex_num]);
3662  } else {
3663  (void) pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
3664  }
3665 }
3666 
3667 static unsigned long ssl_id_callback(void) {
3668  return (unsigned long) pthread_self();
3669 }
3670 
3671 #if !defined(NO_SSL_DL)
3672 static int load_dll(struct mg_context *ctx, const char *dll_name,
3673  struct ssl_func *sw) {
3674  union {void *p; void (*fp)(void);} u;
3675  void *dll_handle;
3676  struct ssl_func *fp;
3677 
3678  if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
3679  cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
3680  return 0;
3681  }
3682 
3683  for (fp = sw; fp->name != NULL; fp++) {
3684 #ifdef _WIN32
3685  // GetProcAddress() returns pointer to function
3686  u.fp = (void (*)(void)) dlsym(dll_handle, fp->name);
3687 #else
3688  // dlsym() on UNIX returns void *. ISO C forbids casts of data pointers to
3689  // function pointers. We need to use a union to make a cast.
3690  u.p = dlsym(dll_handle, fp->name);
3691 #endif // _WIN32
3692  if (u.fp == NULL) {
3693  cry(fc(ctx), "%s: %s: cannot find %s", __func__, dll_name, fp->name);
3694  return 0;
3695  } else {
3696  fp->ptr = u.fp;
3697  }
3698  }
3699 
3700  return 1;
3701 }
3702 #endif // NO_SSL_DL
3703 
3704 // Dynamically load SSL library. Set up ctx->ssl_ctx pointer.
3705 static int set_ssl_option(struct mg_context *ctx) {
3706  struct mg_request_info request_info;
3707  SSL_CTX *CTX;
3708  int i, size;
3709  const char *pem = ctx->config[SSL_CERTIFICATE];
3710  const char *chain = ctx->config[SSL_CHAIN_FILE];
3711 
3712  if (pem == NULL) {
3713  return 1;
3714  }
3715 
3716 #if !defined(NO_SSL_DL)
3717  if (!load_dll(ctx, SSL_LIB, ssl_sw) ||
3718  !load_dll(ctx, CRYPTO_LIB, crypto_sw)) {
3719  return 0;
3720  }
3721 #endif // NO_SSL_DL
3722 
3723  // Initialize SSL crap
3724  SSL_library_init();
3726 
3727  if ((CTX = SSL_CTX_new(SSLv23_server_method())) == NULL) {
3728  cry(fc(ctx), "SSL_CTX_new error: %s", ssl_error());
3729  } else if (ctx->user_callback != NULL) {
3730  memset(&request_info, 0, sizeof(request_info));
3731  request_info.user_data = ctx->user_data;
3732  ctx->user_callback(MG_INIT_SSL, (struct mg_connection *) CTX,
3733  &request_info);
3734  }
3735 
3736  if (CTX != NULL && SSL_CTX_use_certificate_file(CTX, pem,
3737  SSL_FILETYPE_PEM) == 0) {
3738  cry(fc(ctx), "%s: cannot open %s: %s", __func__, pem, ssl_error());
3739  return 0;
3740  } else if (CTX != NULL && SSL_CTX_use_PrivateKey_file(CTX, pem,
3741  SSL_FILETYPE_PEM) == 0) {
3742  cry(fc(ctx), "%s: cannot open %s: %s", NULL, pem, ssl_error());
3743  return 0;
3744  }
3745 
3746  if (CTX != NULL && chain != NULL &&
3747  SSL_CTX_use_certificate_chain_file(CTX, chain) == 0) {
3748  cry(fc(ctx), "%s: cannot open %s: %s", NULL, chain, ssl_error());
3749  return 0;
3750  }
3751 
3752  // Initialize locking callbacks, needed for thread safety.
3753  // http://www.openssl.org/support/faq.html#PROG1
3754  size = sizeof(pthread_mutex_t) * CRYPTO_num_locks();
3755  if ((ssl_mutexes = (pthread_mutex_t *) malloc((size_t)size)) == NULL) {
3756  cry(fc(ctx), "%s: cannot allocate mutexes: %s", __func__, ssl_error());
3757  return 0;
3758  }
3759 
3760  for (i = 0; i < CRYPTO_num_locks(); i++) {
3761  pthread_mutex_init(&ssl_mutexes[i], NULL);
3762  }
3763 
3766 
3767  // Done with everything. Save the context.
3768  ctx->ssl_ctx = CTX;
3769 
3770  return 1;
3771 }
3772 
3773 static void uninitialize_ssl(struct mg_context *ctx) {
3774  int i;
3775  if (ctx->ssl_ctx != NULL) {
3777  for (i = 0; i < CRYPTO_num_locks(); i++) {
3778  pthread_mutex_destroy(&ssl_mutexes[i]);
3779  }
3781  CRYPTO_set_id_callback(NULL);
3782  }
3783 }
3784 #endif // !NO_SSL
3785 
3786 static int set_gpass_option(struct mg_context *ctx) {
3787  struct mgstat mgstat;
3788  const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
3789  return path == NULL || mg_stat(path, &mgstat) == 0;
3790 }
3791 
3792 static int set_acl_option(struct mg_context *ctx) {
3793  struct usa fake;
3794  return check_acl(ctx, &fake) != -1;
3795 }
3796 
3797 static void reset_per_request_attributes(struct mg_connection *conn) {
3798  struct mg_request_info *ri = &conn->request_info;
3799 
3800  // Reset request info attributes. DO NOT TOUCH is_ssl, remote_ip, remote_port
3801  if (ri->remote_user != NULL) {
3802  free((void *) ri->remote_user);
3803  }
3804  ri->remote_user = ri->request_method = ri->uri = ri->http_version = NULL;
3805  ri->num_headers = 0;
3806  ri->status_code = -1;
3807 
3808  conn->num_bytes_sent = conn->consumed_content = 0;
3809  conn->content_len = -1;
3810  conn->request_len = conn->data_len = 0;
3811 }
3812 
3813 static void close_socket_gracefully(SOCKET sock) {
3814  char buf[BUFSIZ];
3815  struct linger linger;
3816  int n;
3817 
3818  // Set linger option to avoid socket hanging out after close. This prevent
3819  // ephemeral port exhaust problem under high QPS.
3820  linger.l_onoff = 1;
3821  linger.l_linger = 1;
3822  setsockopt(sock, SOL_SOCKET, SO_LINGER, (const char *) &linger, sizeof(linger));
3823 
3824  // Send FIN to the client
3825  (void) shutdown(sock, SHUT_WR);
3826  set_non_blocking_mode(sock);
3827 
3828  // Read and discard pending data. If we do not do that and close the
3829  // socket, the data in the send buffer may be discarded. This
3830  // behaviour is seen on Windows, when client keeps sending data
3831  // when server decide to close the connection; then when client
3832  // does recv() it gets no data back.
3833  do {
3834  n = pull(NULL, sock, NULL, buf, sizeof(buf));
3835  } while (n > 0);
3836 
3837  // Now we know that our FIN is ACK-ed, safe to close
3838  (void) closesocket(sock);
3839 }
3840 
3841 static void close_connection(struct mg_connection *conn) {
3842  if (conn->ssl) {
3843  SSL_free(conn->ssl);
3844  conn->ssl = NULL;
3845  }
3846 
3847  if (conn->client.sock != INVALID_SOCKET) {
3849  }
3850 }
3851 
3853  char *buffered;
3854  int buffered_len, body_len;
3855 
3856  buffered = conn->buf + conn->request_len;
3857  buffered_len = conn->data_len - conn->request_len;
3858  assert(buffered_len >= 0);
3859 
3860  if (conn->content_len == -1) {
3861  body_len = 0;
3862  } else if (conn->content_len < (int64_t) buffered_len) {
3863  body_len = (int) conn->content_len;
3864  } else {
3865  body_len = buffered_len;
3866  }
3867 
3868  conn->data_len -= conn->request_len + body_len;
3869  memmove(conn->buf, conn->buf + conn->request_len + body_len,
3870  (size_t) conn->data_len);
3871 }
3872 
3873 static int parse_url(const char *url, char *host, int *port) {
3874  int len;
3875 
3876  if (sscanf(url, "%*[htps]://%1024[^:]:%d%n", host, port, &len) == 2 ||
3877  sscanf(url, "%1024[^:]:%d%n", host, port, &len) == 2) {
3878  } else if (sscanf(url, "%*[htps]://%1024[^/]%n", host, &len) == 1) {
3879  *port = 80;
3880  } else {
3881  sscanf(url, "%1024[^/]%n", host, &len);
3882  *port = 80;
3883  }
3884  DEBUG_TRACE(("Host:%s, port:%d", host, *port));
3885 
3886  return len;
3887 }
3888 
3889 static void handle_proxy_request(struct mg_connection *conn) {
3890  struct mg_request_info *ri = &conn->request_info;
3891  char host[1025], buf[BUFSIZ];
3892  int port, is_ssl, len, i, n;
3893 
3894  DEBUG_TRACE(("URL: %s", ri->uri));
3895  if (ri->uri == NULL ||
3896  ri->uri[0] == '/' ||
3897  (len = parse_url(ri->uri, host, &port)) == 0) {
3898  return;
3899  }
3900 
3901  if (conn->peer == NULL) {
3902  is_ssl = !strcmp(ri->request_method, "CONNECT");
3903  if ((conn->peer = mg_connect(conn, host, port, is_ssl)) == NULL) {
3904  return;
3905  }
3906  conn->peer->client.is_ssl = is_ssl;
3907  }
3908 
3909  // Forward client's request to the target
3910  mg_printf(conn->peer, "%s %s HTTP/%s\r\n", ri->request_method, ri->uri + len,
3911  ri->http_version);
3912 
3913  // And also all headers. TODO(lsm): anonymize!
3914  for (i = 0; i < ri->num_headers; i++) {
3915  mg_printf(conn->peer, "%s: %s\r\n", ri->http_headers[i].name,
3916  ri->http_headers[i].value);
3917  }
3918  // End of headers, final newline
3919  mg_write(conn->peer, "\r\n", 2);
3920 
3921  // Read and forward body data if any
3922  if (!strcmp(ri->request_method, "POST")) {
3923  forward_body_data(conn, NULL, conn->peer->client.sock, conn->peer->ssl);
3924  }
3925 
3926  // Read data from the target and forward it to the client
3927  while ((n = pull(NULL, conn->peer->client.sock, conn->peer->ssl,
3928  buf, sizeof(buf))) > 0) {
3929  if (mg_write(conn, buf, (size_t)n) != n) {
3930  break;
3931  }
3932  }
3933 
3934  if (!conn->peer->client.is_ssl) {
3935  close_connection(conn->peer);
3936  free(conn->peer);
3937  conn->peer = NULL;
3938  }
3939 }
3940 
3941 static int is_valid_uri(const char *uri) {
3942  // Conform to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
3943  // URI can be an asterisk (*) or should start with slash.
3944  return (uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0'));
3945 }
3946 
3947 static void process_new_connection(struct mg_connection *conn) {
3948  struct mg_request_info *ri = &conn->request_info;
3949  int keep_alive_enabled;
3950  const char *cl;
3951 
3952  keep_alive_enabled = !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
3953 
3954  do {
3956 
3957  // If next request is not pipelined, read it in
3958  if ((conn->request_len = get_request_len(conn->buf, conn->data_len)) == 0) {
3959  conn->request_len = read_request(NULL, conn->client.sock, conn->ssl,
3960  conn->buf, conn->buf_size, &conn->data_len);
3961  }
3962  assert(conn->data_len >= conn->request_len);
3963  if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
3964  send_http_error(conn, 413, "Request Too Large", "");
3965  return;
3966  } if (conn->request_len <= 0) {
3967  return; // Remote end closed the connection
3968  }
3969 
3970  // Nul-terminate the request cause parse_http_request() uses sscanf
3971  conn->buf[conn->request_len - 1] = '\0';
3972  if (!parse_http_request(conn->buf, ri) ||
3973  (!conn->client.is_proxy && !is_valid_uri(ri->uri))) {
3974  // Do not put garbage in the access log, just send it back to the client
3975  send_http_error(conn, 400, "Bad Request",
3976  "Cannot parse HTTP request: [%.*s]", conn->data_len, conn->buf);
3977  } else if (strcmp(ri->http_version, "1.0") &&
3978  strcmp(ri->http_version, "1.1")) {
3979  // Request seems valid, but HTTP version is strange
3980  send_http_error(conn, 505, "HTTP version not supported", "");
3981  log_access(conn);
3982  } else {
3983  // Request is valid, handle it
3984  cl = get_header(ri, "Content-Length");
3985  conn->content_len = cl == NULL ? -1 : strtoll(cl, NULL, 10);
3986  conn->birth_time = time(NULL);
3987  if (conn->client.is_proxy) {
3988  handle_proxy_request(conn);
3989  } else {
3990  handle_request(conn);
3991  }
3992  log_access(conn);
3994  }
3995  // conn->peer is not NULL only for SSL-ed proxy connections
3996  } while (conn->ctx->stop_flag == 0 &&
3997  (conn->peer || (keep_alive_enabled && should_keep_alive(conn))));
3998 }
3999 
4000 // Worker threads take accepted socket from the queue
4001 static int consume_socket(struct mg_context *ctx, struct socket *sp) {
4002  (void) pthread_mutex_lock(&ctx->mutex);
4003  DEBUG_TRACE(("going idle"));
4004 
4005  // If the queue is empty, wait. We're idle at this point.
4006  while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
4007  pthread_cond_wait(&ctx->sq_full, &ctx->mutex);
4008  }
4009 
4010  // If we're stopping, sq_head may be equal to sq_tail.
4011  if (ctx->sq_head > ctx->sq_tail) {
4012  // Copy socket from the queue and increment tail
4013  *sp = ctx->queue[ctx->sq_tail % ARRAY_SIZE(ctx->queue)];
4014  ctx->sq_tail++;
4015  DEBUG_TRACE(("grabbed socket %d, going busy", sp->sock));
4016 
4017  // Wrap pointers if needed
4018  while (ctx->sq_tail > (int) ARRAY_SIZE(ctx->queue)) {
4019  ctx->sq_tail -= ARRAY_SIZE(ctx->queue);
4020  ctx->sq_head -= ARRAY_SIZE(ctx->queue);
4021  }
4022  }
4023 
4024  (void) pthread_cond_signal(&ctx->sq_empty);
4025  (void) pthread_mutex_unlock(&ctx->mutex);
4026 
4027  return !ctx->stop_flag;
4028 }
4029 
4030 static void worker_thread(struct mg_context *ctx) {
4031  struct mg_connection *conn;
4032  int buf_size = atoi(ctx->config[MAX_REQUEST_SIZE]);
4033 
4034  conn = (struct mg_connection *) calloc(1, sizeof(*conn) + buf_size);
4035  conn->buf_size = buf_size;
4036  conn->buf = (char *) (conn + 1);
4037  assert(conn != NULL);
4038 
4039  // Call consume_socket() even when ctx->stop_flag > 0, to let it signal
4040  // sq_empty condvar to wake up the master waiting in produce_socket()
4041  while (consume_socket(ctx, &conn->client)) {
4042  conn->birth_time = time(NULL);
4043  conn->ctx = ctx;
4044 
4045  // Fill in IP, port info early so even if SSL setup below fails,
4046  // error handler would have the corresponding info.
4047  // Thanks to Johannes Winkelmann for the patch.
4048  conn->request_info.remote_port = ntohs(conn->client.rsa.u.sin.sin_port);
4049  memcpy(&conn->request_info.remote_ip,
4050  &conn->client.rsa.u.sin.sin_addr.s_addr, 4);
4051  conn->request_info.remote_ip = ntohl(conn->request_info.remote_ip);
4052  conn->request_info.is_ssl = conn->client.is_ssl;
4053 
4054  if (!conn->client.is_ssl ||
4055  (conn->client.is_ssl && sslize(conn, SSL_accept))) {
4056  process_new_connection(conn);
4057  }
4058 
4059  close_connection(conn);
4060  }
4061  free(conn);
4062 
4063  // Signal master that we're done with connection and exiting
4064  (void) pthread_mutex_lock(&ctx->mutex);
4065  ctx->num_threads--;
4066  (void) pthread_cond_signal(&ctx->cond);
4067  assert(ctx->num_threads >= 0);
4068  (void) pthread_mutex_unlock(&ctx->mutex);
4069 
4070  DEBUG_TRACE(("exiting"));
4071 }
4072 
4073 // Master thread adds accepted socket to a queue
4074 static void produce_socket(struct mg_context *ctx, const struct socket *sp) {
4075  (void) pthread_mutex_lock(&ctx->mutex);
4076 
4077  // If the queue is full, wait
4078  while (ctx->stop_flag == 0 &&
4079  ctx->sq_head - ctx->sq_tail >= (int) ARRAY_SIZE(ctx->queue)) {
4080  (void) pthread_cond_wait(&ctx->sq_empty, &ctx->mutex);
4081  }
4082 
4083  if (ctx->sq_head - ctx->sq_tail < (int) ARRAY_SIZE(ctx->queue)) {
4084  // Copy socket to the queue and increment head
4085  ctx->queue[ctx->sq_head % ARRAY_SIZE(ctx->queue)] = *sp;
4086  ctx->sq_head++;
4087  DEBUG_TRACE(("queued socket %d", sp->sock));
4088  }
4089 
4090  (void) pthread_cond_signal(&ctx->sq_full);
4091  (void) pthread_mutex_unlock(&ctx->mutex);
4092 }
4093 
4094 static void accept_new_connection(const struct socket *listener,
4095  struct mg_context *ctx) {
4096  struct socket accepted;
4097  int allowed;
4098 
4099  accepted.rsa.len = sizeof(accepted.rsa.u.sin);
4100  accepted.lsa = listener->lsa;
4101  accepted.sock = accept(listener->sock, &accepted.rsa.u.sa, &accepted.rsa.len);
4102  if (accepted.sock != INVALID_SOCKET) {
4103  allowed = check_acl(ctx, &accepted.rsa);
4104  if (allowed) {
4105  // Put accepted socket structure into the queue
4106  DEBUG_TRACE(("accepted socket %d", accepted.sock));
4107  accepted.is_ssl = listener->is_ssl;
4108  accepted.is_proxy = listener->is_proxy;
4109  produce_socket(ctx, &accepted);
4110  } else {
4111  cry(fc(ctx), "%s: %s is not allowed to connect",
4112  __func__, inet_ntoa(accepted.rsa.u.sin.sin_addr));
4113  (void) closesocket(accepted.sock);
4114  }
4115  }
4116 }
4117 
4118 static void master_thread(struct mg_context *ctx) {
4119  fd_set read_set;
4120  struct timeval tv;
4121  struct socket *sp;
4122  int max_fd;
4123 
4124  while (ctx->stop_flag == 0) {
4125  FD_ZERO(&read_set);
4126  max_fd = -1;
4127 
4128  // Add listening sockets to the read set
4129  for (sp = ctx->listening_sockets; sp != NULL; sp = sp->next) {
4130  add_to_set(sp->sock, &read_set, &max_fd);
4131  }
4132 
4133  tv.tv_sec = 0;
4134  tv.tv_usec = 200 * 1000;
4135 
4136  if (select(max_fd + 1, &read_set, NULL, NULL, &tv) < 0) {
4137 #ifdef _WIN32
4138  // On windows, if read_set and write_set are empty,
4139  // select() returns "Invalid parameter" error
4140  // (at least on my Windows XP Pro). So in this case, we sleep here.
4141  sleep(1);
4142 #endif // _WIN32
4143  } else {
4144  for (sp = ctx->listening_sockets; sp != NULL; sp = sp->next) {
4145  if (ctx->stop_flag == 0 && FD_ISSET(sp->sock, &read_set)) {
4146  accept_new_connection(sp, ctx);
4147  }
4148  }
4149  }
4150  }
4151  DEBUG_TRACE(("stopping workers"));
4152 
4153  // Stop signal received: somebody called mg_stop. Quit.
4155 
4156  // Wakeup workers that are waiting for connections to handle.
4157  pthread_cond_broadcast(&ctx->sq_full);
4158 
4159  // Wait until all threads finish
4160  (void) pthread_mutex_lock(&ctx->mutex);
4161  while (ctx->num_threads > 0) {
4162  (void) pthread_cond_wait(&ctx->cond, &ctx->mutex);
4163  }
4164  (void) pthread_mutex_unlock(&ctx->mutex);
4165 
4166  // All threads exited, no sync is needed. Destroy mutex and condvars
4167  (void) pthread_mutex_destroy(&ctx->mutex);
4168  (void) pthread_cond_destroy(&ctx->cond);
4169  (void) pthread_cond_destroy(&ctx->sq_empty);
4170  (void) pthread_cond_destroy(&ctx->sq_full);
4171 
4172 #if !defined(NO_SSL)
4173  uninitialize_ssl(ctx);
4174 #endif
4175 
4176  // Signal mg_stop() that we're done
4177  ctx->stop_flag = 2;
4178 
4179  DEBUG_TRACE(("exiting"));
4180 }
4181 
4182 static void free_context(struct mg_context *ctx) {
4183  int i;
4184 
4185  // Deallocate config parameters
4186  for (i = 0; i < NUM_OPTIONS; i++) {
4187  if (ctx->config[i] != NULL)
4188  free(ctx->config[i]);
4189  }
4190 
4191  // Deallocate SSL context
4192  if (ctx->ssl_ctx != NULL) {
4193  SSL_CTX_free(ctx->ssl_ctx);
4194  }
4195 #ifndef NO_SSL
4196  if (ssl_mutexes != NULL) {
4197  free(ssl_mutexes);
4198  }
4199 #endif // !NO_SSL
4200 
4201  // Deallocate context itself
4202  free(ctx);
4203 }
4204 
4205 void mg_stop(struct mg_context *ctx) {
4206  ctx->stop_flag = 1;
4207 
4208  // Wait until mg_fini() stops
4209  while (ctx->stop_flag != 2) {
4210  (void) sleep(0);
4211  }
4212  free_context(ctx);
4213 
4214 #if defined(_WIN32) && !defined(__SYMBIAN32__)
4215  (void) WSACleanup();
4216 #endif // _WIN32
4217 }
4218 
4220  const char **options) {
4221  struct mg_context *ctx;
4222  const char *name, *value, *default_value;
4223  int i;
4224 
4225 #if defined(_WIN32) && !defined(__SYMBIAN32__)
4226  WSADATA data;
4227  WSAStartup(MAKEWORD(2,2), &data);
4228 #endif // _WIN32
4229 
4230  // Allocate context and initialize reasonable general case defaults.
4231  // TODO(lsm): do proper error handling here.
4232  ctx = (struct mg_context *) calloc(1, sizeof(*ctx));
4234  ctx->user_data = user_data;
4235 
4236  while (options && (name = *options++) != NULL) {
4237  if ((i = get_option_index(name)) == -1) {
4238  cry(fc(ctx), "Invalid option: %s", name);
4239  free_context(ctx);
4240  return NULL;
4241  } else if ((value = *options++) == NULL) {
4242  cry(fc(ctx), "%s: option value cannot be NULL", name);
4243  free_context(ctx);
4244  return NULL;
4245  }
4246  ctx->config[i] = mg_strdup(value);
4247  DEBUG_TRACE(("[%s] -> [%s]", name, value));
4248  }
4249 
4250  // Set default value if needed
4251  for (i = 0; config_options[i * ENTRIES_PER_CONFIG_OPTION] != NULL; i++) {
4252  default_value = config_options[i * ENTRIES_PER_CONFIG_OPTION + 2];
4253  if (ctx->config[i] == NULL && default_value != NULL) {
4254  ctx->config[i] = mg_strdup(default_value);
4255  DEBUG_TRACE(("Setting default: [%s] -> [%s]",
4256  config_options[i * ENTRIES_PER_CONFIG_OPTION + 1],
4257  default_value));
4258  }
4259  }
4260 
4261  // NOTE(lsm): order is important here. SSL certificates must
4262  // be initialized before listening ports. UID must be set last.
4263  if (!set_gpass_option(ctx) ||
4264 #if !defined(NO_SSL)
4265  !set_ssl_option(ctx) ||
4266 #endif
4267  !set_ports_option(ctx) ||
4268 #if !defined(_WIN32)
4269  !set_uid_option(ctx) ||
4270 #endif
4271  !set_acl_option(ctx)) {
4272  free_context(ctx);
4273  return NULL;
4274  }
4275 
4276 #if !defined(_WIN32) && !defined(__SYMBIAN32__)
4277  // Ignore SIGPIPE signal, so if browser cancels the request, it
4278  // won't kill the whole process.
4279  (void) signal(SIGPIPE, SIG_IGN);
4280  // Also ignoring SIGCHLD to let the OS to reap zombies properly.
4281  (void) signal(SIGCHLD, SIG_IGN);
4282 #endif // !_WIN32
4283 
4284  (void) pthread_mutex_init(&ctx->mutex, NULL);
4285  (void) pthread_cond_init(&ctx->cond, NULL);
4286  (void) pthread_cond_init(&ctx->sq_empty, NULL);
4287  (void) pthread_cond_init(&ctx->sq_full, NULL);
4288 
4289  // Start master (listening) thread
4291 
4292  // Start worker threads
4293  for (i = 0; i < atoi(ctx->config[NUM_THREADS]); i++) {
4294  if (start_thread(ctx, (mg_thread_func_t) worker_thread, ctx) != 0) {
4295  cry(fc(ctx), "Cannot start worker thread: %d", ERRNO);
4296  } else {
4297  ctx->num_threads++;
4298  }
4299  }
4300 
4301  return ctx;
4302 }
static struct mg_connection * fc(struct mg_context *ctx)
Definition: mongoose.cpp:607
const char * ptr
Definition: mongoose.cpp:424
static char * skip(char **buf, const char *delimiters)
Definition: mongoose.cpp:748
void * pthread_mutex_t
Definition: wpthread.h:82
static const char * ssl_error(void)
Definition: mongoose.cpp:599
static char * mg_strdup(const char *str)
Definition: mongoose.cpp:659
#define SSL_CTX_use_PrivateKey_file
Definition: mongoose.cpp:352
static int authorize(struct mg_connection *conn, FILE *fp)
Definition: mongoose.cpp:2170
static void produce_socket(struct mg_context *ctx, const struct socket *sp)
Definition: mongoose.cpp:4074
#define SSL_connect
Definition: mongoose.cpp:343
static void accept_new_connection(const struct socket *listener, struct mg_context *ctx)
Definition: mongoose.cpp:4094
static int parse_port_string(const struct vec *vec, struct socket *so)
Definition: mongoose.cpp:3433
struct mg_request_info request_info
Definition: mongoose.cpp:506
#define CRYPTO_LOCK
Definition: mongoose.cpp:309
void *(* mg_callback_t)(enum mg_event event, struct mg_connection *conn, const struct mg_request_info *request_info)
Definition: mongoose.h:79
static int substitute_index_file(struct mg_connection *conn, char *path, size_t path_len, struct mgstat *stp)
Definition: mongoose.cpp:2694
char buf[CGI_ENVIRONMENT_SIZE]
static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf, int64_t len)
Definition: mongoose.cpp:1344
static void url_encode(const char *src, char *dst, size_t dst_len)
Definition: mongoose.cpp:2325
const char * mime_type
Definition: mongoose.cpp:1738
#define SSL_CTX_use_certificate_file
Definition: mongoose.cpp:354
unsigned sleep(unsigned sec)
Definition: wtime.cpp:151
#define MAX_CGI_ENVIR_VARS
Definition: mongoose.cpp:266
static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen, const char *fmt,...)
Definition: mongoose.cpp:689
struct de * entries
Definition: mongoose.cpp:2445
int SOCKET
Definition: mongoose.cpp:256
static int match_extension(const char *path, const char *ext_list)
Definition: mongoose.cpp:808
char * request_method
Definition: mongoose.h:37
static void free_context(struct mg_context *ctx)
Definition: mongoose.cpp:4182
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.cpp:2041
#define mg_remove(x)
Definition: mongoose.cpp:251
volatile int sq_head
Definition: mongoose.cpp:498
static void send_file_data(struct mg_connection *conn, FILE *fp, int64_t len)
Definition: mongoose.cpp:2519
uint32_t buf[4]
Definition: mongoose.cpp:1824
#define mg_fopen(x, y)
Definition: mongoose.cpp:249
char * nc
Definition: mongoose.cpp:2102
static void MD5Transform(uint32_t buf[4], uint32_t const in[16])
Definition: mongoose.cpp:1863
static int get_month_index(const char *s)
Definition: mongoose.cpp:1675
#define CGI_ENVIRONMENT_SIZE
Definition: mongoose.cpp:265
struct mg_connection * conn
Definition: mongoose.cpp:2320
static int set_non_blocking_mode(SOCKET sock)
Definition: mongoose.cpp:1332
static int start_thread(struct mg_context *ctx, mg_thread_func_t func, void *param)
Definition: mongoose.cpp:1267
static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len)
Definition: mongoose.cpp:1945
static int mg_vsnprintf(struct mg_connection *conn, char *buf, size_t buflen, const char *fmt, va_list ap)
Definition: mongoose.cpp:667
void *(* mg_thread_func_t)(void *)
Definition: mongoose.cpp:295
int64_t consumed_content
Definition: mongoose.cpp:513
char * uri
Definition: mongoose.h:38
#define ENTRIES_PER_CONFIG_OPTION
Definition: mongoose.cpp:482
struct sockaddr sa
Definition: mongoose.cpp:417
char * cnonce
Definition: mongoose.cpp:2102
static void out(const wchar_t *fmt,...)
Definition: wdbg_sym.cpp:419
#define SSL_read
Definition: mongoose.cpp:344
static int parse_auth_header(struct mg_connection *conn, char *buf, size_t buf_size, struct ah *ah)
Definition: mongoose.cpp:2105
static int should_keep_alive(const struct mg_connection *conn)
Definition: mongoose.cpp:826
static int get_option_index(const char *name)
Definition: mongoose.cpp:530
int mg_get_cookie(const struct mg_connection *conn, const char *cookie_name, char *dst, size_t dst_size)
Definition: mongoose.cpp:1533
static void print_props(struct mg_connection *conn, const char *uri, struct mgstat *st)
Definition: mongoose.cpp:3287
struct mg_request_info::mg_header http_headers[64]
struct MD5Context MD5_CTX
static void handle_propfind(struct mg_connection *conn, const char *path, struct mgstat *st)
Definition: mongoose.cpp:3317
#define F1(x, y, z)
Definition: mongoose.cpp:1843
static void handle_request(struct mg_connection *conn)
Definition: mongoose.cpp:3347
#define CRYPTO_LIB
Definition: mongoose.cpp:240
struct usa rsa
Definition: mongoose.cpp:441
pthread_cond_t sq_empty
Definition: mongoose.cpp:501
static void get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
Definition: mongoose.cpp:1786
volatile int num_threads
Definition: mongoose.cpp:493
time_t mtime
Definition: mongoose.cpp:432
static int set_uid_option(struct mg_context *ctx)
Definition: mongoose.cpp:3629
static FILE * open_auth_file(struct mg_connection *conn, const char *path)
Definition: mongoose.cpp:2070
char * log_message
Definition: mongoose.h:42
int is_proxy
Definition: mongoose.cpp:443
#define SSL_CTX_new
Definition: mongoose.cpp:349
#define SSL_FILETYPE_PEM
Definition: mongoose.cpp:308
static const char * config_options[]
Definition: mongoose.cpp:457
#define SSL_free
Definition: mongoose.cpp:341
static int check_authorization(struct mg_connection *conn, const char *path)
Definition: mongoose.cpp:2196
static void log_access(const struct mg_connection *conn)
Definition: mongoose.cpp:3533
size_t ext_len
Definition: mongoose.cpp:1737
static int isbyte(int n)
Definition: mongoose.cpp:3569
static void add_to_set(SOCKET fd, fd_set *set, int *max_fd)
Definition: mongoose.cpp:3621
static void reset_per_request_attributes(struct mg_connection *conn)
Definition: mongoose.cpp:3797
#define PASSWORDS_FILE_NAME
Definition: mongoose.cpp:264
static struct ssl_func crypto_sw[]
Definition: mongoose.cpp:397
static const char * get_header(const struct mg_request_info *ri, const char *name)
Definition: mongoose.cpp:754
static void send_options(struct mg_connection *conn)
Definition: mongoose.cpp:3277
time_t tv_sec
Definition: wtime.h:64
struct ssl_ctx_st SSL_CTX
Definition: mongoose.cpp:304
#define SSL_load_error_strings
Definition: mongoose.cpp:359
size_t len
Definition: mongoose.cpp:425
void mg_md5(char *buf,...)
Definition: mongoose.cpp:2022
#define ERRNO
Definition: mongoose.cpp:253
volatile int sq_tail
Definition: mongoose.cpp:499
pthread_t pthread_self()
Definition: wpthread.cpp:74
static struct ssl_func ssl_sw[]
Definition: mongoose.cpp:375
char * file_name
Definition: mongoose.cpp:2321
static char * mg_strndup(const char *ptr, size_t len)
Definition: mongoose.cpp:649
static void ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
static unsigned long ssl_id_callback(void)
struct socket * next
Definition: mongoose.cpp:438
#define NO_SSL
Definition: mongoose.cpp:37
#define SSLv23_server_method
Definition: mongoose.cpp:350
#define SSL_accept
Definition: mongoose.cpp:342
static int lowercase(const char *s)
Definition: mongoose.cpp:624
static void remove_double_dots_and_double_slashes(char *s)
Definition: mongoose.cpp:1715
#define RTLD_LAZY
Definition: wdlfcn.h:32
static int pull(FILE *fp, SOCKET sock, SSL *ssl, char *buf, int len)
Definition: mongoose.cpp:1376
static int get_document_root(const struct mg_connection *conn, struct vec *document_root)
Definition: mongoose.cpp:1570
static void handle_cgi_request(struct mg_connection *conn, const char *prog)
static void uninitialize_ssl(struct mg_context *ctx)
#define SSL_CTX_set_default_passwd_cb
Definition: mongoose.cpp:356
#define SSL_new
Definition: mongoose.cpp:348
SOCKET sock
Definition: mongoose.cpp:439
static int WINCDECL compare_dir_entries(const void *p1, const void *p2)
Definition: mongoose.cpp:2380
static int mg_strncasecmp(const char *s1, const char *s2, size_t len)
Definition: mongoose.cpp:628
static int is_not_modified(const struct mg_connection *conn, const struct mgstat *stp)
Definition: mongoose.cpp:2739
volatile int stop_flag
Definition: mongoose.cpp:485
unsigned long long uint64_t
Definition: wposix_types.h:57
#define mg_mkdir(x, y)
Definition: mongoose.cpp:250
static int set_acl_option(struct mg_context *ctx)
Definition: mongoose.cpp:3792
int pthread_create(pthread_t *thread_id, const void *attr, void *(*func)(void *), void *arg)
Definition: wpthread.cpp:636
static struct mg_connection * mg_connect(struct mg_connection *conn, const char *host, int port, int use_ssl)
Definition: mongoose.cpp:1613
long tv_nsec
Definition: wtime.h:65
int mg_read(struct mg_connection *conn, void *buf, size_t len)
Definition: mongoose.cpp:1395
__int64 off_t
Definition: wposix_types.h:91
#define CRYPTO_set_id_callback
Definition: mongoose.cpp:366
static void handle_file_request(struct mg_connection *conn, const char *path, struct mgstat *stp)
Definition: mongoose.cpp:2551
static void * call_user(struct mg_connection *conn, enum mg_event event)
Definition: mongoose.cpp:524
static void discard_current_request_from_buffer(struct mg_connection *conn)
Definition: mongoose.cpp:3852
static void cry(struct mg_connection *conn, const char *fmt,...)
Definition: mongoose.cpp:554
static void close_all_listening_sockets(struct mg_context *ctx)
Definition: mongoose.cpp:3422
mg_callback_t user_callback
Definition: mongoose.cpp:488
void * HANDLE
Definition: wgl.h:62
const char * mg_version(void)
Definition: mongoose.cpp:613
static const char * suggest_connection_header(const struct mg_connection *conn)
Definition: mongoose.cpp:833
void * dlopen(const char *so_name, int flags)
Definition: wdlfcn.cpp:64
int read(int fd, void *buf, size_t nbytes)
int is_ssl
Definition: mongoose.cpp:442
static void close_socket_gracefully(SOCKET sock)
Definition: mongoose.cpp:3813
static void master_thread(struct mg_context *ctx)
Definition: mongoose.cpp:4118
struct mg_context * ctx
Definition: mongoose.cpp:507
#define SSL_LIB
Definition: mongoose.cpp:237
#define ERR_get_error
Definition: mongoose.cpp:368
static void mg_strlcpy(register char *dst, register const char *src, size_t n)
Definition: mongoose.cpp:617
struct mgstat st
Definition: mongoose.cpp:2322
char * nonce
Definition: mongoose.cpp:2102
unsigned long DWORD
Definition: wgl.h:56
int pthread_mutex_lock(pthread_mutex_t *m)
Definition: wpthread.cpp:329
int mg_get_var(const char *buf, size_t buf_len, const char *name, char *dst, size_t dst_len)
Definition: mongoose.cpp:1497
static const char * next_option(const char *list, struct vec *val, struct vec *eq_val)
Definition: mongoose.cpp:775
char * http_version
Definition: mongoose.h:39
static int mg_strcasecmp(const char *s1, const char *s2)
Definition: mongoose.cpp:639
#define DIRSEP
Definition: mongoose.cpp:243
long remote_ip
Definition: mongoose.h:43
pthread_mutex_t mutex
Definition: mongoose.cpp:494
static void gmt_time_string(char *buf, size_t buf_len, time_t *t)
Definition: mongoose.cpp:2547
mg_event
Definition: mongoose.h:55
static char * addenv(struct cgi_env_block *block, const char *fmt,...)
unsigned char in[64]
Definition: mongoose.cpp:1826
#define closesocket(a)
Definition: mongoose.cpp:248
void * dlsym(void *handle, const char *sym_name)
Definition: wdlfcn.cpp:74
#define INT64_FMT
Definition: mongoose.cpp:255
static void do_ssi_exec(struct mg_connection *conn, char *tag)
Definition: mongoose.cpp:3180
#define MD5STEP(f, w, x, y, z, data, s)
Definition: mongoose.cpp:1848
#define SSL_get_error
Definition: mongoose.cpp:346
static int forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
Definition: mongoose.cpp:2745
static void parse_http_headers(char **buf, struct mg_request_info *ri)
Definition: mongoose.cpp:2626
char * query_string
Definition: mongoose.h:40
#define F4(x, y, z)
Definition: mongoose.cpp:1846
static int is_authorized_for_put(struct mg_connection *conn)
Definition: mongoose.cpp:2241
struct socket * listening_sockets
Definition: mongoose.cpp:491
struct mg_connection * conn
#define F3(x, y, z)
Definition: mongoose.cpp:1845
int pthread_mutex_init(pthread_mutex_t *m, const pthread_mutexattr_t *)
Definition: wpthread.cpp:323
char * uri
Definition: mongoose.cpp:2102
#define PATH_MAX
Definition: wposix_types.h:101
static void worker_thread(struct mg_context *ctx)
Definition: mongoose.cpp:4030
static const char * month_names[]
Definition: mongoose.cpp:407
static void set_close_on_exec(int fd)
Definition: mongoose.cpp:1263
#define HEXTOI(x)
static int is_valid_http_method(const char *method)
Definition: mongoose.cpp:2638
char * vars[MAX_CGI_ENVIR_VARS]
uint32_t bits[2]
Definition: mongoose.cpp:1825
static void send_authorization_request(struct mg_connection *conn)
Definition: mongoose.cpp:2230
static void byteReverse(unsigned char *buf, unsigned longs)
Definition: mongoose.cpp:1832
const char * mg_get_option(const struct mg_context *ctx, const char *name)
Definition: mongoose.cpp:542
char * response
Definition: mongoose.cpp:2102
#define F2(x, y, z)
Definition: mongoose.cpp:1844
static int set_ports_option(struct mg_context *ctx)
Definition: mongoose.cpp:3464
char * user
Definition: mongoose.cpp:2102
struct socket client
Definition: mongoose.cpp:509
static void handle_directory_request(struct mg_connection *conn, const char *dir)
Definition: mongoose.cpp:2469
static const char * http_500_error
Definition: mongoose.cpp:297
const char * mg_get_header(const struct mg_connection *conn, const char *name)
Definition: mongoose.cpp:765
size_t mime_type_len
Definition: mongoose.cpp:1739
int mg_printf(struct mg_connection *conn, const char *fmt,...)
Definition: mongoose.cpp:1450
struct ssl_st SSL
Definition: mongoose.cpp:302
#define CRYPTO_num_locks
Definition: mongoose.cpp:363
struct socket queue[20]
Definition: mongoose.cpp:497
const char * extension
Definition: mongoose.cpp:1736
uintptr_t pthread_t
Definition: wpthread.h:63
static void dir_scan_callback(struct de *de, void *data)
Definition: mongoose.cpp:2450
pthread_cond_t sq_full
Definition: mongoose.cpp:500
#define SSL_library_init
Definition: mongoose.cpp:351
static void handle_proxy_request(struct mg_connection *conn)
Definition: mongoose.cpp:3889
const char * name
Definition: mongoose.cpp:337
static void MD5Init(MD5_CTX *ctx)
Definition: mongoose.cpp:1853
#define MONGOOSE_VERSION
Definition: mongoose.cpp:263
int mg_write(struct mg_connection *conn, const void *buf, size_t len)
Definition: mongoose.cpp:1445
#define S_ISDIR(m)
Definition: wfilesystem.h:52
const char ** mg_get_valid_option_names(void)
Definition: mongoose.cpp:520
static void print_dav_dir_entry(struct de *de, void *data)
Definition: mongoose.cpp:3309
static void print_dir_entry(struct de *de)
Definition: mongoose.cpp:2345
pthread_cond_t cond
Definition: mongoose.cpp:495
static void put_file(struct mg_connection *conn, const char *path)
Definition: mongoose.cpp:3097
static pid_t spawn_process(struct mg_connection *conn, const char *prog, char *envblk, char *envp[], int fd_stdin, int fd_stdout, const char *dir)
#define SSL_CTX_free
Definition: mongoose.cpp:358
static size_t url_decode(const char *src, size_t src_len, char *dst, size_t dst_len, int is_form_url_encoded)
Definition: mongoose.cpp:1467
unsigned int uint32_t
Definition: wposix_types.h:53
int pthread_mutex_unlock(pthread_mutex_t *m)
Definition: wpthread.cpp:347
#define mg_rename(x, y)
Definition: mongoose.cpp:252
struct usa lsa
Definition: mongoose.cpp:440
char * config[NUM_OPTIONS]
Definition: mongoose.cpp:487
#define SSL_set_fd
Definition: mongoose.cpp:347
static int scan_directory(struct mg_connection *conn, const char *dir, void *data, void(*cb)(struct de *, void *))
Definition: mongoose.cpp:2406
static void process_new_connection(struct mg_connection *conn)
Definition: mongoose.cpp:3947
int64_t num_bytes_sent
Definition: mongoose.cpp:511
static char * skip_quoted(char **buf, const char *delimiters, const char *whitespace, char quotechar)
Definition: mongoose.cpp:705
void * user_data
Definition: mongoose.h:36
static void convert_uri_to_file_name(struct mg_connection *conn, const char *uri, char *buf, size_t buf_len)
Definition: mongoose.cpp:1591
static int get_request_len(const char *buf, int buflen)
Definition: mongoose.cpp:1654
int64_t size
Definition: mongoose.cpp:431
#define ARRAY_SIZE(array)
Definition: mongoose.cpp:267
char * qop
Definition: mongoose.cpp:2102
#define DEBUG_TRACE(x)
Definition: mongoose.cpp:287
#define INVALID_SOCKET
Definition: mongoose.cpp:254
static int check_acl(struct mg_context *ctx, const struct usa *usa)
Definition: mongoose.cpp:3575
static void send_http_error(struct mg_connection *conn, int status, const char *reason, const char *fmt,...)
Definition: mongoose.cpp:837
static void send_ssi_file(struct mg_connection *, const char *, FILE *, int)
Definition: mongoose.cpp:3195
static int parse_range_header(const char *header, int64_t *a, int64_t *b)
Definition: mongoose.cpp:2543
#define IS_DIRSEP_CHAR(c)
Definition: mongoose.cpp:244
#define CRYPTO_set_locking_callback
Definition: mongoose.cpp:364
void(* ptr)(void)
Definition: mongoose.cpp:338
static int load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
Definition: wtime.h:62
static void log_header(const struct mg_connection *conn, const char *header, FILE *fp)
Definition: mongoose.cpp:3522
static Handle handle(size_t idx, u64 tag)
Definition: h_mgr.cpp:121
static int put_dir(const char *path)
Definition: mongoose.cpp:3066
#define ERR_error_string
Definition: mongoose.cpp:369
#define SSL_CTX_use_certificate_chain_file
Definition: mongoose.cpp:360
SSL_CTX * ssl_ctx
Definition: mongoose.cpp:486
static int set_gpass_option(struct mg_context *ctx)
Definition: mongoose.cpp:3786
void mg_send_file(struct mg_connection *conn, const char *path)
Definition: mongoose.cpp:2614
static time_t parse_date_string(const char *datetime)
Definition: mongoose.cpp:1686
int pthread_mutex_destroy(pthread_mutex_t *m)
Definition: wpthread.cpp:312
time_t birth_time
Definition: mongoose.cpp:510
static void do_ssi_include(struct mg_connection *conn, const char *ssi, char *tag, int include_level)
Definition: mongoose.cpp:3132
#define SSL_write
Definition: mongoose.cpp:345
static int read_request(FILE *fp, SOCKET sock, SSL *ssl, char *buf, int bufsiz, int *nread)
Definition: mongoose.cpp:2673
#define WINCDECL
Definition: mongoose.cpp:257
struct mg_context * mg_start(mg_callback_t user_callback, void *user_data, const char **options)
Definition: mongoose.cpp:4219
unsigned short uint16_t
Definition: wposix_types.h:52
union usa::@65 u
static int sslize(struct mg_connection *conn, int(*func)(SSL *))
Definition: mongoose.cpp:1607
int mg_modify_passwords_file(const char *fname, const char *domain, const char *user, const char *pass)
Definition: mongoose.cpp:2256
struct mg_connection * peer
Definition: mongoose.cpp:505
struct sockaddr_in sin
Definition: mongoose.cpp:418
static int mg_stat(const char *path, struct mgstat *stp)
Definition: mongoose.cpp:1247
static void handle_ssi_file_request(struct mg_connection *conn, const char *path)
Definition: mongoose.cpp:3260
static int consume_socket(struct mg_context *ctx, struct socket *sp)
Definition: mongoose.cpp:4001
static pthread_mutex_t * ssl_mutexes
static int parse_url(const char *url, char *host, int *port)
Definition: mongoose.cpp:3873
static struct @64 builtin_mime_types[]
static void MD5Final(unsigned char digest[16], MD5_CTX *ctx)
Definition: mongoose.cpp:1981
static void close_connection(struct mg_connection *conn)
Definition: mongoose.cpp:3841
static void prepare_cgi_environment(struct mg_connection *conn, const char *prog, struct cgi_env_block *blk)
int64_t content_len
Definition: mongoose.cpp:512
static int parse_http_request(char *buf, struct mg_request_info *ri)
Definition: mongoose.cpp:2646
#define __func__
struct ssl_method_st SSL_METHOD
Definition: mongoose.cpp:303
char * remote_user
Definition: mongoose.h:41
void mg_stop(struct mg_context *ctx)
Definition: mongoose.cpp:4205
int is_directory
Definition: mongoose.cpp:430
void * user_data
Definition: mongoose.cpp:489
static int is_valid_uri(const char *uri)
Definition: mongoose.cpp:3941
static void bin2str(char *to, const unsigned char *p, size_t len)
Definition: mongoose.cpp:2011
long long int64_t
Definition: wposix_types.h:48
socklen_t len
Definition: mongoose.cpp:415
static int set_ssl_option(struct mg_context *ctx)