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