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