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