source: rtems-libbsd/services/mghttpd/mongoose.c @ b27d875

4.1155-freebsd-126-freebsd-12freebsd-9.3
Last change on this file since b27d875 was 2cbf1af, checked in by Joel Sherrill <joel.sherrill@…>, on 07/27/12 at 13:03:55

mghttpd: Add services directory with mghttpd as first

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