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