trunk/src/lib/web/mongoose.c
| r0 | r24784 | |
| 1 | // Copyright (c) 2004-2013 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 SETSOCKOPT_CAST const char * |
| 23 | #else |
| 24 | #define SETSOCKOPT_CAST void * |
| 25 | #endif |
| 26 | |
| 27 | #if defined(_WIN32) |
| 28 | #if !defined(_CRT_SECURE_NO_WARNINGS) |
| 29 | #define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005 |
| 30 | #endif |
| 31 | #else |
| 32 | #ifdef __linux__ |
| 33 | #define _XOPEN_SOURCE 600 // For flockfile() on Linux |
| 34 | #endif |
| 35 | #define _LARGEFILE_SOURCE // Enable 64-bit file offsets |
| 36 | #define __STDC_FORMAT_MACROS // <inttypes.h> wants this for C++ |
| 37 | #define __STDC_LIMIT_MACROS // C++ wants that for INT64_MAX |
| 38 | #endif |
| 39 | |
| 40 | #if defined (_MSC_VER) |
| 41 | // conditional expression is constant: introduced by FD_SET(..) |
| 42 | #pragma warning (disable : 4127) |
| 43 | // non-constant aggregate initializer: issued due to missing C99 support |
| 44 | #pragma warning (disable : 4204) |
| 45 | #endif |
| 46 | |
| 47 | // Disable WIN32_LEAN_AND_MEAN. |
| 48 | // This makes windows.h always include winsock2.h |
| 49 | #ifdef WIN32_LEAN_AND_MEAN |
| 50 | #undef WIN32_LEAN_AND_MEAN |
| 51 | #endif |
| 52 | |
| 53 | #if defined(__SYMBIAN32__) |
| 54 | #define NO_SSL // SSL is not supported |
| 55 | #define NO_CGI // CGI is not supported |
| 56 | #define PATH_MAX FILENAME_MAX |
| 57 | #endif // __SYMBIAN32__ |
| 58 | |
| 59 | #ifndef _WIN32_WCE // Some ANSI #includes are not available on Windows CE |
| 60 | #include <sys/types.h> |
| 61 | #include <sys/stat.h> |
| 62 | #include <errno.h> |
| 63 | #include <signal.h> |
| 64 | #include <fcntl.h> |
| 65 | #endif // !_WIN32_WCE |
| 66 | |
| 67 | #include <time.h> |
| 68 | #include <stdlib.h> |
| 69 | #include <stdarg.h> |
| 70 | #include <assert.h> |
| 71 | #include <string.h> |
| 72 | #include <ctype.h> |
| 73 | #include <limits.h> |
| 74 | #include <stddef.h> |
| 75 | #include <stdio.h> |
| 76 | |
| 77 | #if defined(_WIN32) && !defined(__SYMBIAN32__) // Windows specific |
| 78 | #undef _WIN32_WINNT |
| 79 | #define _WIN32_WINNT 0x0400 // To make it link in VS2005 |
| 80 | #include <windows.h> |
| 81 | |
| 82 | #ifndef PATH_MAX |
| 83 | #define PATH_MAX MAX_PATH |
| 84 | #endif |
| 85 | |
| 86 | #ifndef _WIN32_WCE |
| 87 | #include <process.h> |
| 88 | #include <direct.h> |
| 89 | #include <io.h> |
| 90 | #else // _WIN32_WCE |
| 91 | #define NO_CGI // WinCE has no pipes |
| 92 | |
| 93 | typedef long off_t; |
| 94 | |
| 95 | #define errno GetLastError() |
| 96 | #define strerror(x) _ultoa(x, (char *) _alloca(sizeof(x) *3 ), 10) |
| 97 | #endif // _WIN32_WCE |
| 98 | |
| 99 | #define MAKEUQUAD(lo, hi) ((uint64_t)(((uint32_t)(lo)) | \ |
| 100 | ((uint64_t)((uint32_t)(hi))) << 32)) |
| 101 | #define RATE_DIFF 10000000 // 100 nsecs |
| 102 | #define EPOCH_DIFF MAKEUQUAD(0xd53e8000, 0x019db1de) |
| 103 | #define SYS2UNIX_TIME(lo, hi) \ |
| 104 | (time_t) ((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF) |
| 105 | |
| 106 | // Visual Studio 6 does not know __func__ or __FUNCTION__ |
| 107 | // The rest of MS compilers use __FUNCTION__, not C99 __func__ |
| 108 | // Also use _strtoui64 on modern M$ compilers |
| 109 | #if defined(_MSC_VER) && _MSC_VER < 1300 |
| 110 | #define STRX(x) #x |
| 111 | #define STR(x) STRX(x) |
| 112 | #define __func__ __FILE__ ":" STR(__LINE__) |
| 113 | #define strtoull(x, y, z) (unsigned __int64) _atoi64(x) |
| 114 | #define strtoll(x, y, z) _atoi64(x) |
| 115 | #else |
| 116 | #define __func__ __FUNCTION__ |
| 117 | #define strtoull(x, y, z) _strtoui64(x, y, z) |
| 118 | #define strtoll(x, y, z) _strtoi64(x, y, z) |
| 119 | #endif // _MSC_VER |
| 120 | |
| 121 | #define ERRNO GetLastError() |
| 122 | #define NO_SOCKLEN_T |
| 123 | #define SSL_LIB "ssleay32.dll" |
| 124 | #define CRYPTO_LIB "libeay32.dll" |
| 125 | #define O_NONBLOCK 0 |
| 126 | #if !defined(EWOULDBLOCK) |
| 127 | #define EWOULDBLOCK WSAEWOULDBLOCK |
| 128 | #endif // !EWOULDBLOCK |
| 129 | #define _POSIX_ |
| 130 | #define INT64_FMT "I64d" |
| 131 | |
| 132 | #define WINCDECL __cdecl |
| 133 | #define SHUT_WR 1 |
| 134 | #define snprintf _snprintf |
| 135 | #define vsnprintf _vsnprintf |
| 136 | #define mg_sleep(x) Sleep(x) |
| 137 | |
| 138 | #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY) |
| 139 | #ifndef popen |
| 140 | #define popen(x, y) _popen(x, y) |
| 141 | #endif |
| 142 | #ifndef pclose |
| 143 | #define pclose(x) _pclose(x) |
| 144 | #endif |
| 145 | #define close(x) _close(x) |
| 146 | #define dlsym(x,y) GetProcAddress((HINSTANCE) (x), (y)) |
| 147 | #define RTLD_LAZY 0 |
| 148 | #define fseeko(x, y, z) _lseeki64(_fileno(x), (y), (z)) |
| 149 | #define fdopen(x, y) _fdopen((x), (y)) |
| 150 | #define write(x, y, z) _write((x), (y), (unsigned) z) |
| 151 | #define read(x, y, z) _read((x), (y), (unsigned) z) |
| 152 | #define flockfile(x) EnterCriticalSection(&global_log_file_lock) |
| 153 | #define funlockfile(x) LeaveCriticalSection(&global_log_file_lock) |
| 154 | #define sleep(x) Sleep((x) * 1000) |
| 155 | |
| 156 | #if !defined(va_copy) |
| 157 | #define va_copy(x, y) x = y |
| 158 | #endif // !va_copy MINGW #defines va_copy |
| 159 | |
| 160 | #if !defined(fileno) |
| 161 | #define fileno(x) _fileno(x) |
| 162 | #endif // !fileno MINGW #defines fileno |
| 163 | |
| 164 | typedef HANDLE pthread_mutex_t; |
| 165 | typedef struct {HANDLE signal, broadcast;} pthread_cond_t; |
| 166 | typedef DWORD pthread_t; |
| 167 | #define pid_t HANDLE // MINGW typedefs pid_t to int. Using #define here. |
| 168 | |
| 169 | static int pthread_mutex_lock(pthread_mutex_t *); |
| 170 | static int pthread_mutex_unlock(pthread_mutex_t *); |
| 171 | static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len); |
| 172 | struct file; |
| 173 | static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p); |
| 174 | |
| 175 | #if defined(HAVE_STDINT) |
| 176 | #include <stdint.h> |
| 177 | #else |
| 178 | typedef unsigned int uint32_t; |
| 179 | typedef unsigned short uint16_t; |
| 180 | typedef unsigned __int64 uint64_t; |
| 181 | typedef __int64 int64_t; |
| 182 | #define INT64_MAX 9223372036854775807 |
| 183 | #endif // HAVE_STDINT |
| 184 | |
| 185 | // POSIX dirent interface |
| 186 | struct dirent { |
| 187 | char d_name[PATH_MAX]; |
| 188 | }; |
| 189 | |
| 190 | typedef struct DIR { |
| 191 | HANDLE handle; |
| 192 | WIN32_FIND_DATAW info; |
| 193 | struct dirent result; |
| 194 | } DIR; |
| 195 | |
| 196 | #ifndef HAVE_POLL |
| 197 | struct pollfd { |
| 198 | int fd; |
| 199 | short events; |
| 200 | short revents; |
| 201 | }; |
| 202 | #define POLLIN 1 |
| 203 | #endif |
| 204 | |
| 205 | |
| 206 | // Mark required libraries |
| 207 | #ifdef _MSC_VER |
| 208 | #pragma comment(lib, "Ws2_32.lib") |
| 209 | #endif |
| 210 | |
| 211 | #else // UNIX specific |
| 212 | #include <sys/wait.h> |
| 213 | #include <sys/socket.h> |
| 214 | #include <sys/poll.h> |
| 215 | #include <netinet/in.h> |
| 216 | #include <arpa/inet.h> |
| 217 | #include <sys/time.h> |
| 218 | #include <stdint.h> |
| 219 | #include <inttypes.h> |
| 220 | #include <netdb.h> |
| 221 | |
| 222 | #include <pwd.h> |
| 223 | #include <unistd.h> |
| 224 | #include <dirent.h> |
| 225 | #if !defined(NO_SSL_DL) && !defined(NO_SSL) |
| 226 | #include <dlfcn.h> |
| 227 | #endif |
| 228 | #include <pthread.h> |
| 229 | #if defined(__MACH__) |
| 230 | #define SSL_LIB "libssl.dylib" |
| 231 | #define CRYPTO_LIB "libcrypto.dylib" |
| 232 | #else |
| 233 | #if !defined(SSL_LIB) |
| 234 | #define SSL_LIB "libssl.so" |
| 235 | #endif |
| 236 | #if !defined(CRYPTO_LIB) |
| 237 | #define CRYPTO_LIB "libcrypto.so" |
| 238 | #endif |
| 239 | #endif |
| 240 | #ifndef O_BINARY |
| 241 | #define O_BINARY 0 |
| 242 | #endif // O_BINARY |
| 243 | #define closesocket(a) close(a) |
| 244 | #define mg_mkdir(x, y) mkdir(x, y) |
| 245 | #define mg_remove(x) remove(x) |
| 246 | #define mg_sleep(x) usleep((x) * 1000) |
| 247 | #define ERRNO errno |
| 248 | #define INVALID_SOCKET (-1) |
| 249 | #define INT64_FMT PRId64 |
| 250 | typedef int SOCKET; |
| 251 | #define WINCDECL |
| 252 | |
| 253 | #endif // End of Windows and UNIX specific includes |
| 254 | |
| 255 | #include "mongoose.h" |
| 256 | |
| 257 | #define MONGOOSE_VERSION "3.8" |
| 258 | #define PASSWORDS_FILE_NAME ".htpasswd" |
| 259 | #define CGI_ENVIRONMENT_SIZE 4096 |
| 260 | #define MAX_CGI_ENVIR_VARS 64 |
| 261 | #define MG_BUF_LEN 8192 |
| 262 | #define MAX_REQUEST_SIZE 16384 |
| 263 | #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0])) |
| 264 | |
| 265 | #ifdef _WIN32 |
| 266 | static CRITICAL_SECTION global_log_file_lock; |
| 267 | static pthread_t pthread_self(void) { |
| 268 | return GetCurrentThreadId(); |
| 269 | } |
| 270 | #endif // _WIN32 |
| 271 | |
| 272 | #ifdef DEBUG_TRACE |
| 273 | #undef DEBUG_TRACE |
| 274 | #define DEBUG_TRACE(x) |
| 275 | #else |
| 276 | #if defined(DEBUG) |
| 277 | #define DEBUG_TRACE(x) do { \ |
| 278 | flockfile(stdout); \ |
| 279 | printf("*** %lu.%p.%s.%d: ", \ |
| 280 | (unsigned long) time(NULL), (void *) pthread_self(), \ |
| 281 | __func__, __LINE__); \ |
| 282 | printf x; \ |
| 283 | putchar('\n'); \ |
| 284 | fflush(stdout); \ |
| 285 | funlockfile(stdout); \ |
| 286 | } while (0) |
| 287 | #else |
| 288 | #define DEBUG_TRACE(x) |
| 289 | #endif // DEBUG |
| 290 | #endif // DEBUG_TRACE |
| 291 | |
| 292 | // Darwin prior to 7.0 and Win32 do not have socklen_t |
| 293 | #ifdef NO_SOCKLEN_T |
| 294 | typedef int socklen_t; |
| 295 | #endif // NO_SOCKLEN_T |
| 296 | #define _DARWIN_UNLIMITED_SELECT |
| 297 | |
| 298 | #define IP_ADDR_STR_LEN 50 // IPv6 hex string is 46 chars |
| 299 | |
| 300 | #if !defined(MSG_NOSIGNAL) |
| 301 | #define MSG_NOSIGNAL 0 |
| 302 | #endif |
| 303 | |
| 304 | #if !defined(SOMAXCONN) |
| 305 | #define SOMAXCONN 100 |
| 306 | #endif |
| 307 | |
| 308 | #if !defined(PATH_MAX) |
| 309 | #define PATH_MAX 4096 |
| 310 | #endif |
| 311 | |
| 312 | static const char *http_500_error = "Internal Server Error"; |
| 313 | |
| 314 | #if defined(NO_SSL_DL) |
| 315 | #include <openssl/ssl.h> |
| 316 | #else |
| 317 | // SSL loaded dynamically from DLL. |
| 318 | // I put the prototypes here to be independent from OpenSSL source installation. |
| 319 | typedef struct ssl_st SSL; |
| 320 | typedef struct ssl_method_st SSL_METHOD; |
| 321 | typedef struct ssl_ctx_st SSL_CTX; |
| 322 | |
| 323 | struct ssl_func { |
| 324 | const char *name; // SSL function name |
| 325 | void (*ptr)(void); // Function pointer |
| 326 | }; |
| 327 | |
| 328 | #define SSL_free (* (void (*)(SSL *)) ssl_sw[0].ptr) |
| 329 | #define SSL_accept (* (int (*)(SSL *)) ssl_sw[1].ptr) |
| 330 | #define SSL_connect (* (int (*)(SSL *)) ssl_sw[2].ptr) |
| 331 | #define SSL_read (* (int (*)(SSL *, void *, int)) ssl_sw[3].ptr) |
| 332 | #define SSL_write (* (int (*)(SSL *, const void *,int)) ssl_sw[4].ptr) |
| 333 | #define SSL_get_error (* (int (*)(SSL *, int)) ssl_sw[5].ptr) |
| 334 | #define SSL_set_fd (* (int (*)(SSL *, SOCKET)) ssl_sw[6].ptr) |
| 335 | #define SSL_new (* (SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr) |
| 336 | #define SSL_CTX_new (* (SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr) |
| 337 | #define SSLv23_server_method (* (SSL_METHOD * (*)(void)) ssl_sw[9].ptr) |
| 338 | #define SSL_library_init (* (int (*)(void)) ssl_sw[10].ptr) |
| 339 | #define SSL_CTX_use_PrivateKey_file (* (int (*)(SSL_CTX *, \ |
| 340 | const char *, int)) ssl_sw[11].ptr) |
| 341 | #define SSL_CTX_use_certificate_file (* (int (*)(SSL_CTX *, \ |
| 342 | const char *, int)) ssl_sw[12].ptr) |
| 343 | #define SSL_CTX_set_default_passwd_cb \ |
| 344 | (* (void (*)(SSL_CTX *, mg_callback_t)) ssl_sw[13].ptr) |
| 345 | #define SSL_CTX_free (* (void (*)(SSL_CTX *)) ssl_sw[14].ptr) |
| 346 | #define SSL_load_error_strings (* (void (*)(void)) ssl_sw[15].ptr) |
| 347 | #define SSL_CTX_use_certificate_chain_file \ |
| 348 | (* (int (*)(SSL_CTX *, const char *)) ssl_sw[16].ptr) |
| 349 | #define SSLv23_client_method (* (SSL_METHOD * (*)(void)) ssl_sw[17].ptr) |
| 350 | #define SSL_pending (* (int (*)(SSL *)) ssl_sw[18].ptr) |
| 351 | #define SSL_CTX_set_verify (* (void (*)(SSL_CTX *, int, int)) ssl_sw[19].ptr) |
| 352 | #define SSL_shutdown (* (int (*)(SSL *)) ssl_sw[20].ptr) |
| 353 | |
| 354 | #define CRYPTO_num_locks (* (int (*)(void)) crypto_sw[0].ptr) |
| 355 | #define CRYPTO_set_locking_callback \ |
| 356 | (* (void (*)(void (*)(int, int, const char *, int))) crypto_sw[1].ptr) |
| 357 | #define CRYPTO_set_id_callback \ |
| 358 | (* (void (*)(unsigned long (*)(void))) crypto_sw[2].ptr) |
| 359 | #define ERR_get_error (* (unsigned long (*)(void)) crypto_sw[3].ptr) |
| 360 | #define ERR_error_string (* (char * (*)(unsigned long,char *)) crypto_sw[4].ptr) |
| 361 | |
| 362 | // set_ssl_option() function updates this array. |
| 363 | // It loads SSL library dynamically and changes NULLs to the actual addresses |
| 364 | // of respective functions. The macros above (like SSL_connect()) are really |
| 365 | // just calling these functions indirectly via the pointer. |
| 366 | static struct ssl_func ssl_sw[] = { |
| 367 | {"SSL_free", NULL}, |
| 368 | {"SSL_accept", NULL}, |
| 369 | {"SSL_connect", NULL}, |
| 370 | {"SSL_read", NULL}, |
| 371 | {"SSL_write", NULL}, |
| 372 | {"SSL_get_error", NULL}, |
| 373 | {"SSL_set_fd", NULL}, |
| 374 | {"SSL_new", NULL}, |
| 375 | {"SSL_CTX_new", NULL}, |
| 376 | {"SSLv23_server_method", NULL}, |
| 377 | {"SSL_library_init", NULL}, |
| 378 | {"SSL_CTX_use_PrivateKey_file", NULL}, |
| 379 | {"SSL_CTX_use_certificate_file",NULL}, |
| 380 | {"SSL_CTX_set_default_passwd_cb",NULL}, |
| 381 | {"SSL_CTX_free", NULL}, |
| 382 | {"SSL_load_error_strings", NULL}, |
| 383 | {"SSL_CTX_use_certificate_chain_file", NULL}, |
| 384 | {"SSLv23_client_method", NULL}, |
| 385 | {"SSL_pending", NULL}, |
| 386 | {"SSL_CTX_set_verify", NULL}, |
| 387 | {"SSL_shutdown", NULL}, |
| 388 | {NULL, NULL} |
| 389 | }; |
| 390 | |
| 391 | // Similar array as ssl_sw. These functions could be located in different lib. |
| 392 | #if !defined(NO_SSL) |
| 393 | static struct ssl_func crypto_sw[] = { |
| 394 | {"CRYPTO_num_locks", NULL}, |
| 395 | {"CRYPTO_set_locking_callback", NULL}, |
| 396 | {"CRYPTO_set_id_callback", NULL}, |
| 397 | {"ERR_get_error", NULL}, |
| 398 | {"ERR_error_string", NULL}, |
| 399 | {NULL, NULL} |
| 400 | }; |
| 401 | #endif // NO_SSL |
| 402 | #endif // NO_SSL_DL |
| 403 | |
| 404 | static const char *month_names[] = { |
| 405 | "Jan", "Feb", "Mar", "Apr", "May", "Jun", |
| 406 | "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" |
| 407 | }; |
| 408 | |
| 409 | // Unified socket address. For IPv6 support, add IPv6 address structure |
| 410 | // in the union u. |
| 411 | union usa { |
| 412 | struct sockaddr sa; |
| 413 | struct sockaddr_in sin; |
| 414 | #if defined(USE_IPV6) |
| 415 | struct sockaddr_in6 sin6; |
| 416 | #endif |
| 417 | }; |
| 418 | |
| 419 | // Describes a string (chunk of memory). |
| 420 | struct vec { |
| 421 | const char *ptr; |
| 422 | size_t len; |
| 423 | }; |
| 424 | |
| 425 | struct file { |
| 426 | int is_directory; |
| 427 | time_t modification_time; |
| 428 | int64_t size; |
| 429 | FILE *fp; |
| 430 | const char *membuf; // Non-NULL if file data is in memory |
| 431 | // set to 1 if the content is gzipped |
| 432 | // in which case we need a content-encoding: gzip header |
| 433 | int gzipped; |
| 434 | }; |
| 435 | #define STRUCT_FILE_INITIALIZER {0, 0, 0, NULL, NULL, 0} |
| 436 | |
| 437 | // Describes listening socket, or socket which was accept()-ed by the master |
| 438 | // thread and queued for future handling by the worker thread. |
| 439 | struct socket { |
| 440 | SOCKET sock; // Listening socket |
| 441 | union usa lsa; // Local socket address |
| 442 | union usa rsa; // Remote socket address |
| 443 | unsigned is_ssl:1; // Is port SSL-ed |
| 444 | unsigned ssl_redir:1; // Is port supposed to redirect everything to SSL port |
| 445 | }; |
| 446 | |
| 447 | // NOTE(lsm): this enum shoulds be in sync with the config_options below. |
| 448 | enum { |
| 449 | CGI_EXTENSIONS, CGI_ENVIRONMENT, PUT_DELETE_PASSWORDS_FILE, CGI_INTERPRETER, |
| 450 | PROTECT_URI, AUTHENTICATION_DOMAIN, SSI_EXTENSIONS, THROTTLE, |
| 451 | ACCESS_LOG_FILE, ENABLE_DIRECTORY_LISTING, ERROR_LOG_FILE, |
| 452 | GLOBAL_PASSWORDS_FILE, INDEX_FILES, ENABLE_KEEP_ALIVE, ACCESS_CONTROL_LIST, |
| 453 | EXTRA_MIME_TYPES, LISTENING_PORTS, DOCUMENT_ROOT, SSL_CERTIFICATE, |
| 454 | NUM_THREADS, RUN_AS_USER, REWRITE, HIDE_FILES, REQUEST_TIMEOUT, |
| 455 | NUM_OPTIONS |
| 456 | }; |
| 457 | |
| 458 | static const char *config_options[] = { |
| 459 | "cgi_pattern", "**.cgi$|**.pl$|**.php$", |
| 460 | "cgi_environment", NULL, |
| 461 | "put_delete_auth_file", NULL, |
| 462 | "cgi_interpreter", NULL, |
| 463 | "protect_uri", NULL, |
| 464 | "authentication_domain", "mydomain.com", |
| 465 | "ssi_pattern", "**.shtml$|**.shtm$", |
| 466 | "throttle", NULL, |
| 467 | "access_log_file", NULL, |
| 468 | "enable_directory_listing", "yes", |
| 469 | "error_log_file", NULL, |
| 470 | "global_auth_file", NULL, |
| 471 | "index_files", |
| 472 | "index.html,index.htm,index.cgi,index.shtml,index.php,index.lp", |
| 473 | "enable_keep_alive", "no", |
| 474 | "access_control_list", NULL, |
| 475 | "extra_mime_types", NULL, |
| 476 | "listening_ports", "8080", |
| 477 | "document_root", ".", |
| 478 | "ssl_certificate", NULL, |
| 479 | "num_threads", "50", |
| 480 | "run_as_user", NULL, |
| 481 | "url_rewrite_patterns", NULL, |
| 482 | "hide_files_patterns", NULL, |
| 483 | "request_timeout_ms", "30000", |
| 484 | NULL |
| 485 | }; |
| 486 | |
| 487 | struct mg_context { |
| 488 | volatile int stop_flag; // Should we stop event loop |
| 489 | SSL_CTX *ssl_ctx; // SSL context |
| 490 | char *config[NUM_OPTIONS]; // Mongoose configuration parameters |
| 491 | struct mg_callbacks callbacks; // User-defined callback function |
| 492 | void *user_data; // User-defined data |
| 493 | |
| 494 | struct socket *listening_sockets; |
| 495 | int num_listening_sockets; |
| 496 | |
| 497 | volatile int num_threads; // Number of threads |
| 498 | pthread_mutex_t mutex; // Protects (max|num)_threads |
| 499 | pthread_cond_t cond; // Condvar for tracking workers terminations |
| 500 | |
| 501 | struct socket queue[20]; // Accepted sockets |
| 502 | volatile int sq_head; // Head of the socket queue |
| 503 | volatile int sq_tail; // Tail of the socket queue |
| 504 | pthread_cond_t sq_full; // Signaled when socket is produced |
| 505 | pthread_cond_t sq_empty; // Signaled when socket is consumed |
| 506 | }; |
| 507 | |
| 508 | struct mg_connection { |
| 509 | struct mg_request_info request_info; |
| 510 | struct mg_context *ctx; |
| 511 | SSL *ssl; // SSL descriptor |
| 512 | SSL_CTX *client_ssl_ctx; // SSL context for client connections |
| 513 | struct socket client; // Connected client |
| 514 | time_t birth_time; // Time when request was received |
| 515 | int64_t num_bytes_sent; // Total bytes sent to client |
| 516 | int64_t content_len; // Content-Length header value |
| 517 | int64_t consumed_content; // How many bytes of content have been read |
| 518 | char *buf; // Buffer for received data |
| 519 | char *path_info; // PATH_INFO part of the URL |
| 520 | int must_close; // 1 if connection must be closed |
| 521 | int buf_size; // Buffer size |
| 522 | int request_len; // Size of the request + headers in a buffer |
| 523 | int data_len; // Total size of data in a buffer |
| 524 | int status_code; // HTTP reply status code, e.g. 200 |
| 525 | int throttle; // Throttling, bytes/sec. <= 0 means no throttle |
| 526 | time_t last_throttle_time; // Last time throttled data was sent |
| 527 | int64_t last_throttle_bytes;// Bytes sent this second |
| 528 | }; |
| 529 | |
| 530 | // Directory entry |
| 531 | struct de { |
| 532 | struct mg_connection *conn; |
| 533 | char *file_name; |
| 534 | struct file file; |
| 535 | }; |
| 536 | |
| 537 | const char **mg_get_valid_option_names(void) { |
| 538 | return config_options; |
| 539 | } |
| 540 | |
| 541 | static int is_file_in_memory(struct mg_connection *conn, const char *path, |
| 542 | struct file *filep) { |
| 543 | size_t size = 0; |
| 544 | if ((filep->membuf = conn->ctx->callbacks.open_file == NULL ? NULL : |
| 545 | conn->ctx->callbacks.open_file(conn, path, &size)) != NULL) { |
| 546 | // NOTE: override filep->size only on success. Otherwise, it might break |
| 547 | // constructs like if (!mg_stat() || !mg_fopen()) ... |
| 548 | filep->size = size; |
| 549 | } |
| 550 | return filep->membuf != NULL; |
| 551 | } |
| 552 | |
| 553 | static int is_file_opened(const struct file *filep) { |
| 554 | return filep->membuf != NULL || filep->fp != NULL; |
| 555 | } |
| 556 | |
| 557 | static int mg_fopen(struct mg_connection *conn, const char *path, |
| 558 | const char *mode, struct file *filep) { |
| 559 | if (!is_file_in_memory(conn, path, filep)) { |
| 560 | #ifdef _WIN32 |
| 561 | wchar_t wbuf[PATH_MAX], wmode[20]; |
| 562 | to_unicode(path, wbuf, ARRAY_SIZE(wbuf)); |
| 563 | MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode)); |
| 564 | filep->fp = _wfopen(wbuf, wmode); |
| 565 | #else |
| 566 | filep->fp = fopen(path, mode); |
| 567 | #endif |
| 568 | } |
| 569 | |
| 570 | return is_file_opened(filep); |
| 571 | } |
| 572 | |
| 573 | static void mg_fclose(struct file *filep) { |
| 574 | if (filep != NULL && filep->fp != NULL) { |
| 575 | fclose(filep->fp); |
| 576 | } |
| 577 | } |
| 578 | |
| 579 | static int get_option_index(const char *name) { |
| 580 | int i; |
| 581 | |
| 582 | for (i = 0; config_options[i * 2] != NULL; i++) { |
| 583 | if (strcmp(config_options[i * 2], name) == 0) { |
| 584 | return i; |
| 585 | } |
| 586 | } |
| 587 | return -1; |
| 588 | } |
| 589 | |
| 590 | const char *mg_get_option(const struct mg_context *ctx, const char *name) { |
| 591 | int i; |
| 592 | if ((i = get_option_index(name)) == -1) { |
| 593 | return NULL; |
| 594 | } else if (ctx->config[i] == NULL) { |
| 595 | return ""; |
| 596 | } else { |
| 597 | return ctx->config[i]; |
| 598 | } |
| 599 | } |
| 600 | |
| 601 | static void sockaddr_to_string(char *buf, size_t len, |
| 602 | const union usa *usa) { |
| 603 | buf[0] = '\0'; |
| 604 | #if defined(USE_IPV6) |
| 605 | inet_ntop(usa->sa.sa_family, usa->sa.sa_family == AF_INET ? |
| 606 | (void *) &usa->sin.sin_addr : |
| 607 | (void *) &usa->sin6.sin6_addr, buf, len); |
| 608 | #elif defined(_WIN32) |
| 609 | // Only Windoze Vista (and newer) have inet_ntop() |
| 610 | strncpy(buf, inet_ntoa(usa->sin.sin_addr), len); |
| 611 | #else |
| 612 | inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, len); |
| 613 | #endif |
| 614 | } |
| 615 | |
| 616 | static void cry(struct mg_connection *conn, |
| 617 | PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3); |
| 618 | |
| 619 | // Print error message to the opened error log stream. |
| 620 | static void cry(struct mg_connection *conn, const char *fmt, ...) { |
| 621 | char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN]; |
| 622 | va_list ap; |
| 623 | FILE *fp; |
| 624 | time_t timestamp; |
| 625 | |
| 626 | va_start(ap, fmt); |
| 627 | (void) vsnprintf(buf, sizeof(buf), fmt, ap); |
| 628 | va_end(ap); |
| 629 | |
| 630 | // Do not lock when getting the callback value, here and below. |
| 631 | // I suppose this is fine, since function cannot disappear in the |
| 632 | // same way string option can. |
| 633 | if (conn->ctx->callbacks.log_message == NULL || |
| 634 | conn->ctx->callbacks.log_message(conn, buf) == 0) { |
| 635 | fp = conn->ctx == NULL || conn->ctx->config[ERROR_LOG_FILE] == NULL ? NULL : |
| 636 | fopen(conn->ctx->config[ERROR_LOG_FILE], "a+"); |
| 637 | |
| 638 | if (fp != NULL) { |
| 639 | flockfile(fp); |
| 640 | timestamp = time(NULL); |
| 641 | |
| 642 | sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa); |
| 643 | fprintf(fp, "[%010lu] [error] [client %s] ", (unsigned long) timestamp, |
| 644 | src_addr); |
| 645 | |
| 646 | if (conn->request_info.request_method != NULL) { |
| 647 | fprintf(fp, "%s %s: ", conn->request_info.request_method, |
| 648 | conn->request_info.uri); |
| 649 | } |
| 650 | |
| 651 | fprintf(fp, "%s", buf); |
| 652 | fputc('\n', fp); |
| 653 | funlockfile(fp); |
| 654 | fclose(fp); |
| 655 | } |
| 656 | } |
| 657 | } |
| 658 | |
| 659 | // Return fake connection structure. Used for logging, if connection |
| 660 | // is not applicable at the moment of logging. |
| 661 | static struct mg_connection *fc(struct mg_context *ctx) { |
| 662 | static struct mg_connection fake_connection; |
| 663 | fake_connection.ctx = ctx; |
| 664 | return &fake_connection; |
| 665 | } |
| 666 | |
| 667 | const char *mg_version(void) { |
| 668 | return MONGOOSE_VERSION; |
| 669 | } |
| 670 | |
| 671 | struct mg_request_info *mg_get_request_info(struct mg_connection *conn) { |
| 672 | return &conn->request_info; |
| 673 | } |
| 674 | |
| 675 | static void mg_strlcpy(register char *dst, register const char *src, size_t n) { |
| 676 | for (; *src != '\0' && n > 1; n--) { |
| 677 | *dst++ = *src++; |
| 678 | } |
| 679 | *dst = '\0'; |
| 680 | } |
| 681 | |
| 682 | static int lowercase(const char *s) { |
| 683 | return tolower(* (const unsigned char *) s); |
| 684 | } |
| 685 | |
| 686 | static int mg_strncasecmp(const char *s1, const char *s2, size_t len) { |
| 687 | int diff = 0; |
| 688 | |
| 689 | if (len > 0) |
| 690 | do { |
| 691 | diff = lowercase(s1++) - lowercase(s2++); |
| 692 | } while (diff == 0 && s1[-1] != '\0' && --len > 0); |
| 693 | |
| 694 | return diff; |
| 695 | } |
| 696 | |
| 697 | static int mg_strcasecmp(const char *s1, const char *s2) { |
| 698 | int diff; |
| 699 | |
| 700 | do { |
| 701 | diff = lowercase(s1++) - lowercase(s2++); |
| 702 | } while (diff == 0 && s1[-1] != '\0'); |
| 703 | |
| 704 | return diff; |
| 705 | } |
| 706 | |
| 707 | static char * mg_strndup(const char *ptr, size_t len) { |
| 708 | char *p; |
| 709 | |
| 710 | if ((p = (char *) malloc(len + 1)) != NULL) { |
| 711 | mg_strlcpy(p, ptr, len + 1); |
| 712 | } |
| 713 | |
| 714 | return p; |
| 715 | } |
| 716 | |
| 717 | static char * mg_strdup(const char *str) { |
| 718 | return mg_strndup(str, strlen(str)); |
| 719 | } |
| 720 | |
| 721 | static const char *mg_strcasestr(const char *big_str, const char *small_str) { |
| 722 | int i, big_len = strlen(big_str), small_len = strlen(small_str); |
| 723 | |
| 724 | for (i = 0; i <= big_len - small_len; i++) { |
| 725 | if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) { |
| 726 | return big_str + i; |
| 727 | } |
| 728 | } |
| 729 | |
| 730 | return NULL; |
| 731 | } |
| 732 | |
| 733 | // Like snprintf(), but never returns negative value, or a value |
| 734 | // that is larger than a supplied buffer. |
| 735 | // Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability |
| 736 | // in his audit report. |
| 737 | static int mg_vsnprintf(struct mg_connection *conn, char *buf, size_t buflen, |
| 738 | const char *fmt, va_list ap) { |
| 739 | int n; |
| 740 | |
| 741 | if (buflen == 0) |
| 742 | return 0; |
| 743 | |
| 744 | n = vsnprintf(buf, buflen, fmt, ap); |
| 745 | |
| 746 | if (n < 0) { |
| 747 | cry(conn, "vsnprintf error"); |
| 748 | n = 0; |
| 749 | } else if (n >= (int) buflen) { |
| 750 | cry(conn, "truncating vsnprintf buffer: [%.*s]", |
| 751 | n > 200 ? 200 : n, buf); |
| 752 | n = (int) buflen - 1; |
| 753 | } |
| 754 | buf[n] = '\0'; |
| 755 | |
| 756 | return n; |
| 757 | } |
| 758 | |
| 759 | static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen, |
| 760 | PRINTF_FORMAT_STRING(const char *fmt), ...) |
| 761 | PRINTF_ARGS(4, 5); |
| 762 | |
| 763 | static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen, |
| 764 | const char *fmt, ...) { |
| 765 | va_list ap; |
| 766 | int n; |
| 767 | |
| 768 | va_start(ap, fmt); |
| 769 | n = mg_vsnprintf(conn, buf, buflen, fmt, ap); |
| 770 | va_end(ap); |
| 771 | |
| 772 | return n; |
| 773 | } |
| 774 | |
| 775 | // Skip the characters until one of the delimiters characters found. |
| 776 | // 0-terminate resulting word. Skip the delimiter and following whitespaces. |
| 777 | // Advance pointer to buffer to the next word. Return found 0-terminated word. |
| 778 | // Delimiters can be quoted with quotechar. |
| 779 | static char *skip_quoted(char **buf, const char *delimiters, |
| 780 | const char *whitespace, char quotechar) { |
| 781 | char *p, *begin_word, *end_word, *end_whitespace; |
| 782 | |
| 783 | begin_word = *buf; |
| 784 | end_word = begin_word + strcspn(begin_word, delimiters); |
| 785 | |
| 786 | // Check for quotechar |
| 787 | if (end_word > begin_word) { |
| 788 | p = end_word - 1; |
| 789 | while (*p == quotechar) { |
| 790 | // If there is anything beyond end_word, copy it |
| 791 | if (*end_word == '\0') { |
| 792 | *p = '\0'; |
| 793 | break; |
| 794 | } else { |
| 795 | size_t end_off = strcspn(end_word + 1, delimiters); |
| 796 | memmove (p, end_word, end_off + 1); |
| 797 | p += end_off; // p must correspond to end_word - 1 |
| 798 | end_word += end_off + 1; |
| 799 | } |
| 800 | } |
| 801 | for (p++; p < end_word; p++) { |
| 802 | *p = '\0'; |
| 803 | } |
| 804 | } |
| 805 | |
| 806 | if (*end_word == '\0') { |
| 807 | *buf = end_word; |
| 808 | } else { |
| 809 | end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace); |
| 810 | |
| 811 | for (p = end_word; p < end_whitespace; p++) { |
| 812 | *p = '\0'; |
| 813 | } |
| 814 | |
| 815 | *buf = end_whitespace; |
| 816 | } |
| 817 | |
| 818 | return begin_word; |
| 819 | } |
| 820 | |
| 821 | // Simplified version of skip_quoted without quote char |
| 822 | // and whitespace == delimiters |
| 823 | static char *skip(char **buf, const char *delimiters) { |
| 824 | return skip_quoted(buf, delimiters, delimiters, 0); |
| 825 | } |
| 826 | |
| 827 | |
| 828 | // Return HTTP header value, or NULL if not found. |
| 829 | static const char *get_header(const struct mg_request_info *ri, |
| 830 | const char *name) { |
| 831 | int i; |
| 832 | |
| 833 | for (i = 0; i < ri->num_headers; i++) |
| 834 | if (!mg_strcasecmp(name, ri->http_headers[i].name)) |
| 835 | return ri->http_headers[i].value; |
| 836 | |
| 837 | return NULL; |
| 838 | } |
| 839 | |
| 840 | const char *mg_get_header(const struct mg_connection *conn, const char *name) { |
| 841 | return get_header(&conn->request_info, name); |
| 842 | } |
| 843 | |
| 844 | // A helper function for traversing a comma separated list of values. |
| 845 | // It returns a list pointer shifted to the next value, or NULL if the end |
| 846 | // of the list found. |
| 847 | // Value is stored in val vector. If value has form "x=y", then eq_val |
| 848 | // vector is initialized to point to the "y" part, and val vector length |
| 849 | // is adjusted to point only to "x". |
| 850 | static const char *next_option(const char *list, struct vec *val, |
| 851 | struct vec *eq_val) { |
| 852 | if (list == NULL || *list == '\0') { |
| 853 | // End of the list |
| 854 | list = NULL; |
| 855 | } else { |
| 856 | val->ptr = list; |
| 857 | if ((list = strchr(val->ptr, ',')) != NULL) { |
| 858 | // Comma found. Store length and shift the list ptr |
| 859 | val->len = list - val->ptr; |
| 860 | list++; |
| 861 | } else { |
| 862 | // This value is the last one |
| 863 | list = val->ptr + strlen(val->ptr); |
| 864 | val->len = list - val->ptr; |
| 865 | } |
| 866 | |
| 867 | if (eq_val != NULL) { |
| 868 | // Value has form "x=y", adjust pointers and lengths |
| 869 | // so that val points to "x", and eq_val points to "y". |
| 870 | eq_val->len = 0; |
| 871 | eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len); |
| 872 | if (eq_val->ptr != NULL) { |
| 873 | eq_val->ptr++; // Skip over '=' character |
| 874 | eq_val->len = val->ptr + val->len - eq_val->ptr; |
| 875 | val->len = (eq_val->ptr - val->ptr) - 1; |
| 876 | } |
| 877 | } |
| 878 | } |
| 879 | |
| 880 | return list; |
| 881 | } |
| 882 | |
| 883 | static int match_prefix(const char *pattern, int pattern_len, const char *str) { |
| 884 | const char *or_str; |
| 885 | int i, j, len, res; |
| 886 | |
| 887 | if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) { |
| 888 | res = match_prefix(pattern, or_str - pattern, str); |
| 889 | return res > 0 ? res : |
| 890 | match_prefix(or_str + 1, (pattern + pattern_len) - (or_str + 1), str); |
| 891 | } |
| 892 | |
| 893 | i = j = 0; |
| 894 | res = -1; |
| 895 | for (; i < pattern_len; i++, j++) { |
| 896 | if (pattern[i] == '?' && str[j] != '\0') { |
| 897 | continue; |
| 898 | } else if (pattern[i] == '$') { |
| 899 | return str[j] == '\0' ? j : -1; |
| 900 | } else if (pattern[i] == '*') { |
| 901 | i++; |
| 902 | if (pattern[i] == '*') { |
| 903 | i++; |
| 904 | len = (int) strlen(str + j); |
| 905 | } else { |
| 906 | len = (int) strcspn(str + j, "/"); |
| 907 | } |
| 908 | if (i == pattern_len) { |
| 909 | return j + len; |
| 910 | } |
| 911 | do { |
| 912 | res = match_prefix(pattern + i, pattern_len - i, str + j + len); |
| 913 | } while (res == -1 && len-- > 0); |
| 914 | return res == -1 ? -1 : j + res + len; |
| 915 | } else if (pattern[i] != str[j]) { |
| 916 | return -1; |
| 917 | } |
| 918 | } |
| 919 | return j; |
| 920 | } |
| 921 | |
| 922 | // HTTP 1.1 assumes keep alive if "Connection:" header is not set |
| 923 | // This function must tolerate situations when connection info is not |
| 924 | // set up, for example if request parsing failed. |
| 925 | static int should_keep_alive(const struct mg_connection *conn) { |
| 926 | const char *http_version = conn->request_info.http_version; |
| 927 | const char *header = mg_get_header(conn, "Connection"); |
| 928 | if (conn->must_close || |
| 929 | conn->status_code == 401 || |
| 930 | mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0 || |
| 931 | (header != NULL && mg_strcasecmp(header, "keep-alive") != 0) || |
| 932 | (header == NULL && http_version && strcmp(http_version, "1.1"))) { |
| 933 | return 0; |
| 934 | } |
| 935 | return 1; |
| 936 | } |
| 937 | |
| 938 | static const char *suggest_connection_header(const struct mg_connection *conn) { |
| 939 | return should_keep_alive(conn) ? "keep-alive" : "close"; |
| 940 | } |
| 941 | |
| 942 | static void send_http_error(struct mg_connection *, int, const char *, |
| 943 | PRINTF_FORMAT_STRING(const char *fmt), ...) |
| 944 | PRINTF_ARGS(4, 5); |
| 945 | |
| 946 | |
| 947 | static void send_http_error(struct mg_connection *conn, int status, |
| 948 | const char *reason, const char *fmt, ...) { |
| 949 | char buf[MG_BUF_LEN]; |
| 950 | va_list ap; |
| 951 | int len = 0; |
| 952 | |
| 953 | conn->status_code = status; |
| 954 | if (conn->ctx->callbacks.http_error == NULL || |
| 955 | conn->ctx->callbacks.http_error(conn, status)) { |
| 956 | buf[0] = '\0'; |
| 957 | |
| 958 | // Errors 1xx, 204 and 304 MUST NOT send a body |
| 959 | if (status > 199 && status != 204 && status != 304) { |
| 960 | len = mg_snprintf(conn, buf, sizeof(buf), "Error %d: %s", status, reason); |
| 961 | buf[len++] = '\n'; |
| 962 | |
| 963 | va_start(ap, fmt); |
| 964 | len += mg_vsnprintf(conn, buf + len, sizeof(buf) - len, fmt, ap); |
| 965 | va_end(ap); |
| 966 | } |
| 967 | DEBUG_TRACE(("[%s]", buf)); |
| 968 | |
| 969 | mg_printf(conn, "HTTP/1.1 %d %s\r\n" |
| 970 | "Content-Length: %d\r\n" |
| 971 | "Connection: %s\r\n\r\n", status, reason, len, |
| 972 | suggest_connection_header(conn)); |
| 973 | conn->num_bytes_sent += mg_printf(conn, "%s", buf); |
| 974 | } |
| 975 | } |
| 976 | |
| 977 | #if defined(_WIN32) && !defined(__SYMBIAN32__) |
| 978 | static int pthread_mutex_init(pthread_mutex_t *mutex, void *unused) { |
| 979 | (void) unused; |
| 980 | *mutex = CreateMutex(NULL, FALSE, NULL); |
| 981 | return *mutex == NULL ? -1 : 0; |
| 982 | } |
| 983 | |
| 984 | static int pthread_mutex_destroy(pthread_mutex_t *mutex) { |
| 985 | return CloseHandle(*mutex) == 0 ? -1 : 0; |
| 986 | } |
| 987 | |
| 988 | static int pthread_mutex_lock(pthread_mutex_t *mutex) { |
| 989 | return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1; |
| 990 | } |
| 991 | |
| 992 | static int pthread_mutex_unlock(pthread_mutex_t *mutex) { |
| 993 | return ReleaseMutex(*mutex) == 0 ? -1 : 0; |
| 994 | } |
| 995 | |
| 996 | static int pthread_cond_init(pthread_cond_t *cv, const void *unused) { |
| 997 | (void) unused; |
| 998 | cv->signal = CreateEvent(NULL, FALSE, FALSE, NULL); |
| 999 | cv->broadcast = CreateEvent(NULL, TRUE, FALSE, NULL); |
| 1000 | return cv->signal != NULL && cv->broadcast != NULL ? 0 : -1; |
| 1001 | } |
| 1002 | |
| 1003 | static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex) { |
| 1004 | HANDLE handles[] = {cv->signal, cv->broadcast}; |
| 1005 | ReleaseMutex(*mutex); |
| 1006 | WaitForMultipleObjects(2, handles, FALSE, INFINITE); |
| 1007 | return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1; |
| 1008 | } |
| 1009 | |
| 1010 | static int pthread_cond_signal(pthread_cond_t *cv) { |
| 1011 | return SetEvent(cv->signal) == 0 ? -1 : 0; |
| 1012 | } |
| 1013 | |
| 1014 | static int pthread_cond_broadcast(pthread_cond_t *cv) { |
| 1015 | // Implementation with PulseEvent() has race condition, see |
| 1016 | // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html |
| 1017 | return PulseEvent(cv->broadcast) == 0 ? -1 : 0; |
| 1018 | } |
| 1019 | |
| 1020 | static int pthread_cond_destroy(pthread_cond_t *cv) { |
| 1021 | return CloseHandle(cv->signal) && CloseHandle(cv->broadcast) ? 0 : -1; |
| 1022 | } |
| 1023 | |
| 1024 | // For Windows, change all slashes to backslashes in path names. |
| 1025 | static void change_slashes_to_backslashes(char *path) { |
| 1026 | int i; |
| 1027 | |
| 1028 | for (i = 0; path[i] != '\0'; i++) { |
| 1029 | if (path[i] == '/') |
| 1030 | path[i] = '\\'; |
| 1031 | // i > 0 check is to preserve UNC paths, like \\server\file.txt |
| 1032 | if (path[i] == '\\' && i > 0) |
| 1033 | while (path[i + 1] == '\\' || path[i + 1] == '/') |
| 1034 | (void) memmove(path + i + 1, |
| 1035 | path + i + 2, strlen(path + i + 1)); |
| 1036 | } |
| 1037 | } |
| 1038 | |
| 1039 | // Encode 'path' which is assumed UTF-8 string, into UNICODE string. |
| 1040 | // wbuf and wbuf_len is a target buffer and its length. |
| 1041 | static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len) { |
| 1042 | char buf[PATH_MAX], buf2[PATH_MAX]; |
| 1043 | |
| 1044 | mg_strlcpy(buf, path, sizeof(buf)); |
| 1045 | change_slashes_to_backslashes(buf); |
| 1046 | |
| 1047 | // Convert to Unicode and back. If doubly-converted string does not |
| 1048 | // match the original, something is fishy, reject. |
| 1049 | memset(wbuf, 0, wbuf_len * sizeof(wchar_t)); |
| 1050 | MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len); |
| 1051 | WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2), |
| 1052 | NULL, NULL); |
| 1053 | if (strcmp(buf, buf2) != 0) { |
| 1054 | wbuf[0] = L'\0'; |
| 1055 | } |
| 1056 | } |
| 1057 | |
| 1058 | #if defined(_WIN32_WCE) |
| 1059 | static time_t time(time_t *ptime) { |
| 1060 | time_t t; |
| 1061 | SYSTEMTIME st; |
| 1062 | FILETIME ft; |
| 1063 | |
| 1064 | GetSystemTime(&st); |
| 1065 | SystemTimeToFileTime(&st, &ft); |
| 1066 | t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime); |
| 1067 | |
| 1068 | if (ptime != NULL) { |
| 1069 | *ptime = t; |
| 1070 | } |
| 1071 | |
| 1072 | return t; |
| 1073 | } |
| 1074 | |
| 1075 | static struct tm *localtime(const time_t *ptime, struct tm *ptm) { |
| 1076 | int64_t t = ((int64_t) *ptime) * RATE_DIFF + EPOCH_DIFF; |
| 1077 | FILETIME ft, lft; |
| 1078 | SYSTEMTIME st; |
| 1079 | TIME_ZONE_INFORMATION tzinfo; |
| 1080 | |
| 1081 | if (ptm == NULL) { |
| 1082 | return NULL; |
| 1083 | } |
| 1084 | |
| 1085 | * (int64_t *) &ft = t; |
| 1086 | FileTimeToLocalFileTime(&ft, &lft); |
| 1087 | FileTimeToSystemTime(&lft, &st); |
| 1088 | ptm->tm_year = st.wYear - 1900; |
| 1089 | ptm->tm_mon = st.wMonth - 1; |
| 1090 | ptm->tm_wday = st.wDayOfWeek; |
| 1091 | ptm->tm_mday = st.wDay; |
| 1092 | ptm->tm_hour = st.wHour; |
| 1093 | ptm->tm_min = st.wMinute; |
| 1094 | ptm->tm_sec = st.wSecond; |
| 1095 | ptm->tm_yday = 0; // hope nobody uses this |
| 1096 | ptm->tm_isdst = |
| 1097 | GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0; |
| 1098 | |
| 1099 | return ptm; |
| 1100 | } |
| 1101 | |
| 1102 | static struct tm *gmtime(const time_t *ptime, struct tm *ptm) { |
| 1103 | // FIXME(lsm): fix this. |
| 1104 | return localtime(ptime, ptm); |
| 1105 | } |
| 1106 | |
| 1107 | static size_t strftime(char *dst, size_t dst_size, const char *fmt, |
| 1108 | const struct tm *tm) { |
| 1109 | (void) snprintf(dst, dst_size, "implement strftime() for WinCE"); |
| 1110 | return 0; |
| 1111 | } |
| 1112 | #endif |
| 1113 | |
| 1114 | // Windows happily opens files with some garbage at the end of file name. |
| 1115 | // For example, fopen("a.cgi ", "r") on Windows successfully opens |
| 1116 | // "a.cgi", despite one would expect an error back. |
| 1117 | // This function returns non-0 if path ends with some garbage. |
| 1118 | static int path_cannot_disclose_cgi(const char *path) { |
| 1119 | static const char *allowed_last_characters = "_-"; |
| 1120 | int last = path[strlen(path) - 1]; |
| 1121 | return isalnum(last) || strchr(allowed_last_characters, last) != NULL; |
| 1122 | } |
| 1123 | |
| 1124 | static int mg_stat(struct mg_connection *conn, const char *path, |
| 1125 | struct file *filep) { |
| 1126 | wchar_t wbuf[PATH_MAX]; |
| 1127 | WIN32_FILE_ATTRIBUTE_DATA info; |
| 1128 | |
| 1129 | if (!is_file_in_memory(conn, path, filep)) { |
| 1130 | to_unicode(path, wbuf, ARRAY_SIZE(wbuf)); |
| 1131 | if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) { |
| 1132 | filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh); |
| 1133 | filep->modification_time = SYS2UNIX_TIME( |
| 1134 | info.ftLastWriteTime.dwLowDateTime, |
| 1135 | info.ftLastWriteTime.dwHighDateTime); |
| 1136 | filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; |
| 1137 | // If file name is fishy, reset the file structure and return error. |
| 1138 | // Note it is important to reset, not just return the error, cause |
| 1139 | // functions like is_file_opened() check the struct. |
| 1140 | if (!filep->is_directory && !path_cannot_disclose_cgi(path)) { |
| 1141 | memset(filep, 0, sizeof(*filep)); |
| 1142 | } |
| 1143 | } |
| 1144 | } |
| 1145 | |
| 1146 | return filep->membuf != NULL || filep->modification_time != 0; |
| 1147 | } |
| 1148 | |
| 1149 | static int mg_remove(const char *path) { |
| 1150 | wchar_t wbuf[PATH_MAX]; |
| 1151 | to_unicode(path, wbuf, ARRAY_SIZE(wbuf)); |
| 1152 | return DeleteFileW(wbuf) ? 0 : -1; |
| 1153 | } |
| 1154 | |
| 1155 | static int mg_mkdir(const char *path, int mode) { |
| 1156 | char buf[PATH_MAX]; |
| 1157 | wchar_t wbuf[PATH_MAX]; |
| 1158 | |
| 1159 | (void) mode; |
| 1160 | mg_strlcpy(buf, path, sizeof(buf)); |
| 1161 | change_slashes_to_backslashes(buf); |
| 1162 | |
| 1163 | (void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf)); |
| 1164 | |
| 1165 | return CreateDirectoryW(wbuf, NULL) ? 0 : -1; |
| 1166 | } |
| 1167 | |
| 1168 | // Implementation of POSIX opendir/closedir/readdir for Windows. |
| 1169 | static DIR * opendir(const char *name) { |
| 1170 | DIR *dir = NULL; |
| 1171 | wchar_t wpath[PATH_MAX]; |
| 1172 | DWORD attrs; |
| 1173 | |
| 1174 | if (name == NULL) { |
| 1175 | SetLastError(ERROR_BAD_ARGUMENTS); |
| 1176 | } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) { |
| 1177 | SetLastError(ERROR_NOT_ENOUGH_MEMORY); |
| 1178 | } else { |
| 1179 | to_unicode(name, wpath, ARRAY_SIZE(wpath)); |
| 1180 | attrs = GetFileAttributesW(wpath); |
| 1181 | if (attrs != 0xFFFFFFFF && |
| 1182 | ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) { |
| 1183 | (void) wcscat(wpath, L"\\*"); |
| 1184 | dir->handle = FindFirstFileW(wpath, &dir->info); |
| 1185 | dir->result.d_name[0] = '\0'; |
| 1186 | } else { |
| 1187 | free(dir); |
| 1188 | dir = NULL; |
| 1189 | } |
| 1190 | } |
| 1191 | |
| 1192 | return dir; |
| 1193 | } |
| 1194 | |
| 1195 | static int closedir(DIR *dir) { |
| 1196 | int result = 0; |
| 1197 | |
| 1198 | if (dir != NULL) { |
| 1199 | if (dir->handle != INVALID_HANDLE_VALUE) |
| 1200 | result = FindClose(dir->handle) ? 0 : -1; |
| 1201 | |
| 1202 | free(dir); |
| 1203 | } else { |
| 1204 | result = -1; |
| 1205 | SetLastError(ERROR_BAD_ARGUMENTS); |
| 1206 | } |
| 1207 | |
| 1208 | return result; |
| 1209 | } |
| 1210 | |
| 1211 | static struct dirent *readdir(DIR *dir) { |
| 1212 | struct dirent *result = 0; |
| 1213 | |
| 1214 | if (dir) { |
| 1215 | if (dir->handle != INVALID_HANDLE_VALUE) { |
| 1216 | result = &dir->result; |
| 1217 | (void) WideCharToMultiByte(CP_UTF8, 0, |
| 1218 | dir->info.cFileName, -1, result->d_name, |
| 1219 | sizeof(result->d_name), NULL, NULL); |
| 1220 | |
| 1221 | if (!FindNextFileW(dir->handle, &dir->info)) { |
| 1222 | (void) FindClose(dir->handle); |
| 1223 | dir->handle = INVALID_HANDLE_VALUE; |
| 1224 | } |
| 1225 | |
| 1226 | } else { |
| 1227 | SetLastError(ERROR_FILE_NOT_FOUND); |
| 1228 | } |
| 1229 | } else { |
| 1230 | SetLastError(ERROR_BAD_ARGUMENTS); |
| 1231 | } |
| 1232 | |
| 1233 | return result; |
| 1234 | } |
| 1235 | |
| 1236 | #ifndef HAVE_POLL |
| 1237 | static int poll(struct pollfd *pfd, int n, int milliseconds) { |
| 1238 | struct timeval tv; |
| 1239 | fd_set set; |
| 1240 | int i, result, maxfd = 0; |
| 1241 | |
| 1242 | tv.tv_sec = milliseconds / 1000; |
| 1243 | tv.tv_usec = (milliseconds % 1000) * 1000; |
| 1244 | FD_ZERO(&set); |
| 1245 | |
| 1246 | for (i = 0; i < n; i++) { |
| 1247 | FD_SET((SOCKET) pfd[i].fd, &set); |
| 1248 | pfd[i].revents = 0; |
| 1249 | |
| 1250 | if (pfd[i].fd > maxfd) { |
| 1251 | maxfd = pfd[i].fd; |
| 1252 | } |
| 1253 | } |
| 1254 | |
| 1255 | if ((result = select(maxfd + 1, &set, NULL, NULL, &tv)) > 0) { |
| 1256 | for (i = 0; i < n; i++) { |
| 1257 | if (FD_ISSET(pfd[i].fd, &set)) { |
| 1258 | pfd[i].revents = POLLIN; |
| 1259 | } |
| 1260 | } |
| 1261 | } |
| 1262 | |
| 1263 | return result; |
| 1264 | } |
| 1265 | #endif // HAVE_POLL |
| 1266 | |
| 1267 | #define set_close_on_exec(x) // No FD_CLOEXEC on Windows |
| 1268 | |
| 1269 | int mg_start_thread(mg_thread_func_t f, void *p) { |
| 1270 | return (long)_beginthread((void (__cdecl *)(void *)) f, 0, p) == -1L ? -1 : 0; |
| 1271 | } |
| 1272 | |
| 1273 | static HANDLE dlopen(const char *dll_name, int flags) { |
| 1274 | wchar_t wbuf[PATH_MAX]; |
| 1275 | (void) flags; |
| 1276 | to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf)); |
| 1277 | return LoadLibraryW(wbuf); |
| 1278 | } |
| 1279 | |
| 1280 | #if !defined(NO_CGI) |
| 1281 | #define SIGKILL 0 |
| 1282 | static int kill(pid_t pid, int sig_num) { |
| 1283 | (void) TerminateProcess(pid, sig_num); |
| 1284 | (void) CloseHandle(pid); |
| 1285 | return 0; |
| 1286 | } |
| 1287 | |
| 1288 | static void trim_trailing_whitespaces(char *s) { |
| 1289 | char *e = s + strlen(s) - 1; |
| 1290 | while (e > s && isspace(* (unsigned char *) e)) { |
| 1291 | *e-- = '\0'; |
| 1292 | } |
| 1293 | } |
| 1294 | |
| 1295 | static pid_t spawn_process(struct mg_connection *conn, const char *prog, |
| 1296 | char *envblk, char *envp[], int fd_stdin, |
| 1297 | int fd_stdout, const char *dir) { |
| 1298 | HANDLE me; |
| 1299 | char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX], |
| 1300 | cmdline[PATH_MAX], buf[PATH_MAX]; |
| 1301 | struct file file = STRUCT_FILE_INITIALIZER; |
| 1302 | STARTUPINFOA si; |
| 1303 | PROCESS_INFORMATION pi = { 0 }; |
| 1304 | |
| 1305 | (void) envp; |
| 1306 | |
| 1307 | memset(&si, 0, sizeof(si)); |
| 1308 | si.cb = sizeof(si); |
| 1309 | |
| 1310 | // TODO(lsm): redirect CGI errors to the error log file |
| 1311 | si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; |
| 1312 | si.wShowWindow = SW_HIDE; |
| 1313 | |
| 1314 | me = GetCurrentProcess(); |
| 1315 | DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdin), me, |
| 1316 | &si.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS); |
| 1317 | DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdout), me, |
| 1318 | &si.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS); |
| 1319 | |
| 1320 | // If CGI file is a script, try to read the interpreter line |
| 1321 | interp = conn->ctx->config[CGI_INTERPRETER]; |
| 1322 | if (interp == NULL) { |
| 1323 | buf[0] = buf[1] = '\0'; |
| 1324 | |
| 1325 | // Read the first line of the script into the buffer |
| 1326 | snprintf(cmdline, sizeof(cmdline), "%s%c%s", dir, '/', prog); |
| 1327 | if (mg_fopen(conn, cmdline, "r", &file)) { |
| 1328 | p = (char *) file.membuf; |
| 1329 | mg_fgets(buf, sizeof(buf), &file, &p); |
| 1330 | mg_fclose(&file); |
| 1331 | buf[sizeof(buf) - 1] = '\0'; |
| 1332 | } |
| 1333 | |
| 1334 | if (buf[0] == '#' && buf[1] == '!') { |
| 1335 | trim_trailing_whitespaces(buf + 2); |
| 1336 | } else { |
| 1337 | buf[2] = '\0'; |
| 1338 | } |
| 1339 | interp = buf + 2; |
| 1340 | } |
| 1341 | |
| 1342 | if (interp[0] != '\0') { |
| 1343 | GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL); |
| 1344 | interp = full_interp; |
| 1345 | } |
| 1346 | GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL); |
| 1347 | |
| 1348 | mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%s%s\\%s", |
| 1349 | interp, interp[0] == '\0' ? "" : " ", full_dir, prog); |
| 1350 | |
| 1351 | DEBUG_TRACE(("Running [%s]", cmdline)); |
| 1352 | if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, |
| 1353 | CREATE_NEW_PROCESS_GROUP, envblk, NULL, &si, &pi) == 0) { |
| 1354 | cry(conn, "%s: CreateProcess(%s): %ld", |
| 1355 | __func__, cmdline, ERRNO); |
| 1356 | pi.hProcess = (pid_t) -1; |
| 1357 | } |
| 1358 | |
| 1359 | // Always close these to prevent handle leakage. |
| 1360 | (void) close(fd_stdin); |
| 1361 | (void) close(fd_stdout); |
| 1362 | |
| 1363 | (void) CloseHandle(si.hStdOutput); |
| 1364 | (void) CloseHandle(si.hStdInput); |
| 1365 | (void) CloseHandle(pi.hThread); |
| 1366 | |
| 1367 | return (pid_t) pi.hProcess; |
| 1368 | } |
| 1369 | #endif // !NO_CGI |
| 1370 | |
| 1371 | static int set_non_blocking_mode(SOCKET sock) { |
| 1372 | unsigned long on = 1; |
| 1373 | return ioctlsocket(sock, FIONBIO, &on); |
| 1374 | } |
| 1375 | |
| 1376 | #else |
| 1377 | static int mg_stat(struct mg_connection *conn, const char *path, |
| 1378 | struct file *filep) { |
| 1379 | struct stat st; |
| 1380 | |
| 1381 | if (!is_file_in_memory(conn, path, filep) && !stat(path, &st)) { |
| 1382 | filep->size = st.st_size; |
| 1383 | filep->modification_time = st.st_mtime; |
| 1384 | filep->is_directory = S_ISDIR(st.st_mode); |
| 1385 | } else { |
| 1386 | filep->modification_time = (time_t) 0; |
| 1387 | } |
| 1388 | |
| 1389 | return filep->membuf != NULL || filep->modification_time != (time_t) 0; |
| 1390 | } |
| 1391 | |
| 1392 | static void set_close_on_exec(int fd) { |
| 1393 | fcntl(fd, F_SETFD, FD_CLOEXEC); |
| 1394 | } |
| 1395 | |
| 1396 | int mg_start_thread(mg_thread_func_t func, void *param) { |
| 1397 | pthread_t thread_id; |
| 1398 | pthread_attr_t attr; |
| 1399 | int result; |
| 1400 | |
| 1401 | (void) pthread_attr_init(&attr); |
| 1402 | (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); |
| 1403 | // TODO(lsm): figure out why mongoose dies on Linux if next line is enabled |
| 1404 | // (void) pthread_attr_setstacksize(&attr, sizeof(struct mg_connection) * 5); |
| 1405 | |
| 1406 | result = pthread_create(&thread_id, &attr, func, param); |
| 1407 | pthread_attr_destroy(&attr); |
| 1408 | |
| 1409 | return result; |
| 1410 | } |
| 1411 | |
| 1412 | #ifndef NO_CGI |
| 1413 | static pid_t spawn_process(struct mg_connection *conn, const char *prog, |
| 1414 | char *envblk, char *envp[], int fd_stdin, |
| 1415 | int fd_stdout, const char *dir) { |
| 1416 | pid_t pid; |
| 1417 | const char *interp; |
| 1418 | |
| 1419 | (void) envblk; |
| 1420 | |
| 1421 | if ((pid = fork()) == -1) { |
| 1422 | // Parent |
| 1423 | send_http_error(conn, 500, http_500_error, "fork(): %s", strerror(ERRNO)); |
| 1424 | } else if (pid == 0) { |
| 1425 | // Child |
| 1426 | if (chdir(dir) != 0) { |
| 1427 | cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO)); |
| 1428 | } else if (dup2(fd_stdin, 0) == -1) { |
| 1429 | cry(conn, "%s: dup2(%d, 0): %s", __func__, fd_stdin, strerror(ERRNO)); |
| 1430 | } else if (dup2(fd_stdout, 1) == -1) { |
| 1431 | cry(conn, "%s: dup2(%d, 1): %s", __func__, fd_stdout, strerror(ERRNO)); |
| 1432 | } else { |
| 1433 | // Not redirecting stderr to stdout, to avoid output being littered |
| 1434 | // with the error messages. |
| 1435 | (void) close(fd_stdin); |
| 1436 | (void) close(fd_stdout); |
| 1437 | |
| 1438 | // After exec, all signal handlers are restored to their default values, |
| 1439 | // with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's |
| 1440 | // implementation, SIGCHLD's handler will leave unchanged after exec |
| 1441 | // if it was set to be ignored. Restore it to default action. |
| 1442 | signal(SIGCHLD, SIG_DFL); |
| 1443 | |
| 1444 | interp = conn->ctx->config[CGI_INTERPRETER]; |
| 1445 | if (interp == NULL) { |
| 1446 | (void) execle(prog, prog, NULL, envp); |
| 1447 | cry(conn, "%s: execle(%s): %s", __func__, prog, strerror(ERRNO)); |
| 1448 | } else { |
| 1449 | (void) execle(interp, interp, prog, NULL, envp); |
| 1450 | cry(conn, "%s: execle(%s %s): %s", __func__, interp, prog, |
| 1451 | strerror(ERRNO)); |
| 1452 | } |
| 1453 | } |
| 1454 | exit(EXIT_FAILURE); |
| 1455 | } |
| 1456 | |
| 1457 | // Parent. Close stdio descriptors |
| 1458 | (void) close(fd_stdin); |
| 1459 | (void) close(fd_stdout); |
| 1460 | |
| 1461 | return pid; |
| 1462 | } |
| 1463 | #endif // !NO_CGI |
| 1464 | |
| 1465 | static int set_non_blocking_mode(SOCKET sock) { |
| 1466 | int flags; |
| 1467 | |
| 1468 | flags = fcntl(sock, F_GETFL, 0); |
| 1469 | (void) fcntl(sock, F_SETFL, flags | O_NONBLOCK); |
| 1470 | |
| 1471 | return 0; |
| 1472 | } |
| 1473 | #endif // _WIN32 |
| 1474 | |
| 1475 | // Write data to the IO channel - opened file descriptor, socket or SSL |
| 1476 | // descriptor. Return number of bytes written. |
| 1477 | static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf, |
| 1478 | int64_t len) { |
| 1479 | int64_t sent; |
| 1480 | int n, k; |
| 1481 | |
| 1482 | (void) ssl; // Get rid of warning |
| 1483 | sent = 0; |
| 1484 | while (sent < len) { |
| 1485 | |
| 1486 | // How many bytes we send in this iteration |
| 1487 | k = len - sent > INT_MAX ? INT_MAX : (int) (len - sent); |
| 1488 | |
| 1489 | #ifndef NO_SSL |
| 1490 | if (ssl != NULL) { |
| 1491 | n = SSL_write(ssl, buf + sent, k); |
| 1492 | } else |
| 1493 | #endif |
| 1494 | if (fp != NULL) { |
| 1495 | n = (int) fwrite(buf + sent, 1, (size_t) k, fp); |
| 1496 | if (ferror(fp)) |
| 1497 | n = -1; |
| 1498 | } else { |
| 1499 | n = send(sock, buf + sent, (size_t) k, MSG_NOSIGNAL); |
| 1500 | } |
| 1501 | |
| 1502 | if (n <= 0) |
| 1503 | break; |
| 1504 | |
| 1505 | sent += n; |
| 1506 | } |
| 1507 | |
| 1508 | return sent; |
| 1509 | } |
| 1510 | |
| 1511 | // Read from IO channel - opened file descriptor, socket, or SSL descriptor. |
| 1512 | // Return negative value on error, or number of bytes read on success. |
| 1513 | static int pull(FILE *fp, struct mg_connection *conn, char *buf, int len) { |
| 1514 | int nread; |
| 1515 | |
| 1516 | if (fp != NULL) { |
| 1517 | // Use read() instead of fread(), because if we're reading from the CGI |
| 1518 | // pipe, fread() may block until IO buffer is filled up. We cannot afford |
| 1519 | // to block and must pass all read bytes immediately to the client. |
| 1520 | nread = read(fileno(fp), buf, (size_t) len); |
| 1521 | #ifndef NO_SSL |
| 1522 | } else if (conn->ssl != NULL) { |
| 1523 | nread = SSL_read(conn->ssl, buf, len); |
| 1524 | #endif |
| 1525 | } else { |
| 1526 | nread = recv(conn->client.sock, buf, (size_t) len, 0); |
| 1527 | } |
| 1528 | |
| 1529 | return conn->ctx->stop_flag ? -1 : nread; |
| 1530 | } |
| 1531 | |
| 1532 | static int pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len) { |
| 1533 | int n, nread = 0; |
| 1534 | |
| 1535 | while (len > 0) { |
| 1536 | n = pull(fp, conn, buf + nread, len); |
| 1537 | if (n < 0) { |
| 1538 | nread = n; // Propagate the error |
| 1539 | break; |
| 1540 | } else if (n == 0) { |
| 1541 | break; // No more data to read |
| 1542 | } else { |
| 1543 | conn->consumed_content += n; |
| 1544 | nread += n; |
| 1545 | len -= n; |
| 1546 | } |
| 1547 | } |
| 1548 | |
| 1549 | return nread; |
| 1550 | } |
| 1551 | |
| 1552 | int mg_read(struct mg_connection *conn, void *buf, size_t len) { |
| 1553 | int n, buffered_len, nread; |
| 1554 | const char *body; |
| 1555 | |
| 1556 | // If Content-Length is not set, read until socket is closed |
| 1557 | if (conn->consumed_content == 0 && conn->content_len == 0) { |
| 1558 | conn->content_len = INT64_MAX; |
| 1559 | conn->must_close = 1; |
| 1560 | } |
| 1561 | |
| 1562 | nread = 0; |
| 1563 | if (conn->consumed_content < conn->content_len) { |
| 1564 | // Adjust number of bytes to read. |
| 1565 | int64_t to_read = conn->content_len - conn->consumed_content; |
| 1566 | if (to_read < (int64_t) len) { |
| 1567 | len = (size_t) to_read; |
| 1568 | } |
| 1569 | |
| 1570 | // Return buffered data |
| 1571 | body = conn->buf + conn->request_len + conn->consumed_content; |
| 1572 | buffered_len = &conn->buf[conn->data_len] - body; |
| 1573 | if (buffered_len > 0) { |
| 1574 | if (len < (size_t) buffered_len) { |
| 1575 | buffered_len = (int) len; |
| 1576 | } |
| 1577 | memcpy(buf, body, (size_t) buffered_len); |
| 1578 | len -= buffered_len; |
| 1579 | conn->consumed_content += buffered_len; |
| 1580 | nread += buffered_len; |
| 1581 | buf = (char *) buf + buffered_len; |
| 1582 | } |
| 1583 | |
| 1584 | // We have returned all buffered data. Read new data from the remote socket. |
| 1585 | n = pull_all(NULL, conn, (char *) buf, (int) len); |
| 1586 | nread = n >= 0 ? nread + n : n; |
| 1587 | } |
| 1588 | return nread; |
| 1589 | } |
| 1590 | |
| 1591 | int mg_write(struct mg_connection *conn, const void *buf, size_t len) { |
| 1592 | time_t now; |
| 1593 | int64_t n, total, allowed; |
| 1594 | |
| 1595 | if (conn->throttle > 0) { |
| 1596 | if ((now = time(NULL)) != conn->last_throttle_time) { |
| 1597 | conn->last_throttle_time = now; |
| 1598 | conn->last_throttle_bytes = 0; |
| 1599 | } |
| 1600 | allowed = conn->throttle - conn->last_throttle_bytes; |
| 1601 | if (allowed > (int64_t) len) { |
| 1602 | allowed = len; |
| 1603 | } |
| 1604 | if ((total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf, |
| 1605 | (int64_t) allowed)) == allowed) { |
| 1606 | buf = (char *) buf + total; |
| 1607 | conn->last_throttle_bytes += total; |
| 1608 | while (total < (int64_t) len && conn->ctx->stop_flag == 0) { |
| 1609 | allowed = conn->throttle > (int64_t) len - total ? |
| 1610 | (int64_t) len - total : conn->throttle; |
| 1611 | if ((n = push(NULL, conn->client.sock, conn->ssl, (const char *) buf, |
| 1612 | (int64_t) allowed)) != allowed) { |
| 1613 | break; |
| 1614 | } |
| 1615 | sleep(1); |
| 1616 | conn->last_throttle_bytes = allowed; |
| 1617 | conn->last_throttle_time = time(NULL); |
| 1618 | buf = (char *) buf + n; |
| 1619 | total += n; |
| 1620 | } |
| 1621 | } |
| 1622 | } else { |
| 1623 | total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf, |
| 1624 | (int64_t) len); |
| 1625 | } |
| 1626 | return (int) total; |
| 1627 | } |
| 1628 | |
| 1629 | // Print message to buffer. If buffer is large enough to hold the message, |
| 1630 | // return buffer. If buffer is to small, allocate large enough buffer on heap, |
| 1631 | // and return allocated buffer. |
| 1632 | static int alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap) { |
| 1633 | va_list ap_copy; |
| 1634 | int len; |
| 1635 | |
| 1636 | // Windows is not standard-compliant, and vsnprintf() returns -1 if |
| 1637 | // buffer is too small. Also, older versions of msvcrt.dll do not have |
| 1638 | // _vscprintf(). However, if size is 0, vsnprintf() behaves correctly. |
| 1639 | // Therefore, we make two passes: on first pass, get required message length. |
| 1640 | // On second pass, actually print the message. |
| 1641 | va_copy(ap_copy, ap); |
| 1642 | len = vsnprintf(NULL, 0, fmt, ap_copy); |
| 1643 | |
| 1644 | if (len > (int) size && |
| 1645 | (size = len + 1) > 0 && |
| 1646 | (*buf = (char *) malloc(size)) == NULL) { |
| 1647 | len = -1; // Allocation failed, mark failure |
| 1648 | } else { |
| 1649 | va_copy(ap_copy, ap); |
| 1650 | vsnprintf(*buf, size, fmt, ap_copy); |
| 1651 | } |
| 1652 | |
| 1653 | return len; |
| 1654 | } |
| 1655 | |
| 1656 | int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap) { |
| 1657 | char mem[MG_BUF_LEN], *buf = mem; |
| 1658 | int len; |
| 1659 | |
| 1660 | if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) { |
| 1661 | len = mg_write(conn, buf, (size_t) len); |
| 1662 | } |
| 1663 | if (buf != mem && buf != NULL) { |
| 1664 | free(buf); |
| 1665 | } |
| 1666 | |
| 1667 | return len; |
| 1668 | } |
| 1669 | |
| 1670 | int mg_printf(struct mg_connection *conn, const char *fmt, ...) { |
| 1671 | va_list ap; |
| 1672 | va_start(ap, fmt); |
| 1673 | return mg_vprintf(conn, fmt, ap); |
| 1674 | } |
| 1675 | |
| 1676 | int mg_url_decode(const char *src, int src_len, char *dst, |
| 1677 | int dst_len, int is_form_url_encoded) { |
| 1678 | int i, j, a, b; |
| 1679 | #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W') |
| 1680 | |
| 1681 | for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) { |
| 1682 | if (src[i] == '%' && i < src_len - 2 && |
| 1683 | isxdigit(* (const unsigned char *) (src + i + 1)) && |
| 1684 | isxdigit(* (const unsigned char *) (src + i + 2))) { |
| 1685 | a = tolower(* (const unsigned char *) (src + i + 1)); |
| 1686 | b = tolower(* (const unsigned char *) (src + i + 2)); |
| 1687 | dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b)); |
| 1688 | i += 2; |
| 1689 | } else if (is_form_url_encoded && src[i] == '+') { |
| 1690 | dst[j] = ' '; |
| 1691 | } else { |
| 1692 | dst[j] = src[i]; |
| 1693 | } |
| 1694 | } |
| 1695 | |
| 1696 | dst[j] = '\0'; // Null-terminate the destination |
| 1697 | |
| 1698 | return i >= src_len ? j : -1; |
| 1699 | } |
| 1700 | |
| 1701 | int mg_get_var(const char *data, size_t data_len, const char *name, |
| 1702 | char *dst, size_t dst_len) { |
| 1703 | const char *p, *e, *s; |
| 1704 | size_t name_len; |
| 1705 | int len; |
| 1706 | |
| 1707 | if (dst == NULL || dst_len == 0) { |
| 1708 | len = -2; |
| 1709 | } else if (data == NULL || name == NULL || data_len == 0) { |
| 1710 | len = -1; |
| 1711 | dst[0] = '\0'; |
| 1712 | } else { |
| 1713 | name_len = strlen(name); |
| 1714 | e = data + data_len; |
| 1715 | len = -1; |
| 1716 | dst[0] = '\0'; |
| 1717 | |
| 1718 | // data is "var1=val1&var2=val2...". Find variable first |
| 1719 | for (p = data; p + name_len < e; p++) { |
| 1720 | if ((p == data || p[-1] == '&') && p[name_len] == '=' && |
| 1721 | !mg_strncasecmp(name, p, name_len)) { |
| 1722 | |
| 1723 | // Point p to variable value |
| 1724 | p += name_len + 1; |
| 1725 | |
| 1726 | // Point s to the end of the value |
| 1727 | s = (const char *) memchr(p, '&', (size_t)(e - p)); |
| 1728 | if (s == NULL) { |
| 1729 | s = e; |
| 1730 | } |
| 1731 | assert(s >= p); |
| 1732 | |
| 1733 | // Decode variable into destination buffer |
| 1734 | len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1); |
| 1735 | |
| 1736 | // Redirect error code from -1 to -2 (destination buffer too small). |
| 1737 | if (len == -1) { |
| 1738 | len = -2; |
| 1739 | } |
| 1740 | break; |
| 1741 | } |
| 1742 | } |
| 1743 | } |
| 1744 | |
| 1745 | return len; |
| 1746 | } |
| 1747 | |
| 1748 | int mg_get_cookie(const char *cookie_header, const char *var_name, |
| 1749 | char *dst, size_t dst_size) { |
| 1750 | const char *s, *p, *end; |
| 1751 | int name_len, len = -1; |
| 1752 | |
| 1753 | if (dst == NULL || dst_size == 0) { |
| 1754 | len = -2; |
| 1755 | } else if (var_name == NULL || (s = cookie_header) == NULL) { |
| 1756 | len = -1; |
| 1757 | dst[0] = '\0'; |
| 1758 | } else { |
| 1759 | name_len = (int) strlen(var_name); |
| 1760 | end = s + strlen(s); |
| 1761 | dst[0] = '\0'; |
| 1762 | |
| 1763 | for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) { |
| 1764 | if (s[name_len] == '=') { |
| 1765 | s += name_len + 1; |
| 1766 | if ((p = strchr(s, ' ')) == NULL) |
| 1767 | p = end; |
| 1768 | if (p[-1] == ';') |
| 1769 | p--; |
| 1770 | if (*s == '"' && p[-1] == '"' && p > s + 1) { |
| 1771 | s++; |
| 1772 | p--; |
| 1773 | } |
| 1774 | if ((size_t) (p - s) < dst_size) { |
| 1775 | len = p - s; |
| 1776 | mg_strlcpy(dst, s, (size_t) len + 1); |
| 1777 | } else { |
| 1778 | len = -3; |
| 1779 | } |
| 1780 | break; |
| 1781 | } |
| 1782 | } |
| 1783 | } |
| 1784 | return len; |
| 1785 | } |
| 1786 | |
| 1787 | static void convert_uri_to_file_name(struct mg_connection *conn, char *buf, |
| 1788 | size_t buf_len, struct file *filep) { |
| 1789 | struct vec a, b; |
| 1790 | const char *rewrite, *uri = conn->request_info.uri; |
| 1791 | char *p; |
| 1792 | int match_len; |
| 1793 | char gz_path[PATH_MAX]; |
| 1794 | char const* accept_encoding; |
| 1795 | |
| 1796 | // Using buf_len - 1 because memmove() for PATH_INFO may shift part |
| 1797 | // of the path one byte on the right. |
| 1798 | mg_snprintf(conn, buf, buf_len - 1, "%s%s", conn->ctx->config[DOCUMENT_ROOT], |
| 1799 | uri); |
| 1800 | |
| 1801 | rewrite = conn->ctx->config[REWRITE]; |
| 1802 | while ((rewrite = next_option(rewrite, &a, &b)) != NULL) { |
| 1803 | if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) { |
| 1804 | mg_snprintf(conn, buf, buf_len - 1, "%.*s%s", (int) b.len, b.ptr, |
| 1805 | uri + match_len); |
| 1806 | break; |
| 1807 | } |
| 1808 | } |
| 1809 | |
| 1810 | if (mg_stat(conn, buf, filep)) return; |
| 1811 | |
| 1812 | // if we can't find the actual file, look for the file |
| 1813 | // with the same name but a .gz extension. If we find it, |
| 1814 | // use that and set the gzipped flag in the file struct |
| 1815 | // to indicate that the response need to have the content- |
| 1816 | // encoding: gzip header |
| 1817 | // we can only do this if the browser declares support |
| 1818 | if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) { |
| 1819 | if (strstr(accept_encoding,"gzip") != NULL) { |
| 1820 | snprintf(gz_path, sizeof(gz_path), "%s.gz", buf); |
| 1821 | if (mg_stat(conn, gz_path, filep)) { |
| 1822 | filep->gzipped = 1; |
| 1823 | return; |
| 1824 | } |
| 1825 | } |
| 1826 | } |
| 1827 | |
| 1828 | // Support PATH_INFO for CGI scripts. |
| 1829 | for (p = buf + strlen(buf); p > buf + 1; p--) { |
| 1830 | if (*p == '/') { |
| 1831 | *p = '\0'; |
| 1832 | if (match_prefix(conn->ctx->config[CGI_EXTENSIONS], |
| 1833 | strlen(conn->ctx->config[CGI_EXTENSIONS]), buf) > 0 && |
| 1834 | mg_stat(conn, buf, filep)) { |
| 1835 | // Shift PATH_INFO block one character right, e.g. |
| 1836 | // "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00" |
| 1837 | // conn->path_info is pointing to the local variable "path" declared |
| 1838 | // in handle_request(), so PATH_INFO is not valid after |
| 1839 | // handle_request returns. |
| 1840 | conn->path_info = p + 1; |
| 1841 | memmove(p + 2, p + 1, strlen(p + 1) + 1); // +1 is for trailing \0 |
| 1842 | p[1] = '/'; |
| 1843 | break; |
| 1844 | } else { |
| 1845 | *p = '/'; |
| 1846 | } |
| 1847 | } |
| 1848 | } |
| 1849 | } |
| 1850 | |
| 1851 | // Check whether full request is buffered. Return: |
| 1852 | // -1 if request is malformed |
| 1853 | // 0 if request is not yet fully buffered |
| 1854 | // >0 actual request length, including last \r\n\r\n |
| 1855 | static int get_request_len(const char *buf, int buflen) { |
| 1856 | const char *s, *e; |
| 1857 | int len = 0; |
| 1858 | |
| 1859 | for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++) |
| 1860 | // Control characters are not allowed but >=128 is. |
| 1861 | if (!isprint(* (const unsigned char *) s) && *s != '\r' && |
| 1862 | *s != '\n' && * (const unsigned char *) s < 128) { |
| 1863 | len = -1; |
| 1864 | break; // [i_a] abort scan as soon as one malformed character is found; |
| 1865 | // don't let subsequent \r\n\r\n win us over anyhow |
| 1866 | } else if (s[0] == '\n' && s[1] == '\n') { |
| 1867 | len = (int) (s - buf) + 2; |
| 1868 | } else if (s[0] == '\n' && &s[1] < e && |
| 1869 | s[1] == '\r' && s[2] == '\n') { |
| 1870 | len = (int) (s - buf) + 3; |
| 1871 | } |
| 1872 | |
| 1873 | return len; |
| 1874 | } |
| 1875 | |
| 1876 | // Convert month to the month number. Return -1 on error, or month number |
| 1877 | static int get_month_index(const char *s) { |
| 1878 | size_t i; |
| 1879 | |
| 1880 | for (i = 0; i < ARRAY_SIZE(month_names); i++) |
| 1881 | if (!strcmp(s, month_names[i])) |
| 1882 | return (int) i; |
| 1883 | |
| 1884 | return -1; |
| 1885 | } |
| 1886 | |
| 1887 | static int num_leap_years(int year) { |
| 1888 | return year / 4 - year / 100 + year / 400; |
| 1889 | } |
| 1890 | |
| 1891 | // Parse UTC date-time string, and return the corresponding time_t value. |
| 1892 | static time_t parse_date_string(const char *datetime) { |
| 1893 | static const unsigned short days_before_month[] = { |
| 1894 | 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 |
| 1895 | }; |
| 1896 | char month_str[32]; |
| 1897 | int second, minute, hour, day, month, year, leap_days, days; |
| 1898 | time_t result = (time_t) 0; |
| 1899 | |
| 1900 | if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d", |
| 1901 | &day, month_str, &year, &hour, &minute, &second) == 6) || |
| 1902 | (sscanf(datetime, "%d %3s %d %d:%d:%d", |
| 1903 | &day, month_str, &year, &hour, &minute, &second) == 6) || |
| 1904 | (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", |
| 1905 | &day, month_str, &year, &hour, &minute, &second) == 6) || |
| 1906 | (sscanf(datetime, "%d-%3s-%d %d:%d:%d", |
| 1907 | &day, month_str, &year, &hour, &minute, &second) == 6)) && |
| 1908 | year > 1970 && |
| 1909 | (month = get_month_index(month_str)) != -1) { |
| 1910 | leap_days = num_leap_years(year) - num_leap_years(1970); |
| 1911 | year -= 1970; |
| 1912 | days = year * 365 + days_before_month[month] + (day - 1) + leap_days; |
| 1913 | result = days * 24 * 3600 + hour * 3600 + minute * 60 + second; |
| 1914 | } |
| 1915 | |
| 1916 | return result; |
| 1917 | } |
| 1918 | |
| 1919 | // Protect against directory disclosure attack by removing '..', |
| 1920 | // excessive '/' and '\' characters |
| 1921 | static void remove_double_dots_and_double_slashes(char *s) { |
| 1922 | char *p = s; |
| 1923 | |
| 1924 | while (*s != '\0') { |
| 1925 | *p++ = *s++; |
| 1926 | if (s[-1] == '/' || s[-1] == '\\') { |
| 1927 | // Skip all following slashes, backslashes and double-dots |
| 1928 | while (s[0] != '\0') { |
| 1929 | if (s[0] == '/' || s[0] == '\\') { |
| 1930 | s++; |
| 1931 | } else if (s[0] == '.' && s[1] == '.') { |
| 1932 | s += 2; |
| 1933 | } else { |
| 1934 | break; |
| 1935 | } |
| 1936 | } |
| 1937 | } |
| 1938 | } |
| 1939 | *p = '\0'; |
| 1940 | } |
| 1941 | |
| 1942 | static const struct { |
| 1943 | const char *extension; |
| 1944 | size_t ext_len; |
| 1945 | const char *mime_type; |
| 1946 | } builtin_mime_types[] = { |
| 1947 | {".html", 5, "text/html"}, |
| 1948 | {".htm", 4, "text/html"}, |
| 1949 | {".shtm", 5, "text/html"}, |
| 1950 | {".shtml", 6, "text/html"}, |
| 1951 | {".css", 4, "text/css"}, |
| 1952 | {".js", 3, "application/x-javascript"}, |
| 1953 | {".ico", 4, "image/x-icon"}, |
| 1954 | {".gif", 4, "image/gif"}, |
| 1955 | {".jpg", 4, "image/jpeg"}, |
| 1956 | {".jpeg", 5, "image/jpeg"}, |
| 1957 | {".png", 4, "image/png"}, |
| 1958 | {".svg", 4, "image/svg+xml"}, |
| 1959 | {".txt", 4, "text/plain"}, |
| 1960 | {".torrent", 8, "application/x-bittorrent"}, |
| 1961 | {".wav", 4, "audio/x-wav"}, |
| 1962 | {".mp3", 4, "audio/x-mp3"}, |
| 1963 | {".mid", 4, "audio/mid"}, |
| 1964 | {".m3u", 4, "audio/x-mpegurl"}, |
| 1965 | {".ogg", 4, "audio/ogg"}, |
| 1966 | {".ram", 4, "audio/x-pn-realaudio"}, |
| 1967 | {".xml", 4, "text/xml"}, |
| 1968 | {".json", 5, "text/json"}, |
| 1969 | {".xslt", 5, "application/xml"}, |
| 1970 | {".xsl", 4, "application/xml"}, |
| 1971 | {".ra", 3, "audio/x-pn-realaudio"}, |
| 1972 | {".doc", 4, "application/msword"}, |
| 1973 | {".exe", 4, "application/octet-stream"}, |
| 1974 | {".zip", 4, "application/x-zip-compressed"}, |
| 1975 | {".xls", 4, "application/excel"}, |
| 1976 | {".tgz", 4, "application/x-tar-gz"}, |
| 1977 | {".tar", 4, "application/x-tar"}, |
| 1978 | {".gz", 3, "application/x-gunzip"}, |
| 1979 | {".arj", 4, "application/x-arj-compressed"}, |
| 1980 | {".rar", 4, "application/x-arj-compressed"}, |
| 1981 | {".rtf", 4, "application/rtf"}, |
| 1982 | {".pdf", 4, "application/pdf"}, |
| 1983 | {".swf", 4, "application/x-shockwave-flash"}, |
| 1984 | {".mpg", 4, "video/mpeg"}, |
| 1985 | {".webm", 5, "video/webm"}, |
| 1986 | {".mpeg", 5, "video/mpeg"}, |
| 1987 | {".mov", 4, "video/quicktime"}, |
| 1988 | {".mp4", 4, "video/mp4"}, |
| 1989 | {".m4v", 4, "video/x-m4v"}, |
| 1990 | {".asf", 4, "video/x-ms-asf"}, |
| 1991 | {".avi", 4, "video/x-msvideo"}, |
| 1992 | {".bmp", 4, "image/bmp"}, |
| 1993 | {".ttf", 4, "application/x-font-ttf"}, |
| 1994 | {NULL, 0, NULL} |
| 1995 | }; |
| 1996 | |
| 1997 | const char *mg_get_builtin_mime_type(const char *path) { |
| 1998 | const char *ext; |
| 1999 | size_t i, path_len; |
| 2000 | |
| 2001 | path_len = strlen(path); |
| 2002 | |
| 2003 | for (i = 0; builtin_mime_types[i].extension != NULL; i++) { |
| 2004 | ext = path + (path_len - builtin_mime_types[i].ext_len); |
| 2005 | if (path_len > builtin_mime_types[i].ext_len && |
| 2006 | mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) { |
| 2007 | return builtin_mime_types[i].mime_type; |
| 2008 | } |
| 2009 | } |
| 2010 | |
| 2011 | return "text/plain"; |
| 2012 | } |
| 2013 | |
| 2014 | // Look at the "path" extension and figure what mime type it has. |
| 2015 | // Store mime type in the vector. |
| 2016 | static void get_mime_type(struct mg_context *ctx, const char *path, |
| 2017 | struct vec *vec) { |
| 2018 | struct vec ext_vec, mime_vec; |
| 2019 | const char *list, *ext; |
| 2020 | size_t path_len; |
| 2021 | |
| 2022 | path_len = strlen(path); |
| 2023 | |
| 2024 | // Scan user-defined mime types first, in case user wants to |
| 2025 | // override default mime types. |
| 2026 | list = ctx->config[EXTRA_MIME_TYPES]; |
| 2027 | while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) { |
| 2028 | // ext now points to the path suffix |
| 2029 | ext = path + path_len - ext_vec.len; |
| 2030 | if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) { |
| 2031 | *vec = mime_vec; |
| 2032 | return; |
| 2033 | } |
| 2034 | } |
| 2035 | |
| 2036 | vec->ptr = mg_get_builtin_mime_type(path); |
| 2037 | vec->len = strlen(vec->ptr); |
| 2038 | } |
| 2039 | |
| 2040 | static int is_big_endian(void) { |
| 2041 | static const int n = 1; |
| 2042 | return ((char *) &n)[0] == 0; |
| 2043 | } |
| 2044 | |
| 2045 | #ifndef HAVE_MD5 |
| 2046 | typedef struct MD5Context { |
| 2047 | uint32_t buf[4]; |
| 2048 | uint32_t bits[2]; |
| 2049 | unsigned char in[64]; |
| 2050 | } MD5_CTX; |
| 2051 | |
| 2052 | static void byteReverse(unsigned char *buf, unsigned longs) { |
| 2053 | uint32_t t; |
| 2054 | |
| 2055 | // Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN |
| 2056 | if (is_big_endian()) { |
| 2057 | do { |
| 2058 | t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 | |
| 2059 | ((unsigned) buf[1] << 8 | buf[0]); |
| 2060 | * (uint32_t *) buf = t; |
| 2061 | buf += 4; |
| 2062 | } while (--longs); |
| 2063 | } |
| 2064 | } |
| 2065 | |
| 2066 | #define F1(x, y, z) (z ^ (x & (y ^ z))) |
| 2067 | #define F2(x, y, z) F1(z, x, y) |
| 2068 | #define F3(x, y, z) (x ^ y ^ z) |
| 2069 | #define F4(x, y, z) (y ^ (x | ~z)) |
| 2070 | |
| 2071 | #define MD5STEP(f, w, x, y, z, data, s) \ |
| 2072 | ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x ) |
| 2073 | |
| 2074 | // Start MD5 accumulation. Set bit count to 0 and buffer to mysterious |
| 2075 | // initialization constants. |
| 2076 | static void MD5Init(MD5_CTX *ctx) { |
| 2077 | ctx->buf[0] = 0x67452301; |
| 2078 | ctx->buf[1] = 0xefcdab89; |
| 2079 | ctx->buf[2] = 0x98badcfe; |
| 2080 | ctx->buf[3] = 0x10325476; |
| 2081 | |
| 2082 | ctx->bits[0] = 0; |
| 2083 | ctx->bits[1] = 0; |
| 2084 | } |
| 2085 | |
| 2086 | static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) { |
| 2087 | register uint32_t a, b, c, d; |
| 2088 | |
| 2089 | a = buf[0]; |
| 2090 | b = buf[1]; |
| 2091 | c = buf[2]; |
| 2092 | d = buf[3]; |
| 2093 | |
| 2094 | MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); |
| 2095 | MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); |
| 2096 | MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); |
| 2097 | MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); |
| 2098 | MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); |
| 2099 | MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); |
| 2100 | MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); |
| 2101 | MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); |
| 2102 | MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); |
| 2103 | MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); |
| 2104 | MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); |
| 2105 | MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); |
| 2106 | MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); |
| 2107 | MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); |
| 2108 | MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); |
| 2109 | MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); |
| 2110 | |
| 2111 | MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); |
| 2112 | MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); |
| 2113 | MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); |
| 2114 | MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); |
| 2115 | MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); |
| 2116 | MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); |
| 2117 | MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); |
| 2118 | MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); |
| 2119 | MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); |
| 2120 | MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); |
| 2121 | MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); |
| 2122 | MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); |
| 2123 | MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); |
| 2124 | MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); |
| 2125 | MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); |
| 2126 | MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); |
| 2127 | |
| 2128 | MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); |
| 2129 | MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); |
| 2130 | MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); |
| 2131 | MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); |
| 2132 | MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); |
| 2133 | MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); |
| 2134 | MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); |
| 2135 | MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); |
| 2136 | MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); |
| 2137 | MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); |
| 2138 | MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); |
| 2139 | MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); |
| 2140 | MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); |
| 2141 | MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); |
| 2142 | MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); |
| 2143 | MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); |
| 2144 | |
| 2145 | MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); |
| 2146 | MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); |
| 2147 | MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); |
| 2148 | MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); |
| 2149 | MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); |
| 2150 | MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); |
| 2151 | MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); |
| 2152 | MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); |
| 2153 | MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); |
| 2154 | MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); |
| 2155 | MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); |
| 2156 | MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); |
| 2157 | MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); |
| 2158 | MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); |
| 2159 | MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); |
| 2160 | MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); |
| 2161 | |
| 2162 | buf[0] += a; |
| 2163 | buf[1] += b; |
| 2164 | buf[2] += c; |
| 2165 | buf[3] += d; |
| 2166 | } |
| 2167 | |
| 2168 | static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) { |
| 2169 | uint32_t t; |
| 2170 | |
| 2171 | t = ctx->bits[0]; |
| 2172 | if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) |
| 2173 | ctx->bits[1]++; |
| 2174 | ctx->bits[1] += len >> 29; |
| 2175 | |
| 2176 | t = (t >> 3) & 0x3f; |
| 2177 | |
| 2178 | if (t) { |
| 2179 | unsigned char *p = (unsigned char *) ctx->in + t; |
| 2180 | |
| 2181 | t = 64 - t; |
| 2182 | if (len < t) { |
| 2183 | memcpy(p, buf, len); |
| 2184 | return; |
| 2185 | } |
| 2186 | memcpy(p, buf, t); |
| 2187 | byteReverse(ctx->in, 16); |
| 2188 | MD5Transform(ctx->buf, (uint32_t *) ctx->in); |
| 2189 | buf += t; |
| 2190 | len -= t; |
| 2191 | } |
| 2192 | |
| 2193 | while (len >= 64) { |
| 2194 | memcpy(ctx->in, buf, 64); |
| 2195 | byteReverse(ctx->in, 16); |
| 2196 | MD5Transform(ctx->buf, (uint32_t *) ctx->in); |
| 2197 | buf += 64; |
| 2198 | len -= 64; |
| 2199 | } |
| 2200 | |
| 2201 | memcpy(ctx->in, buf, len); |
| 2202 | } |
| 2203 | |
| 2204 | static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) { |
| 2205 | unsigned count; |
| 2206 | unsigned char *p; |
| 2207 | uint32_t *a; |
| 2208 | |
| 2209 | count = (ctx->bits[0] >> 3) & 0x3F; |
| 2210 | |
| 2211 | p = ctx->in + count; |
| 2212 | *p++ = 0x80; |
| 2213 | count = 64 - 1 - count; |
| 2214 | if (count < 8) { |
| 2215 | memset(p, 0, count); |
| 2216 | byteReverse(ctx->in, 16); |
| 2217 | MD5Transform(ctx->buf, (uint32_t *) ctx->in); |
| 2218 | memset(ctx->in, 0, 56); |
| 2219 | } else { |
| 2220 | memset(p, 0, count - 8); |
| 2221 | } |
| 2222 | byteReverse(ctx->in, 14); |
| 2223 | |
| 2224 | a = (uint32_t *)ctx->in; |
| 2225 | a[14] = ctx->bits[0]; |
| 2226 | a[15] = ctx->bits[1]; |
| 2227 | |
| 2228 | MD5Transform(ctx->buf, (uint32_t *) ctx->in); |
| 2229 | byteReverse((unsigned char *) ctx->buf, 4); |
| 2230 | memcpy(digest, ctx->buf, 16); |
| 2231 | memset((char *) ctx, 0, sizeof(*ctx)); |
| 2232 | } |
| 2233 | #endif // !HAVE_MD5 |
| 2234 | |
| 2235 | // Stringify binary data. Output buffer must be twice as big as input, |
| 2236 | // because each byte takes 2 bytes in string representation |
| 2237 | static void bin2str(char *to, const unsigned char *p, size_t len) { |
| 2238 | static const char *hex = "0123456789abcdef"; |
| 2239 | |
| 2240 | for (; len--; p++) { |
| 2241 | *to++ = hex[p[0] >> 4]; |
| 2242 | *to++ = hex[p[0] & 0x0f]; |
| 2243 | } |
| 2244 | *to = '\0'; |
| 2245 | } |
| 2246 | |
| 2247 | // Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. |
| 2248 | char *mg_md5(char buf[33], ...) { |
| 2249 | unsigned char hash[16]; |
| 2250 | const char *p; |
| 2251 | va_list ap; |
| 2252 | MD5_CTX ctx; |
| 2253 | |
| 2254 | MD5Init(&ctx); |
| 2255 | |
| 2256 | va_start(ap, buf); |
| 2257 | while ((p = va_arg(ap, const char *)) != NULL) { |
| 2258 | MD5Update(&ctx, (const unsigned char *) p, (unsigned) strlen(p)); |
| 2259 | } |
| 2260 | va_end(ap); |
| 2261 | |
| 2262 | MD5Final(hash, &ctx); |
| 2263 | bin2str(buf, hash, sizeof(hash)); |
| 2264 | return buf; |
| 2265 | } |
| 2266 | |
| 2267 | // Check the user's password, return 1 if OK |
| 2268 | static int check_password(const char *method, const char *ha1, const char *uri, |
| 2269 | const char *nonce, const char *nc, const char *cnonce, |
| 2270 | const char *qop, const char *response) { |
| 2271 | char ha2[32 + 1], expected_response[32 + 1]; |
| 2272 | |
| 2273 | // Some of the parameters may be NULL |
| 2274 | if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL || |
| 2275 | qop == NULL || response == NULL) { |
| 2276 | return 0; |
| 2277 | } |
| 2278 | |
| 2279 | // NOTE(lsm): due to a bug in MSIE, we do not compare the URI |
| 2280 | // TODO(lsm): check for authentication timeout |
| 2281 | if (// strcmp(dig->uri, c->ouri) != 0 || |
| 2282 | strlen(response) != 32 |
| 2283 | // || now - strtoul(dig->nonce, NULL, 10) > 3600 |
| 2284 | ) { |
| 2285 | return 0; |
| 2286 | } |
| 2287 | |
| 2288 | mg_md5(ha2, method, ":", uri, NULL); |
| 2289 | mg_md5(expected_response, ha1, ":", nonce, ":", nc, |
| 2290 | ":", cnonce, ":", qop, ":", ha2, NULL); |
| 2291 | |
| 2292 | return mg_strcasecmp(response, expected_response) == 0; |
| 2293 | } |
| 2294 | |
| 2295 | // Use the global passwords file, if specified by auth_gpass option, |
| 2296 | // or search for .htpasswd in the requested directory. |
| 2297 | static void open_auth_file(struct mg_connection *conn, const char *path, |
| 2298 | struct file *filep) { |
| 2299 | char name[PATH_MAX]; |
| 2300 | const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE]; |
| 2301 | struct file file = STRUCT_FILE_INITIALIZER; |
| 2302 | |
| 2303 | if (gpass != NULL) { |
| 2304 | // Use global passwords file |
| 2305 | if (!mg_fopen(conn, gpass, "r", filep)) { |
| 2306 | cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO)); |
| 2307 | } |
| 2308 | // Important: using local struct file to test path for is_directory flag. |
| 2309 | // If filep is used, mg_stat() makes it appear as if auth file was opened. |
| 2310 | } else if (mg_stat(conn, path, &file) && file.is_directory) { |
| 2311 | mg_snprintf(conn, name, sizeof(name), "%s%c%s", |
| 2312 | path, '/', PASSWORDS_FILE_NAME); |
| 2313 | mg_fopen(conn, name, "r", filep); |
| 2314 | } else { |
| 2315 | // Try to find .htpasswd in requested directory. |
| 2316 | for (p = path, e = p + strlen(p) - 1; e > p; e--) |
| 2317 | if (e[0] == '/') |
| 2318 | break; |
| 2319 | mg_snprintf(conn, name, sizeof(name), "%.*s%c%s", |
| 2320 | (int) (e - p), p, '/', PASSWORDS_FILE_NAME); |
| 2321 | mg_fopen(conn, name, "r", filep); |
| 2322 | } |
| 2323 | } |
| 2324 | |
| 2325 | // Parsed Authorization header |
| 2326 | struct ah { |
| 2327 | char *user, *uri, *cnonce, *response, *qop, *nc, *nonce; |
| 2328 | }; |
| 2329 | |
| 2330 | // Return 1 on success. Always initializes the ah structure. |
| 2331 | static int parse_auth_header(struct mg_connection *conn, char *buf, |
| 2332 | size_t buf_size, struct ah *ah) { |
| 2333 | char *name, *value, *s; |
| 2334 | const char *auth_header; |
| 2335 | |
| 2336 | (void) memset(ah, 0, sizeof(*ah)); |
| 2337 | if ((auth_header = mg_get_header(conn, "Authorization")) == NULL || |
| 2338 | mg_strncasecmp(auth_header, "Digest ", 7) != 0) { |
| 2339 | return 0; |
| 2340 | } |
| 2341 | |
| 2342 | // Make modifiable copy of the auth header |
| 2343 | (void) mg_strlcpy(buf, auth_header + 7, buf_size); |
| 2344 | s = buf; |
| 2345 | |
| 2346 | // Parse authorization header |
| 2347 | for (;;) { |
| 2348 | // Gobble initial spaces |
| 2349 | while (isspace(* (unsigned char *) s)) { |
| 2350 | s++; |
| 2351 | } |
| 2352 | name = skip_quoted(&s, "=", " ", 0); |
| 2353 | // Value is either quote-delimited, or ends at first comma or space. |
| 2354 | if (s[0] == '\"') { |
| 2355 | s++; |
| 2356 | value = skip_quoted(&s, "\"", " ", '\\'); |
| 2357 | if (s[0] == ',') { |
| 2358 | s++; |
| 2359 | } |
| 2360 | } else { |
| 2361 | value = skip_quoted(&s, ", ", " ", 0); // IE uses commas, FF uses spaces |
| 2362 | } |
| 2363 | if (*name == '\0') { |
| 2364 | break; |
| 2365 | } |
| 2366 | |
| 2367 | if (!strcmp(name, "username")) { |
| 2368 | ah->user = value; |
| 2369 | } else if (!strcmp(name, "cnonce")) { |
| 2370 | ah->cnonce = value; |
| 2371 | } else if (!strcmp(name, "response")) { |
| 2372 | ah->response = value; |
| 2373 | } else if (!strcmp(name, "uri")) { |
| 2374 | ah->uri = value; |
| 2375 | } else if (!strcmp(name, "qop")) { |
| 2376 | ah->qop = value; |
| 2377 | } else if (!strcmp(name, "nc")) { |
| 2378 | ah->nc = value; |
| 2379 | } else if (!strcmp(name, "nonce")) { |
| 2380 | ah->nonce = value; |
| 2381 | } |
| 2382 | } |
| 2383 | |
| 2384 | // CGI needs it as REMOTE_USER |
| 2385 | if (ah->user != NULL) { |
| 2386 | conn->request_info.remote_user = mg_strdup(ah->user); |
| 2387 | } else { |
| 2388 | return 0; |
| 2389 | } |
| 2390 | |
| 2391 | return 1; |
| 2392 | } |
| 2393 | |
| 2394 | static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p) { |
| 2395 | char *eof; |
| 2396 | size_t len; |
| 2397 | |
| 2398 | if (filep->membuf != NULL && *p != NULL) { |
| 2399 | eof = (char*)memchr(*p, '\n', &filep->membuf[filep->size] - *p); |
| 2400 | len = (size_t) (eof - *p) > size - 1 ? size - 1 : (size_t) (eof - *p); |
| 2401 | memcpy(buf, *p, len); |
| 2402 | buf[len] = '\0'; |
| 2403 | *p = eof; |
| 2404 | return eof; |
| 2405 | } else if (filep->fp != NULL) { |
| 2406 | return fgets(buf, size, filep->fp); |
| 2407 | } else { |
| 2408 | return NULL; |
| 2409 | } |
| 2410 | } |
| 2411 | |
| 2412 | // Authorize against the opened passwords file. Return 1 if authorized. |
| 2413 | static int authorize(struct mg_connection *conn, struct file *filep) { |
| 2414 | struct ah ah; |
| 2415 | char line[256], f_user[256], ha1[256], f_domain[256], buf[MG_BUF_LEN], *p; |
| 2416 | |
| 2417 | if (!parse_auth_header(conn, buf, sizeof(buf), &ah)) { |
| 2418 | return 0; |
| 2419 | } |
| 2420 | |
| 2421 | // Loop over passwords file |
| 2422 | p = (char *) filep->membuf; |
| 2423 | while (mg_fgets(line, sizeof(line), filep, &p) != NULL) { |
| 2424 | if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) != 3) { |
| 2425 | continue; |
| 2426 | } |
| 2427 | |
| 2428 | if (!strcmp(ah.user, f_user) && |
| 2429 | !strcmp(conn->ctx->config[AUTHENTICATION_DOMAIN], f_domain)) |
| 2430 | return check_password(conn->request_info.request_method, ha1, ah.uri, |
| 2431 | ah.nonce, ah.nc, ah.cnonce, ah.qop, ah.response); |
| 2432 | } |
| 2433 | |
| 2434 | return 0; |
| 2435 | } |
| 2436 | |
| 2437 | // Return 1 if request is authorised, 0 otherwise. |
| 2438 | static int check_authorization(struct mg_connection *conn, const char *path) { |
| 2439 | char fname[PATH_MAX]; |
| 2440 | struct vec uri_vec, filename_vec; |
| 2441 | const char *list; |
| 2442 | struct file file = STRUCT_FILE_INITIALIZER; |
| 2443 | int authorized = 1; |
| 2444 | |
| 2445 | list = conn->ctx->config[PROTECT_URI]; |
| 2446 | while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) { |
| 2447 | if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) { |
| 2448 | mg_snprintf(conn, fname, sizeof(fname), "%.*s", |
| 2449 | (int) filename_vec.len, filename_vec.ptr); |
| 2450 | if (!mg_fopen(conn, fname, "r", &file)) { |
| 2451 | cry(conn, "%s: cannot open %s: %s", __func__, fname, strerror(errno)); |
| 2452 | } |
| 2453 | break; |
| 2454 | } |
| 2455 | } |
| 2456 | |
| 2457 | if (!is_file_opened(&file)) { |
| 2458 | open_auth_file(conn, path, &file); |
| 2459 | } |
| 2460 | |
| 2461 | if (is_file_opened(&file)) { |
| 2462 | authorized = authorize(conn, &file); |
| 2463 | mg_fclose(&file); |
| 2464 | } |
| 2465 | |
| 2466 | return authorized; |
| 2467 | } |
| 2468 | |
| 2469 | static void send_authorization_request(struct mg_connection *conn) { |
| 2470 | conn->status_code = 401; |
| 2471 | mg_printf(conn, |
| 2472 | "HTTP/1.1 401 Unauthorized\r\n" |
| 2473 | "Content-Length: 0\r\n" |
| 2474 | "WWW-Authenticate: Digest qop=\"auth\", " |
| 2475 | "realm=\"%s\", nonce=\"%lu\"\r\n\r\n", |
| 2476 | conn->ctx->config[AUTHENTICATION_DOMAIN], |
| 2477 | (unsigned long) time(NULL)); |
| 2478 | } |
| 2479 | |
| 2480 | static int is_authorized_for_put(struct mg_connection *conn) { |
| 2481 | struct file file = STRUCT_FILE_INITIALIZER; |
| 2482 | const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE]; |
| 2483 | int ret = 0; |
| 2484 | |
| 2485 | if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) { |
| 2486 | ret = authorize(conn, &file); |
| 2487 | mg_fclose(&file); |
| 2488 | } |
| 2489 | |
| 2490 | return ret; |
| 2491 | } |
| 2492 | |
| 2493 | int mg_modify_passwords_file(const char *fname, const char *domain, |
| 2494 | const char *user, const char *pass) { |
| 2495 | int found; |
| 2496 | char line[512], u[512], d[512], ha1[33], tmp[PATH_MAX]; |
| 2497 | FILE *fp, *fp2; |
| 2498 | |
| 2499 | found = 0; |
| 2500 | fp = fp2 = NULL; |
| 2501 | |
| 2502 | // Regard empty password as no password - remove user record. |
| 2503 | if (pass != NULL && pass[0] == '\0') { |
| 2504 | pass = NULL; |
| 2505 | } |
| 2506 | |
| 2507 | (void) snprintf(tmp, sizeof(tmp), "%s.tmp", fname); |
| 2508 | |
| 2509 | // Create the file if does not exist |
| 2510 | if ((fp = fopen(fname, "a+")) != NULL) { |
| 2511 | (void) fclose(fp); |
| 2512 | } |
| 2513 | |
| 2514 | // Open the given file and temporary file |
| 2515 | if ((fp = fopen(fname, "r")) == NULL) { |
| 2516 | return 0; |
| 2517 | } else if ((fp2 = fopen(tmp, "w+")) == NULL) { |
| 2518 | fclose(fp); |
| 2519 | return 0; |
| 2520 | } |
| 2521 | |
| 2522 | // Copy the stuff to temporary file |
| 2523 | while (fgets(line, sizeof(line), fp) != NULL) { |
| 2524 | if (sscanf(line, "%[^:]:%[^:]:%*s", u, d) != 2) { |
| 2525 | continue; |
| 2526 | } |
| 2527 | |
| 2528 | if (!strcmp(u, user) && !strcmp(d, domain)) { |
| 2529 | found++; |
| 2530 | if (pass != NULL) { |
| 2531 | mg_md5(ha1, user, ":", domain, ":", pass, NULL); |
| 2532 | fprintf(fp2, "%s:%s:%s\n", user, domain, ha1); |
| 2533 | } |
| 2534 | } else { |
| 2535 | fprintf(fp2, "%s", line); |
| 2536 | } |
| 2537 | } |
| 2538 | |
| 2539 | // If new user, just add it |
| 2540 | if (!found && pass != NULL) { |
| 2541 | mg_md5(ha1, user, ":", domain, ":", pass, NULL); |
| 2542 | fprintf(fp2, "%s:%s:%s\n", user, domain, ha1); |
| 2543 | } |
| 2544 | |
| 2545 | // Close files |
| 2546 | fclose(fp); |
| 2547 | fclose(fp2); |
| 2548 | |
| 2549 | // Put the temp file in place of real file |
| 2550 | remove(fname); |
| 2551 | rename(tmp, fname); |
| 2552 | |
| 2553 | return 1; |
| 2554 | } |
| 2555 | |
| 2556 | static int conn2(const char *host, int port, int use_ssl, |
| 2557 | char *ebuf, size_t ebuf_len) { |
| 2558 | struct sockaddr_in sin; |
| 2559 | struct hostent *he; |
| 2560 | SOCKET sock = INVALID_SOCKET; |
| 2561 | |
| 2562 | if (host == NULL) { |
| 2563 | snprintf(ebuf, ebuf_len, "%s", "NULL host"); |
| 2564 | } else if (use_ssl && SSLv23_client_method == NULL) { |
| 2565 | snprintf(ebuf, ebuf_len, "%s", "SSL is not initialized"); |
| 2566 | // TODO(lsm): use something threadsafe instead of gethostbyname() |
| 2567 | } else if ((he = gethostbyname(host)) == NULL) { |
| 2568 | snprintf(ebuf, ebuf_len, "gethostbyname(%s): %s", host, strerror(ERRNO)); |
| 2569 | } else if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) { |
| 2570 | snprintf(ebuf, ebuf_len, "socket(): %s", strerror(ERRNO)); |
| 2571 | } else { |
| 2572 | sin.sin_family = AF_INET; |
| 2573 | sin.sin_port = htons((uint16_t) port); |
| 2574 | sin.sin_addr = * (struct in_addr *) he->h_addr_list[0]; |
| 2575 | if (connect(sock, (struct sockaddr *) &sin, sizeof(sin)) != 0) { |
| 2576 | snprintf(ebuf, ebuf_len, "connect(%s:%d): %s", |
| 2577 | host, port, strerror(ERRNO)); |
| 2578 | closesocket(sock); |
| 2579 | sock = INVALID_SOCKET; |
| 2580 | } |
| 2581 | } |
| 2582 | return sock; |
| 2583 | } |
| 2584 | |
| 2585 | |
| 2586 | |
| 2587 | void mg_url_encode(const char *src, char *dst, size_t dst_len) { |
| 2588 | static const char *dont_escape = "._-$,;~()"; |
| 2589 | static const char *hex = "0123456789abcdef"; |
| 2590 | const char *end = dst + dst_len - 1; |
| 2591 | |
| 2592 | for (; *src != '\0' && dst < end; src++, dst++) { |
| 2593 | if (isalnum(*(const unsigned char *) src) || |
| 2594 | strchr(dont_escape, * (const unsigned char *) src) != NULL) { |
| 2595 | *dst = *src; |
| 2596 | } else if (dst + 2 < end) { |
| 2597 | dst[0] = '%'; |
| 2598 | dst[1] = hex[(* (const unsigned char *) src) >> 4]; |
| 2599 | dst[2] = hex[(* (const unsigned char *) src) & 0xf]; |
| 2600 | dst += 2; |
| 2601 | } |
| 2602 | } |
| 2603 | |
| 2604 | *dst = '\0'; |
| 2605 | } |
| 2606 | |
| 2607 | static void print_dir_entry(struct de *de) { |
| 2608 | char size[64], mod[64], href[PATH_MAX]; |
| 2609 | |
| 2610 | if (de->file.is_directory) { |
| 2611 | mg_snprintf(de->conn, size, sizeof(size), "%s", "[DIRECTORY]"); |
| 2612 | } else { |
| 2613 | // We use (signed) cast below because MSVC 6 compiler cannot |
| 2614 | // convert unsigned __int64 to double. Sigh. |
| 2615 | if (de->file.size < 1024) { |
| 2616 | mg_snprintf(de->conn, size, sizeof(size), "%d", (int) de->file.size); |
| 2617 | } else if (de->file.size < 0x100000) { |
| 2618 | mg_snprintf(de->conn, size, sizeof(size), |
| 2619 | "%.1fk", (double) de->file.size / 1024.0); |
| 2620 | } else if (de->file.size < 0x40000000) { |
| 2621 | mg_snprintf(de->conn, size, sizeof(size), |
| 2622 | "%.1fM", (double) de->file.size / 1048576); |
| 2623 | } else { |
| 2624 | mg_snprintf(de->conn, size, sizeof(size), |
| 2625 | "%.1fG", (double) de->file.size / 1073741824); |
| 2626 | } |
| 2627 | } |
| 2628 | strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", |
| 2629 | localtime(&de->file.modification_time)); |
| 2630 | mg_url_encode(de->file_name, href, sizeof(href)); |
| 2631 | de->conn->num_bytes_sent += mg_printf(de->conn, |
| 2632 | "<tr><td><a href=\"%s%s%s\">%s%s</a></td>" |
| 2633 | "<td> %s</td><td> %s</td></tr>\n", |
| 2634 | de->conn->request_info.uri, href, de->file.is_directory ? "/" : "", |
| 2635 | de->file_name, de->file.is_directory ? "/" : "", mod, size); |
| 2636 | } |
| 2637 | |
| 2638 | // This function is called from send_directory() and used for |
| 2639 | // sorting directory entries by size, or name, or modification time. |
| 2640 | // On windows, __cdecl specification is needed in case if project is built |
| 2641 | // with __stdcall convention. qsort always requires __cdels callback. |
| 2642 | static int WINCDECL compare_dir_entries(const void *p1, const void *p2) { |
| 2643 | const struct de *a = (const struct de *) p1, *b = (const struct de *) p2; |
| 2644 | const char *query_string = a->conn->request_info.query_string; |
| 2645 | int cmp_result = 0; |
| 2646 | |
| 2647 | if (query_string == NULL) { |
| 2648 | query_string = "na"; |
| 2649 | } |
| 2650 | |
| 2651 | if (a->file.is_directory && !b->file.is_directory) { |
| 2652 | return -1; // Always put directories on top |
| 2653 | } else if (!a->file.is_directory && b->file.is_directory) { |
| 2654 | return 1; // Always put directories on top |
| 2655 | } else if (*query_string == 'n') { |
| 2656 | cmp_result = strcmp(a->file_name, b->file_name); |
| 2657 | } else if (*query_string == 's') { |
| 2658 | cmp_result = a->file.size == b->file.size ? 0 : |
| 2659 | a->file.size > b->file.size ? 1 : -1; |
| 2660 | } else if (*query_string == 'd') { |
| 2661 | cmp_result = a->file.modification_time == b->file.modification_time ? 0 : |
| 2662 | a->file.modification_time > b->file.modification_time ? 1 : -1; |
| 2663 | } |
| 2664 | |
| 2665 | return query_string[1] == 'd' ? -cmp_result : cmp_result; |
| 2666 | } |
| 2667 | |
| 2668 | static int must_hide_file(struct mg_connection *conn, const char *path) { |
| 2669 | const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$"; |
| 2670 | const char *pattern = conn->ctx->config[HIDE_FILES]; |
| 2671 | return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 || |
| 2672 | (pattern != NULL && match_prefix(pattern, strlen(pattern), path) > 0); |
| 2673 | } |
| 2674 | |
| 2675 | static int scan_directory(struct mg_connection *conn, const char *dir, |
| 2676 | void *data, void (*cb)(struct de *, void *)) { |
| 2677 | char path[PATH_MAX]; |
| 2678 | struct dirent *dp; |
| 2679 | DIR *dirp; |
| 2680 | struct de de; |
| 2681 | |
| 2682 | if ((dirp = opendir(dir)) == NULL) { |
| 2683 | return 0; |
| 2684 | } else { |
| 2685 | de.conn = conn; |
| 2686 | |
| 2687 | while ((dp = readdir(dirp)) != NULL) { |
| 2688 | // Do not show current dir and hidden files |
| 2689 | if (!strcmp(dp->d_name, ".") || |
| 2690 | !strcmp(dp->d_name, "..") || |
| 2691 | must_hide_file(conn, dp->d_name)) { |
| 2692 | continue; |
| 2693 | } |
| 2694 | |
| 2695 | mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name); |
| 2696 | |
| 2697 | // If we don't memset stat structure to zero, mtime will have |
| 2698 | // garbage and strftime() will segfault later on in |
| 2699 | // print_dir_entry(). memset is required only if mg_stat() |
| 2700 | // fails. For more details, see |
| 2701 | // http://code.google.com/p/mongoose/issues/detail?id=79 |
| 2702 | memset(&de.file, 0, sizeof(de.file)); |
| 2703 | mg_stat(conn, path, &de.file); |
| 2704 | |
| 2705 | de.file_name = dp->d_name; |
| 2706 | cb(&de, data); |
| 2707 | } |
| 2708 | (void) closedir(dirp); |
| 2709 | } |
| 2710 | return 1; |
| 2711 | } |
| 2712 | |
| 2713 | static int remove_directory(struct mg_connection *conn, const char *dir) { |
| 2714 | char path[PATH_MAX]; |
| 2715 | struct dirent *dp; |
| 2716 | DIR *dirp; |
| 2717 | struct de de; |
| 2718 | |
| 2719 | if ((dirp = opendir(dir)) == NULL) { |
| 2720 | return 0; |
| 2721 | } else { |
| 2722 | de.conn = conn; |
| 2723 | |
| 2724 | while ((dp = readdir(dirp)) != NULL) { |
| 2725 | // Do not show current dir (but show hidden files as they will also be removed) |
| 2726 | if (!strcmp(dp->d_name, ".") || |
| 2727 | !strcmp(dp->d_name, "..")) { |
| 2728 | continue; |
| 2729 | } |
| 2730 | |
| 2731 | mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name); |
| 2732 | |
| 2733 | // If we don't memset stat structure to zero, mtime will have |
| 2734 | // garbage and strftime() will segfault later on in |
| 2735 | // print_dir_entry(). memset is required only if mg_stat() |
| 2736 | // fails. For more details, see |
| 2737 | // http://code.google.com/p/mongoose/issues/detail?id=79 |
| 2738 | memset(&de.file, 0, sizeof(de.file)); |
| 2739 | mg_stat(conn, path, &de.file); |
| 2740 | if(de.file.modification_time) { |
| 2741 | if(de.file.is_directory) { |
| 2742 | remove_directory(conn, path); |
| 2743 | } else { |
| 2744 | mg_remove(path); |
| 2745 | } |
| 2746 | } |
| 2747 | |
| 2748 | } |
| 2749 | (void) closedir(dirp); |
| 2750 | |
| 2751 | rmdir(dir); |
| 2752 | } |
| 2753 | |
| 2754 | return 1; |
| 2755 | } |
| 2756 | |
| 2757 | struct dir_scan_data { |
| 2758 | struct de *entries; |
| 2759 | int num_entries; |
| 2760 | int arr_size; |
| 2761 | }; |
| 2762 | |
| 2763 | // Behaves like realloc(), but frees original pointer on failure |
| 2764 | static void *realloc2(void *ptr, size_t size) { |
| 2765 | void *new_ptr = realloc(ptr, size); |
| 2766 | if (new_ptr == NULL) { |
| 2767 | free(ptr); |
| 2768 | } |
| 2769 | return new_ptr; |
| 2770 | } |
| 2771 | |
| 2772 | static void dir_scan_callback(struct de *de, void *data) { |
| 2773 | struct dir_scan_data *dsd = (struct dir_scan_data *) data; |
| 2774 | |
| 2775 | if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) { |
| 2776 | dsd->arr_size *= 2; |
| 2777 | dsd->entries = (struct de *) realloc2(dsd->entries, dsd->arr_size * |
| 2778 | sizeof(dsd->entries[0])); |
| 2779 | } |
| 2780 | if (dsd->entries == NULL) { |
| 2781 | // TODO(lsm): propagate an error to the caller |
| 2782 | dsd->num_entries = 0; |
| 2783 | } else { |
| 2784 | dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name); |
| 2785 | dsd->entries[dsd->num_entries].file = de->file; |
| 2786 | dsd->entries[dsd->num_entries].conn = de->conn; |
| 2787 | dsd->num_entries++; |
| 2788 | } |
| 2789 | } |
| 2790 | |
| 2791 | static void handle_directory_request(struct mg_connection *conn, |
| 2792 | const char *dir) { |
| 2793 | int i, sort_direction; |
| 2794 | struct dir_scan_data data = { NULL, 0, 128 }; |
| 2795 | |
| 2796 | if (!scan_directory(conn, dir, &data, dir_scan_callback)) { |
| 2797 | send_http_error(conn, 500, "Cannot open directory", |
| 2798 | "Error: opendir(%s): %s", dir, strerror(ERRNO)); |
| 2799 | return; |
| 2800 | } |
| 2801 | |
| 2802 | sort_direction = conn->request_info.query_string != NULL && |
| 2803 | conn->request_info.query_string[1] == 'd' ? 'a' : 'd'; |
| 2804 | |
| 2805 | conn->must_close = 1; |
| 2806 | mg_printf(conn, "%s", |
| 2807 | "HTTP/1.1 200 OK\r\n" |
| 2808 | "Connection: close\r\n" |
| 2809 | "Content-Type: text/html; charset=utf-8\r\n\r\n"); |
| 2810 | |
| 2811 | conn->num_bytes_sent += mg_printf(conn, |
| 2812 | "<html><head><title>Index of %s</title>" |
| 2813 | "<style>th {text-align: left;}</style></head>" |
| 2814 | "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">" |
| 2815 | "<tr><th><a href=\"?n%c\">Name</a></th>" |
| 2816 | "<th><a href=\"?d%c\">Modified</a></th>" |
| 2817 | "<th><a href=\"?s%c\">Size</a></th></tr>" |
| 2818 | "<tr><td colspan=\"3\"><hr></td></tr>", |
| 2819 | conn->request_info.uri, conn->request_info.uri, |
| 2820 | sort_direction, sort_direction, sort_direction); |
| 2821 | |
| 2822 | // Print first entry - link to a parent directory |
| 2823 | conn->num_bytes_sent += mg_printf(conn, |
| 2824 | "<tr><td><a href=\"%s%s\">%s</a></td>" |
| 2825 | "<td> %s</td><td> %s</td></tr>\n", |
| 2826 | conn->request_info.uri, "..", "Parent directory", "-", "-"); |
| 2827 | |
| 2828 | // Sort and print directory entries |
| 2829 | qsort(data.entries, (size_t) data.num_entries, sizeof(data.entries[0]), |
| 2830 | compare_dir_entries); |
| 2831 | for (i = 0; i < data.num_entries; i++) { |
| 2832 | print_dir_entry(&data.entries[i]); |
| 2833 | free(data.entries[i].file_name); |
| 2834 | } |
| 2835 | free(data.entries); |
| 2836 | |
| 2837 | conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>"); |
| 2838 | conn->status_code = 200; |
| 2839 | } |
| 2840 | |
| 2841 | // Send len bytes from the opened file to the client. |
| 2842 | static void send_file_data(struct mg_connection *conn, struct file *filep, |
| 2843 | int64_t offset, int64_t len) { |
| 2844 | char buf[MG_BUF_LEN]; |
| 2845 | int to_read, num_read, num_written; |
| 2846 | |
| 2847 | // Sanity check the offset |
| 2848 | offset = offset < 0 ? 0 : offset > filep->size ? filep->size : offset; |
| 2849 | |
| 2850 | if (len > 0 && filep->membuf != NULL && filep->size > 0) { |
| 2851 | if (len > filep->size - offset) { |
| 2852 | len = filep->size - offset; |
| 2853 | } |
| 2854 | mg_write(conn, filep->membuf + offset, (size_t) len); |
| 2855 | } else if (len > 0 && filep->fp != NULL) { |
| 2856 | fseeko(filep->fp, offset, SEEK_SET); |
| 2857 | while (len > 0) { |
| 2858 | // Calculate how much to read from the file in the buffer |
| 2859 | to_read = sizeof(buf); |
| 2860 | if ((int64_t) to_read > len) { |
| 2861 | to_read = (int) len; |
| 2862 | } |
| 2863 | |
| 2864 | // Read from file, exit the loop on error |
| 2865 | if ((num_read = fread(buf, 1, (size_t) to_read, filep->fp)) <= 0) { |
| 2866 | break; |
| 2867 | } |
| 2868 | |
| 2869 | // Send read bytes to the client, exit the loop on error |
| 2870 | if ((num_written = mg_write(conn, buf, (size_t) num_read)) != num_read) { |
| 2871 | break; |
| 2872 | } |
| 2873 | |
| 2874 | // Both read and were successful, adjust counters |
| 2875 | conn->num_bytes_sent += num_written; |
| 2876 | len -= num_written; |
| 2877 | } |
| 2878 | } |
| 2879 | } |
| 2880 | |
| 2881 | static int parse_range_header(const char *header, int64_t *a, int64_t *b) { |
| 2882 | return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b); |
| 2883 | } |
| 2884 | |
| 2885 | static void gmt_time_string(char *buf, size_t buf_len, time_t *t) { |
| 2886 | strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t)); |
| 2887 | } |
| 2888 | |
| 2889 | static void construct_etag(char *buf, size_t buf_len, |
| 2890 | const struct file *filep) { |
| 2891 | snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", |
| 2892 | (unsigned long) filep->modification_time, filep->size); |
| 2893 | } |
| 2894 | |
| 2895 | static void fclose_on_exec(struct file *filep) { |
| 2896 | if (filep != NULL && filep->fp != NULL) { |
| 2897 | #ifndef _WIN32 |
| 2898 | fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC); |
| 2899 | #endif |
| 2900 | } |
| 2901 | } |
| 2902 | |
| 2903 | static void handle_file_request(struct mg_connection *conn, const char *path, |
| 2904 | struct file *filep) { |
| 2905 | char date[64], lm[64], etag[64], range[64]; |
| 2906 | const char *msg = "OK", *hdr; |
| 2907 | time_t curtime = time(NULL); |
| 2908 | int64_t cl, r1, r2; |
| 2909 | struct vec mime_vec; |
| 2910 | int n; |
| 2911 | char gz_path[PATH_MAX]; |
| 2912 | char const* encoding = ""; |
| 2913 | |
| 2914 | get_mime_type(conn->ctx, path, &mime_vec); |
| 2915 | cl = filep->size; |
| 2916 | conn->status_code = 200; |
| 2917 | range[0] = '\0'; |
| 2918 | |
| 2919 | // if this file is in fact a pre-gzipped file, rewrite its filename |
| 2920 | // it's important to rewrite the filename after resolving |
| 2921 | // the mime type from it, to preserve the actual file's type |
| 2922 | if (filep->gzipped) { |
| 2923 | snprintf(gz_path, sizeof(gz_path), "%s.gz", path); |
| 2924 | path = gz_path; |
| 2925 | encoding = "Content-Encoding: gzip\r\n"; |
| 2926 | } |
| 2927 | |
| 2928 | if (!mg_fopen(conn, path, "rb", filep)) { |
| 2929 | send_http_error(conn, 500, http_500_error, |
| 2930 | "fopen(%s): %s", path, strerror(ERRNO)); |
| 2931 | return; |
| 2932 | } |
| 2933 | |
| 2934 | fclose_on_exec(filep); |
| 2935 | |
| 2936 | // If Range: header specified, act accordingly |
| 2937 | r1 = r2 = 0; |
| 2938 | hdr = mg_get_header(conn, "Range"); |
| 2939 | if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && |
| 2940 | r1 >= 0 && r2 >= 0) { |
| 2941 | // actually, range requests don't play well with a pre-gzipped |
| 2942 | // file (since the range is specified in the uncmpressed space) |
| 2943 | if (filep->gzipped) { |
| 2944 | send_http_error(conn, 501, "Not Implemented", "range requests in gzipped files are not supported"); |
| 2945 | return; |
| 2946 | } |
| 2947 | conn->status_code = 206; |
| 2948 | cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1: cl - r1; |
| 2949 | mg_snprintf(conn, range, sizeof(range), |
| 2950 | "Content-Range: bytes " |
| 2951 | "%" INT64_FMT "-%" |
| 2952 | INT64_FMT "/%" INT64_FMT "\r\n", |
| 2953 | r1, r1 + cl - 1, filep->size); |
| 2954 | msg = "Partial Content"; |
| 2955 | } |
| 2956 | |
| 2957 | // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to |
| 2958 | // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 |
| 2959 | gmt_time_string(date, sizeof(date), &curtime); |
| 2960 | gmt_time_string(lm, sizeof(lm), &filep->modification_time); |
| 2961 | construct_etag(etag, sizeof(etag), filep); |
| 2962 | |
| 2963 | (void) mg_printf(conn, |
| 2964 | "HTTP/1.1 %d %s\r\n" |
| 2965 | "Date: %s\r\n" |
| 2966 | "Last-Modified: %s\r\n" |
| 2967 | "Etag: %s\r\n" |
| 2968 | "Content-Type: %.*s\r\n" |
| 2969 | "Content-Length: %" INT64_FMT "\r\n" |
| 2970 | "Connection: %s\r\n" |
| 2971 | "Accept-Ranges: bytes\r\n" |
| 2972 | "%s%s\r\n", |
| 2973 | conn->status_code, msg, date, lm, etag, (int) mime_vec.len, |
| 2974 | mime_vec.ptr, cl, suggest_connection_header(conn), range, encoding); |
| 2975 | |
| 2976 | if (strcmp(conn->request_info.request_method, "HEAD") != 0) { |
| 2977 | send_file_data(conn, filep, r1, cl); |
| 2978 | } |
| 2979 | mg_fclose(filep); |
| 2980 | } |
| 2981 | |
| 2982 | void mg_send_file(struct mg_connection *conn, const char *path) { |
| 2983 | struct file file = STRUCT_FILE_INITIALIZER; |
| 2984 | if (mg_stat(conn, path, &file)) { |
| 2985 | handle_file_request(conn, path, &file); |
| 2986 | } else { |
| 2987 | send_http_error(conn, 404, "Not Found", "%s", "File not found"); |
| 2988 | } |
| 2989 | } |
| 2990 | |
| 2991 | |
| 2992 | // Parse HTTP headers from the given buffer, advance buffer to the point |
| 2993 | // where parsing stopped. |
| 2994 | static void parse_http_headers(char **buf, struct mg_request_info *ri) { |
| 2995 | int i; |
| 2996 | |
| 2997 | for (i = 0; i < (int) ARRAY_SIZE(ri->http_headers); i++) { |
| 2998 | ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0); |
| 2999 | ri->http_headers[i].value = skip(buf, "\r\n"); |
| 3000 | if (ri->http_headers[i].name[0] == '\0') |
| 3001 | break; |
| 3002 | ri->num_headers = i + 1; |
| 3003 | } |
| 3004 | } |
| 3005 | |
| 3006 | static int is_valid_http_method(const char *method) { |
| 3007 | return !strcmp(method, "GET") || !strcmp(method, "POST") || |
| 3008 | !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") || |
| 3009 | !strcmp(method, "PUT") || !strcmp(method, "DELETE") || |
| 3010 | !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND") |
| 3011 | || !strcmp(method, "MKCOL") |
| 3012 | ; |
| 3013 | } |
| 3014 | |
| 3015 | // Parse HTTP request, fill in mg_request_info structure. |
| 3016 | // This function modifies the buffer by NUL-terminating |
| 3017 | // HTTP request components, header names and header values. |
| 3018 | static int parse_http_message(char *buf, int len, struct mg_request_info *ri) { |
| 3019 | int is_request, request_length = get_request_len(buf, len); |
| 3020 | if (request_length > 0) { |
| 3021 | // Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_port |
| 3022 | ri->remote_user = ri->request_method = ri->uri = ri->http_version = NULL; |
| 3023 | ri->num_headers = 0; |
| 3024 | |
| 3025 | buf[request_length - 1] = '\0'; |
| 3026 | |
| 3027 | // RFC says that all initial whitespaces should be ingored |
| 3028 | while (*buf != '\0' && isspace(* (unsigned char *) buf)) { |
| 3029 | buf++; |
| 3030 | } |
| 3031 | ri->request_method = skip(&buf, " "); |
| 3032 | ri->uri = skip(&buf, " "); |
| 3033 | ri->http_version = skip(&buf, "\r\n"); |
| 3034 | if (((is_request = is_valid_http_method(ri->request_method)) && |
| 3035 | memcmp(ri->http_version, "HTTP/", 5) != 0) || |
| 3036 | (!is_request && memcmp(ri->request_method, "HTTP/", 5)) != 0) { |
| 3037 | request_length = -1; |
| 3038 | } else { |
| 3039 | if (is_request) { |
| 3040 | ri->http_version += 5; |
| 3041 | } |
| 3042 | parse_http_headers(&buf, ri); |
| 3043 | } |
| 3044 | } |
| 3045 | return request_length; |
| 3046 | } |
| 3047 | |
| 3048 | // Keep reading the input (either opened file descriptor fd, or socket sock, |
| 3049 | // or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the |
| 3050 | // buffer (which marks the end of HTTP request). Buffer buf may already |
| 3051 | // have some data. The length of the data is stored in nread. |
| 3052 | // Upon every read operation, increase nread by the number of bytes read. |
| 3053 | static int read_request(FILE *fp, struct mg_connection *conn, |
| 3054 | char *buf, int bufsiz, int *nread) { |
| 3055 | int request_len, n = 0; |
| 3056 | |
| 3057 | request_len = get_request_len(buf, *nread); |
| 3058 | while (*nread < bufsiz && request_len == 0 && |
| 3059 | (n = pull(fp, conn, buf + *nread, bufsiz - *nread)) > 0) { |
| 3060 | *nread += n; |
| 3061 | assert(*nread <= bufsiz); |
| 3062 | request_len = get_request_len(buf, *nread); |
| 3063 | } |
| 3064 | |
| 3065 | return request_len <= 0 && n <= 0 ? -1 : request_len; |
| 3066 | } |
| 3067 | |
| 3068 | // For given directory path, substitute it to valid index file. |
| 3069 | // Return 0 if index file has been found, -1 if not found. |
| 3070 | // If the file is found, it's stats is returned in stp. |
| 3071 | static int substitute_index_file(struct mg_connection *conn, char *path, |
| 3072 | size_t path_len, struct file *filep) { |
| 3073 | const char *list = conn->ctx->config[INDEX_FILES]; |
| 3074 | struct file file = STRUCT_FILE_INITIALIZER; |
| 3075 | struct vec filename_vec; |
| 3076 | size_t n = strlen(path); |
| 3077 | int found = 0; |
| 3078 | |
| 3079 | // The 'path' given to us points to the directory. Remove all trailing |
| 3080 | // directory separator characters from the end of the path, and |
| 3081 | // then append single directory separator character. |
| 3082 | while (n > 0 && path[n - 1] == '/') { |
| 3083 | n--; |
| 3084 | } |
| 3085 | path[n] = '/'; |
| 3086 | |
| 3087 | // Traverse index files list. For each entry, append it to the given |
| 3088 | // path and see if the file exists. If it exists, break the loop |
| 3089 | while ((list = next_option(list, &filename_vec, NULL)) != NULL) { |
| 3090 | |
| 3091 | // Ignore too long entries that may overflow path buffer |
| 3092 | if (filename_vec.len > path_len - (n + 2)) |
| 3093 | continue; |
| 3094 | |
| 3095 | // Prepare full path to the index file |
| 3096 | mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1); |
| 3097 | |
| 3098 | // Does it exist? |
| 3099 | if (mg_stat(conn, path, &file)) { |
| 3100 | // Yes it does, break the loop |
| 3101 | *filep = file; |
| 3102 | found = 1; |
| 3103 | break; |
| 3104 | } |
| 3105 | } |
| 3106 | |
| 3107 | // If no index file exists, restore directory path |
| 3108 | if (!found) { |
| 3109 | path[n] = '\0'; |
| 3110 | } |
| 3111 | |
| 3112 | return found; |
| 3113 | } |
| 3114 | |
| 3115 | // Return True if we should reply 304 Not Modified. |
| 3116 | static int is_not_modified(const struct mg_connection *conn, |
| 3117 | const struct file *filep) { |
| 3118 | char etag[64]; |
| 3119 | const char *ims = mg_get_header(conn, "If-Modified-Since"); |
| 3120 | const char *inm = mg_get_header(conn, "If-None-Match"); |
| 3121 | construct_etag(etag, sizeof(etag), filep); |
| 3122 | return (inm != NULL && !mg_strcasecmp(etag, inm)) || |
| 3123 | (ims != NULL && filep->modification_time <= parse_date_string(ims)); |
| 3124 | } |
| 3125 | |
| 3126 | static int forward_body_data(struct mg_connection *conn, FILE *fp, |
| 3127 | SOCKET sock, SSL *ssl) { |
| 3128 | const char *expect, *body; |
| 3129 | char buf[MG_BUF_LEN]; |
| 3130 | int to_read, nread, buffered_len, success = 0; |
| 3131 | |
| 3132 | expect = mg_get_header(conn, "Expect"); |
| 3133 | assert(fp != NULL); |
| 3134 | |
| 3135 | if (conn->content_len == -1) { |
| 3136 | send_http_error(conn, 411, "Length Required", "%s", ""); |
| 3137 | } else if (expect != NULL && mg_strcasecmp(expect, "100-continue")) { |
| 3138 | send_http_error(conn, 417, "Expectation Failed", "%s", ""); |
| 3139 | } else { |
| 3140 | if (expect != NULL) { |
| 3141 | (void) mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n"); |
| 3142 | } |
| 3143 | |
| 3144 | body = conn->buf + conn->request_len + conn->consumed_content; |
| 3145 | buffered_len = &conn->buf[conn->data_len] - body; |
| 3146 | assert(buffered_len >= 0); |
| 3147 | assert(conn->consumed_content == 0); |
| 3148 | |
| 3149 | if (buffered_len > 0) { |
| 3150 | if ((int64_t) buffered_len > conn->content_len) { |
| 3151 | buffered_len = (int) conn->content_len; |
| 3152 | } |
| 3153 | push(fp, sock, ssl, body, (int64_t) buffered_len); |
| 3154 | conn->consumed_content += buffered_len; |
| 3155 | } |
| 3156 | |
| 3157 | nread = 0; |
| 3158 | while (conn->consumed_content < conn->content_len) { |
| 3159 | to_read = sizeof(buf); |
| 3160 | if ((int64_t) to_read > conn->content_len - conn->consumed_content) { |
| 3161 | to_read = (int) (conn->content_len - conn->consumed_content); |
| 3162 | } |
| 3163 | nread = pull(NULL, conn, buf, to_read); |
| 3164 | if (nread <= 0 || push(fp, sock, ssl, buf, nread) != nread) { |
| 3165 | break; |
| 3166 | } |
| 3167 | conn->consumed_content += nread; |
| 3168 | } |
| 3169 | |
| 3170 | if (conn->consumed_content == conn->content_len) { |
| 3171 | success = nread >= 0; |
| 3172 | } |
| 3173 | |
| 3174 | // Each error code path in this function must send an error |
| 3175 | if (!success) { |
| 3176 | send_http_error(conn, 577, http_500_error, "%s", ""); |
| 3177 | } |
| 3178 | } |
| 3179 | |
| 3180 | return success; |
| 3181 | } |
| 3182 | |
| 3183 | #if !defined(NO_CGI) |
| 3184 | // This structure helps to create an environment for the spawned CGI program. |
| 3185 | // Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings, |
| 3186 | // last element must be NULL. |
| 3187 | // However, on Windows there is a requirement that all these VARIABLE=VALUE\0 |
| 3188 | // strings must reside in a contiguous buffer. The end of the buffer is |
| 3189 | // marked by two '\0' characters. |
| 3190 | // We satisfy both worlds: we create an envp array (which is vars), all |
| 3191 | // entries are actually pointers inside buf. |
| 3192 | struct cgi_env_block { |
| 3193 | struct mg_connection *conn; |
| 3194 | char buf[CGI_ENVIRONMENT_SIZE]; // Environment buffer |
| 3195 | int len; // Space taken |
| 3196 | char *vars[MAX_CGI_ENVIR_VARS]; // char **envp |
| 3197 | int nvars; // Number of variables |
| 3198 | }; |
| 3199 | |
| 3200 | static char *addenv(struct cgi_env_block *block, |
| 3201 | PRINTF_FORMAT_STRING(const char *fmt), ...) |
| 3202 | PRINTF_ARGS(2, 3); |
| 3203 | |
| 3204 | // Append VARIABLE=VALUE\0 string to the buffer, and add a respective |
| 3205 | // pointer into the vars array. |
| 3206 | static char *addenv(struct cgi_env_block *block, const char *fmt, ...) { |
| 3207 | int n, space; |
| 3208 | char *added; |
| 3209 | va_list ap; |
| 3210 | |
| 3211 | // Calculate how much space is left in the buffer |
| 3212 | space = sizeof(block->buf) - block->len - 2; |
| 3213 | assert(space >= 0); |
| 3214 | |
| 3215 | // Make a pointer to the free space int the buffer |
| 3216 | added = block->buf + block->len; |
| 3217 | |
| 3218 | // Copy VARIABLE=VALUE\0 string into the free space |
| 3219 | va_start(ap, fmt); |
| 3220 | n = mg_vsnprintf(block->conn, added, (size_t) space, fmt, ap); |
| 3221 | va_end(ap); |
| 3222 | |
| 3223 | // Make sure we do not overflow buffer and the envp array |
| 3224 | if (n > 0 && n + 1 < space && |
| 3225 | block->nvars < (int) ARRAY_SIZE(block->vars) - 2) { |
| 3226 | // Append a pointer to the added string into the envp array |
| 3227 | block->vars[block->nvars++] = added; |
| 3228 | // Bump up used length counter. Include \0 terminator |
| 3229 | block->len += n + 1; |
| 3230 | } else { |
| 3231 | cry(block->conn, "%s: CGI env buffer truncated for [%s]", __func__, fmt); |
| 3232 | } |
| 3233 | |
| 3234 | return added; |
| 3235 | } |
| 3236 | |
| 3237 | static void prepare_cgi_environment(struct mg_connection *conn, |
| 3238 | const char *prog, |
| 3239 | struct cgi_env_block *blk) { |
| 3240 | const char *s, *slash; |
| 3241 | struct vec var_vec; |
| 3242 | char *p, src_addr[IP_ADDR_STR_LEN]; |
| 3243 | int i; |
| 3244 | |
| 3245 | blk->len = blk->nvars = 0; |
| 3246 | blk->conn = conn; |
| 3247 | sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa); |
| 3248 | |
| 3249 | addenv(blk, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]); |
| 3250 | addenv(blk, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]); |
| 3251 | addenv(blk, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]); |
| 3252 | |
| 3253 | // Prepare the environment block |
| 3254 | addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1"); |
| 3255 | addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1"); |
| 3256 | addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP |
| 3257 | |
| 3258 | // TODO(lsm): fix this for IPv6 case |
| 3259 | addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port)); |
| 3260 | |
| 3261 | addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method); |
| 3262 | addenv(blk, "REMOTE_ADDR=%s", src_addr); |
| 3263 | addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port); |
| 3264 | addenv(blk, "REQUEST_URI=%s", conn->request_info.uri); |
| 3265 | |
| 3266 | // SCRIPT_NAME |
| 3267 | assert(conn->request_info.uri[0] == '/'); |
| 3268 | slash = strrchr(conn->request_info.uri, '/'); |
| 3269 | if ((s = strrchr(prog, '/')) == NULL) |
| 3270 | s = prog; |
| 3271 | addenv(blk, "SCRIPT_NAME=%.*s%s", (int) (slash - conn->request_info.uri), |
| 3272 | conn->request_info.uri, s); |
| 3273 | |
| 3274 | addenv(blk, "SCRIPT_FILENAME=%s", prog); |
| 3275 | addenv(blk, "PATH_TRANSLATED=%s", prog); |
| 3276 | addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on"); |
| 3277 | |
| 3278 | if ((s = mg_get_header(conn, "Content-Type")) != NULL) |
| 3279 | addenv(blk, "CONTENT_TYPE=%s", s); |
| 3280 | |
| 3281 | if (conn->request_info.query_string != NULL) |
| 3282 | addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string); |
| 3283 | |
| 3284 | if ((s = mg_get_header(conn, "Content-Length")) != NULL) |
| 3285 | addenv(blk, "CONTENT_LENGTH=%s", s); |
| 3286 | |
| 3287 | if ((s = getenv("PATH")) != NULL) |
| 3288 | addenv(blk, "PATH=%s", s); |
| 3289 | |
| 3290 | if (conn->path_info != NULL) { |
| 3291 | addenv(blk, "PATH_INFO=%s", conn->path_info); |
| 3292 | } |
| 3293 | |
| 3294 | #if defined(_WIN32) |
| 3295 | if ((s = getenv("COMSPEC")) != NULL) { |
| 3296 | addenv(blk, "COMSPEC=%s", s); |
| 3297 | } |
| 3298 | if ((s = getenv("SYSTEMROOT")) != NULL) { |
| 3299 | addenv(blk, "SYSTEMROOT=%s", s); |
| 3300 | } |
| 3301 | if ((s = getenv("SystemDrive")) != NULL) { |
| 3302 | addenv(blk, "SystemDrive=%s", s); |
| 3303 | } |
| 3304 | if ((s = getenv("ProgramFiles")) != NULL) { |
| 3305 | addenv(blk, "ProgramFiles=%s", s); |
| 3306 | } |
| 3307 | if ((s = getenv("ProgramFiles(x86)")) != NULL) { |
| 3308 | addenv(blk, "ProgramFiles(x86)=%s", s); |
| 3309 | } |
| 3310 | #else |
| 3311 | if ((s = getenv("LD_LIBRARY_PATH")) != NULL) |
| 3312 | addenv(blk, "LD_LIBRARY_PATH=%s", s); |
| 3313 | #endif // _WIN32 |
| 3314 | |
| 3315 | if ((s = getenv("PERLLIB")) != NULL) |
| 3316 | addenv(blk, "PERLLIB=%s", s); |
| 3317 | |
| 3318 | if (conn->request_info.remote_user != NULL) { |
| 3319 | addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user); |
| 3320 | addenv(blk, "%s", "AUTH_TYPE=Digest"); |
| 3321 | } |
| 3322 | |
| 3323 | // Add all headers as HTTP_* variables |
| 3324 | for (i = 0; i < conn->request_info.num_headers; i++) { |
| 3325 | p = addenv(blk, "HTTP_%s=%s", |
| 3326 | conn->request_info.http_headers[i].name, |
| 3327 | conn->request_info.http_headers[i].value); |
| 3328 | |
| 3329 | // Convert variable name into uppercase, and change - to _ |
| 3330 | for (; *p != '=' && *p != '\0'; p++) { |
| 3331 | if (*p == '-') |
| 3332 | *p = '_'; |
| 3333 | *p = (char) toupper(* (unsigned char *) p); |
| 3334 | } |
| 3335 | } |
| 3336 | |
| 3337 | // Add user-specified variables |
| 3338 | s = conn->ctx->config[CGI_ENVIRONMENT]; |
| 3339 | while ((s = next_option(s, &var_vec, NULL)) != NULL) { |
| 3340 | addenv(blk, "%.*s", (int) var_vec.len, var_vec.ptr); |
| 3341 | } |
| 3342 | |
| 3343 | blk->vars[blk->nvars++] = NULL; |
| 3344 | blk->buf[blk->len++] = '\0'; |
| 3345 | |
| 3346 | assert(blk->nvars < (int) ARRAY_SIZE(blk->vars)); |
| 3347 | assert(blk->len > 0); |
| 3348 | assert(blk->len < (int) sizeof(blk->buf)); |
| 3349 | } |
| 3350 | |
| 3351 | static void handle_cgi_request(struct mg_connection *conn, const char *prog) { |
| 3352 | int headers_len, data_len, i, fd_stdin[2], fd_stdout[2]; |
| 3353 | const char *status, *status_text; |
| 3354 | char buf[16384], *pbuf, dir[PATH_MAX], *p; |
| 3355 | struct mg_request_info ri; |
| 3356 | struct cgi_env_block blk; |
| 3357 | FILE *in, *out; |
| 3358 | struct file fout = STRUCT_FILE_INITIALIZER; |
| 3359 | pid_t pid; |
| 3360 | ri.mg_request_info::num_headers = 0; |
| 3361 | |
| 3362 | prepare_cgi_environment(conn, prog, &blk); |
| 3363 | |
| 3364 | // CGI must be executed in its own directory. 'dir' must point to the |
| 3365 | // directory containing executable program, 'p' must point to the |
| 3366 | // executable program name relative to 'dir'. |
| 3367 | (void) mg_snprintf(conn, dir, sizeof(dir), "%s", prog); |
| 3368 | if ((p = strrchr(dir, '/')) != NULL) { |
| 3369 | *p++ = '\0'; |
| 3370 | } else { |
| 3371 | dir[0] = '.', dir[1] = '\0'; |
| 3372 | p = (char *) prog; |
| 3373 | } |
| 3374 | |
| 3375 | pid = (pid_t) -1; |
| 3376 | fd_stdin[0] = fd_stdin[1] = fd_stdout[0] = fd_stdout[1] = -1; |
| 3377 | in = out = NULL; |
| 3378 | |
| 3379 | if (pipe(fd_stdin) != 0 || pipe(fd_stdout) != 0) { |
| 3380 | send_http_error(conn, 500, http_500_error, |
| 3381 | "Cannot create CGI pipe: %s", strerror(ERRNO)); |
| 3382 | goto done; |
| 3383 | } |
| 3384 | |
| 3385 | pid = spawn_process(conn, p, blk.buf, blk.vars, fd_stdin[0], fd_stdout[1], |
| 3386 | dir); |
| 3387 | // spawn_process() must close those! |
| 3388 | // If we don't mark them as closed, close() attempt before |
| 3389 | // return from this function throws an exception on Windows. |
| 3390 | // Windows does not like when closed descriptor is closed again. |
| 3391 | fd_stdin[0] = fd_stdout[1] = -1; |
| 3392 | |
| 3393 | if (pid == (pid_t) -1) { |
| 3394 | send_http_error(conn, 500, http_500_error, |
| 3395 | "Cannot spawn CGI process [%s]: %s", prog, strerror(ERRNO)); |
| 3396 | goto done; |
| 3397 | } |
| 3398 | |
| 3399 | if ((in = fdopen(fd_stdin[1], "wb")) == NULL || |
| 3400 | (out = fdopen(fd_stdout[0], "rb")) == NULL) { |
| 3401 | send_http_error(conn, 500, http_500_error, |
| 3402 | "fopen: %s", strerror(ERRNO)); |
| 3403 | goto done; |
| 3404 | } |
| 3405 | |
| 3406 | setbuf(in, NULL); |
| 3407 | setbuf(out, NULL); |
| 3408 | fout.fp = out; |
| 3409 | |
| 3410 | // Send POST data to the CGI process if needed |
| 3411 | if (!strcmp(conn->request_info.request_method, "POST") && |
| 3412 | !forward_body_data(conn, in, INVALID_SOCKET, NULL)) { |
| 3413 | goto done; |
| 3414 | } |
| 3415 | |
| 3416 | // Close so child gets an EOF. |
| 3417 | fclose(in); |
| 3418 | in = NULL; |
| 3419 | fd_stdin[1] = -1; |
| 3420 | |
| 3421 | // Now read CGI reply into a buffer. We need to set correct |
| 3422 | // status code, thus we need to see all HTTP headers first. |
| 3423 | // Do not send anything back to client, until we buffer in all |
| 3424 | // HTTP headers. |
| 3425 | data_len = 0; |
| 3426 | headers_len = read_request(out, conn, buf, sizeof(buf), &data_len); |
| 3427 | if (headers_len <= 0) { |
| 3428 | send_http_error(conn, 500, http_500_error, |
| 3429 | "CGI program sent malformed or too big (>%u bytes) " |
| 3430 | "HTTP headers: [%.*s]", |
| 3431 | (unsigned) sizeof(buf), data_len, buf); |
| 3432 | goto done; |
| 3433 | } |
| 3434 | pbuf = buf; |
| 3435 | buf[headers_len - 1] = '\0'; |
| 3436 | parse_http_headers(&pbuf, &ri); |
| 3437 | |
| 3438 | // Make up and send the status line |
| 3439 | status_text = "OK"; |
| 3440 | if ((status = get_header(&ri, "Status")) != NULL) { |
| 3441 | conn->status_code = atoi(status); |
| 3442 | status_text = status; |
| 3443 | while (isdigit(* (unsigned char *) status_text) || *status_text == ' ') { |
| 3444 | status_text++; |
| 3445 | } |
| 3446 | } else if (get_header(&ri, "Location") != NULL) { |
| 3447 | conn->status_code = 302; |
| 3448 | } else { |
| 3449 | conn->status_code = 200; |
| 3450 | } |
| 3451 | if (get_header(&ri, "Connection") != NULL && |
| 3452 | !mg_strcasecmp(get_header(&ri, "Connection"), "keep-alive")) { |
| 3453 | conn->must_close = 1; |
| 3454 | } |
| 3455 | (void) mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, |
| 3456 | status_text); |
| 3457 | |
| 3458 | // Send headers |
| 3459 | for (i = 0; i < ri.num_headers; i++) { |
| 3460 | mg_printf(conn, "%s: %s\r\n", |
| 3461 | ri.http_headers[i].name, ri.http_headers[i].value); |
| 3462 | } |
| 3463 | mg_write(conn, "\r\n", 2); |
| 3464 | |
| 3465 | // Send chunk of data that may have been read after the headers |
| 3466 | conn->num_bytes_sent += mg_write(conn, buf + headers_len, |
| 3467 | (size_t)(data_len - headers_len)); |
| 3468 | |
| 3469 | // Read the rest of CGI output and send to the client |
| 3470 | send_file_data(conn, &fout, 0, INT64_MAX); |
| 3471 | |
| 3472 | done: |
| 3473 | if (pid != (pid_t) -1) { |
| 3474 | kill(pid, SIGKILL); |
| 3475 | } |
| 3476 | if (fd_stdin[0] != -1) { |
| 3477 | close(fd_stdin[0]); |
| 3478 | } |
| 3479 | if (fd_stdout[1] != -1) { |
| 3480 | close(fd_stdout[1]); |
| 3481 | } |
| 3482 | |
| 3483 | if (in != NULL) { |
| 3484 | fclose(in); |
| 3485 | } else if (fd_stdin[1] != -1) { |
| 3486 | close(fd_stdin[1]); |
| 3487 | } |
| 3488 | |
| 3489 | if (out != NULL) { |
| 3490 | fclose(out); |
| 3491 | } else if (fd_stdout[0] != -1) { |
| 3492 | close(fd_stdout[0]); |
| 3493 | } |
| 3494 | } |
| 3495 | #endif // !NO_CGI |
| 3496 | |
| 3497 | // For a given PUT path, create all intermediate subdirectories |
| 3498 | // for given path. Return 0 if the path itself is a directory, |
| 3499 | // or -1 on error, 1 if OK. |
| 3500 | static int put_dir(struct mg_connection *conn, const char *path) { |
| 3501 | char buf[PATH_MAX]; |
| 3502 | const char *s, *p; |
| 3503 | struct file file = STRUCT_FILE_INITIALIZER; |
| 3504 | int len, res = 1; |
| 3505 | |
| 3506 | for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) { |
| 3507 | len = p - path; |
| 3508 | if (len >= (int) sizeof(buf)) { |
| 3509 | res = -1; |
| 3510 | break; |
| 3511 | } |
| 3512 | memcpy(buf, path, len); |
| 3513 | buf[len] = '\0'; |
| 3514 | |
| 3515 | // Try to create intermediate directory |
| 3516 | DEBUG_TRACE(("mkdir(%s)", buf)); |
| 3517 | if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) { |
| 3518 | res = -1; |
| 3519 | break; |
| 3520 | } |
| 3521 | |
| 3522 | // Is path itself a directory? |
| 3523 | if (p[1] == '\0') { |
| 3524 | res = 0; |
| 3525 | } |
| 3526 | } |
| 3527 | |
| 3528 | return res; |
| 3529 | } |
| 3530 | |
| 3531 | static void mkcol(struct mg_connection *conn, const char *path) { |
| 3532 | int rc, body_len; |
| 3533 | struct de de; |
| 3534 | memset(&de.file, 0, sizeof(de.file)); |
| 3535 | mg_stat(conn, path, &de.file); |
| 3536 | |
| 3537 | if(de.file.modification_time) { |
| 3538 | send_http_error(conn, 405, "Method Not Allowed", |
| 3539 | "mkcol(%s): %s", path, strerror(ERRNO)); |
| 3540 | return; |
| 3541 | } |
| 3542 | |
| 3543 | body_len = conn->data_len - conn->request_len; |
| 3544 | if(body_len > 0) { |
| 3545 | send_http_error(conn, 415, "Unsupported media type", |
| 3546 | "mkcol(%s): %s", path, strerror(ERRNO)); |
| 3547 | return; |
| 3548 | } |
| 3549 | |
| 3550 | rc = mg_mkdir(path, 0755); |
| 3551 | |
| 3552 | if (rc == 0) { |
| 3553 | conn->status_code = 201; |
| 3554 | mg_printf(conn, "HTTP/1.1 %d Created\r\n\r\n", conn->status_code); |
| 3555 | } else if (rc == -1) { |
| 3556 | if(errno == EEXIST) |
| 3557 | send_http_error(conn, 405, "Method Not Allowed", |
| 3558 | "mkcol(%s): %s", path, strerror(ERRNO)); |
| 3559 | else if(errno == EACCES) |
| 3560 | send_http_error(conn, 403, "Forbidden", |
| 3561 | "mkcol(%s): %s", path, strerror(ERRNO)); |
| 3562 | else if(errno == ENOENT) |
| 3563 | send_http_error(conn, 409, "Conflict", |
| 3564 | "mkcol(%s): %s", path, strerror(ERRNO)); |
| 3565 | else |
| 3566 | send_http_error(conn, 500, http_500_error, |
| 3567 | "fopen(%s): %s", path, strerror(ERRNO)); |
| 3568 | } |
| 3569 | } |
| 3570 | |
| 3571 | static void put_file(struct mg_connection *conn, const char *path) { |
| 3572 | struct file file = STRUCT_FILE_INITIALIZER; |
| 3573 | const char *range; |
| 3574 | int64_t r1, r2; |
| 3575 | int rc; |
| 3576 | |
| 3577 | conn->status_code = mg_stat(conn, path, &file) ? 200 : 201; |
| 3578 | |
| 3579 | if ((rc = put_dir(conn, path)) == 0) { |
| 3580 | mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", conn->status_code); |
| 3581 | } else if (rc == -1) { |
| 3582 | send_http_error(conn, 500, http_500_error, |
| 3583 | "put_dir(%s): %s", path, strerror(ERRNO)); |
| 3584 | } else if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) { |
| 3585 | mg_fclose(&file); |
| 3586 | send_http_error(conn, 500, http_500_error, |
| 3587 | "fopen(%s): %s", path, strerror(ERRNO)); |
| 3588 | } else { |
| 3589 | fclose_on_exec(&file); |
| 3590 | range = mg_get_header(conn, "Content-Range"); |
| 3591 | r1 = r2 = 0; |
| 3592 | if (range != NULL && parse_range_header(range, &r1, &r2) > 0) { |
| 3593 | conn->status_code = 206; |
| 3594 | fseeko(file.fp, r1, SEEK_SET); |
| 3595 | } |
| 3596 | if (forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) { |
| 3597 | mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", conn->status_code); |
| 3598 | } |
| 3599 | mg_fclose(&file); |
| 3600 | } |
| 3601 | } |
| 3602 | |
| 3603 | static void send_ssi_file(struct mg_connection *, const char *, |
| 3604 | struct file *, int); |
| 3605 | |
| 3606 | static void do_ssi_include(struct mg_connection *conn, const char *ssi, |
| 3607 | char *tag, int include_level) { |
| 3608 | char file_name[MG_BUF_LEN], path[PATH_MAX], *p; |
| 3609 | struct file file = STRUCT_FILE_INITIALIZER; |
| 3610 | |
| 3611 | // sscanf() is safe here, since send_ssi_file() also uses buffer |
| 3612 | // of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN. |
| 3613 | if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) { |
| 3614 | // File name is relative to the webserver root |
| 3615 | (void) mg_snprintf(conn, path, sizeof(path), "%s%c%s", |
| 3616 | conn->ctx->config[DOCUMENT_ROOT], '/', file_name); |
| 3617 | } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1) { |
| 3618 | // File name is relative to the webserver working directory |
| 3619 | // or it is absolute system path |
| 3620 | (void) mg_snprintf(conn, path, sizeof(path), "%s", file_name); |
| 3621 | } else if (sscanf(tag, " \"%[^\"]\"", file_name) == 1) { |
| 3622 | // File name is relative to the currect document |
| 3623 | (void) mg_snprintf(conn, path, sizeof(path), "%s", ssi); |
| 3624 | if ((p = strrchr(path, '/')) != NULL) { |
| 3625 | p[1] = '\0'; |
| 3626 | } |
| 3627 | (void) mg_snprintf(conn, path + strlen(path), |
| 3628 | sizeof(path) - strlen(path), "%s", file_name); |
| 3629 | } else { |
| 3630 | cry(conn, "Bad SSI #include: [%s]", tag); |
| 3631 | return; |
| 3632 | } |
| 3633 | |
| 3634 | if (!mg_fopen(conn, path, "rb", &file)) { |
| 3635 | cry(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s", |
| 3636 | tag, path, strerror(ERRNO)); |
| 3637 | } else { |
| 3638 | fclose_on_exec(&file); |
| 3639 | if (match_prefix(conn->ctx->config[SSI_EXTENSIONS], |
| 3640 | strlen(conn->ctx->config[SSI_EXTENSIONS]), path) > 0) { |
| 3641 | send_ssi_file(conn, path, &file, include_level + 1); |
| 3642 | } else { |
| 3643 | send_file_data(conn, &file, 0, INT64_MAX); |
| 3644 | } |
| 3645 | mg_fclose(&file); |
| 3646 | } |
| 3647 | } |
| 3648 | |
| 3649 | #if !defined(NO_POPEN) |
| 3650 | static void do_ssi_exec(struct mg_connection *conn, char *tag) { |
| 3651 | char cmd[MG_BUF_LEN]; |
| 3652 | struct file file = STRUCT_FILE_INITIALIZER; |
| 3653 | |
| 3654 | if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) { |
| 3655 | cry(conn, "Bad SSI #exec: [%s]", tag); |
| 3656 | } else if ((file.fp = popen(cmd, "r")) == NULL) { |
| 3657 | cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO)); |
| 3658 | } else { |
| 3659 | send_file_data(conn, &file, 0, INT64_MAX); |
| 3660 | pclose(file.fp); |
| 3661 | } |
| 3662 | } |
| 3663 | #endif // !NO_POPEN |
| 3664 | |
| 3665 | static int mg_fgetc(struct file *filep, int offset) { |
| 3666 | if (filep->membuf != NULL && offset >=0 && offset < filep->size) { |
| 3667 | return ((unsigned char *) filep->membuf)[offset]; |
| 3668 | } else if (filep->fp != NULL) { |
| 3669 | return fgetc(filep->fp); |
| 3670 | } else { |
| 3671 | return EOF; |
| 3672 | } |
| 3673 | } |
| 3674 | |
| 3675 | static void send_ssi_file(struct mg_connection *conn, const char *path, |
| 3676 | struct file *filep, int include_level) { |
| 3677 | char buf[MG_BUF_LEN]; |
| 3678 | int ch, offset, len, in_ssi_tag; |
| 3679 | |
| 3680 | if (include_level > 10) { |
| 3681 | cry(conn, "SSI #include level is too deep (%s)", path); |
| 3682 | return; |
| 3683 | } |
| 3684 | |
| 3685 | in_ssi_tag = len = offset = 0; |
| 3686 | while ((ch = mg_fgetc(filep, offset)) != EOF) { |
| 3687 | if (in_ssi_tag && ch == '>') { |
| 3688 | in_ssi_tag = 0; |
| 3689 | buf[len++] = (char) ch; |
| 3690 | buf[len] = '\0'; |
| 3691 | assert(len <= (int) sizeof(buf)); |
| 3692 | if (len < 6 || memcmp(buf, "<!--#", 5) != 0) { |
| 3693 | // Not an SSI tag, pass it |
| 3694 | (void) mg_write(conn, buf, (size_t) len); |
| 3695 | } else { |
| 3696 | if (!memcmp(buf + 5, "include", 7)) { |
| 3697 | do_ssi_include(conn, path, buf + 12, include_level); |
| 3698 | #if !defined(NO_POPEN) |
| 3699 | } else if (!memcmp(buf + 5, "exec", 4)) { |
| 3700 | do_ssi_exec(conn, buf + 9); |
| 3701 | #endif // !NO_POPEN |
| 3702 | } else { |
| 3703 | cry(conn, "%s: unknown SSI " "command: \"%s\"", path, buf); |
| 3704 | } |
| 3705 | } |
| 3706 | len = 0; |
| 3707 | } else if (in_ssi_tag) { |
| 3708 | if (len == 5 && memcmp(buf, "<!--#", 5) != 0) { |
| 3709 | // Not an SSI tag |
| 3710 | in_ssi_tag = 0; |
| 3711 | } else if (len == (int) sizeof(buf) - 2) { |
| 3712 | cry(conn, "%s: SSI tag is too large", path); |
| 3713 | len = 0; |
| 3714 | } |
| 3715 | buf[len++] = ch & 0xff; |
| 3716 | } else if (ch == '<') { |
| 3717 | in_ssi_tag = 1; |
| 3718 | if (len > 0) { |
| 3719 | mg_write(conn, buf, (size_t) len); |
| 3720 | } |
| 3721 | len = 0; |
| 3722 | buf[len++] = ch & 0xff; |
| 3723 | } else { |
| 3724 | buf[len++] = ch & 0xff; |
| 3725 | if (len == (int) sizeof(buf)) { |
| 3726 | mg_write(conn, buf, (size_t) len); |
| 3727 | len = 0; |
| 3728 | } |
| 3729 | } |
| 3730 | } |
| 3731 | |
| 3732 | // Send the rest of buffered data |
| 3733 | if (len > 0) { |
| 3734 | mg_write(conn, buf, (size_t) len); |
| 3735 | } |
| 3736 | } |
| 3737 | |
| 3738 | static void handle_ssi_file_request(struct mg_connection *conn, |
| 3739 | const char *path) { |
| 3740 | struct file file = STRUCT_FILE_INITIALIZER; |
| 3741 | |
| 3742 | if (!mg_fopen(conn, path, "rb", &file)) { |
| 3743 | send_http_error(conn, 500, http_500_error, "fopen(%s): %s", path, |
| 3744 | strerror(ERRNO)); |
| 3745 | } else { |
| 3746 | conn->must_close = 1; |
| 3747 | fclose_on_exec(&file); |
| 3748 | mg_printf(conn, "HTTP/1.1 200 OK\r\n" |
| 3749 | "Content-Type: text/html\r\nConnection: %s\r\n\r\n", |
| 3750 | suggest_connection_header(conn)); |
| 3751 | send_ssi_file(conn, path, &file, 0); |
| 3752 | mg_fclose(&file); |
| 3753 | } |
| 3754 | } |
| 3755 | |
| 3756 | static void send_options(struct mg_connection *conn) { |
| 3757 | conn->status_code = 200; |
| 3758 | |
| 3759 | mg_printf(conn, "%s", "HTTP/1.1 200 OK\r\n" |
| 3760 | "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL\r\n" |
| 3761 | "DAV: 1\r\n\r\n"); |
| 3762 | } |
| 3763 | |
| 3764 | // Writes PROPFIND properties for a collection element |
| 3765 | static void print_props(struct mg_connection *conn, const char* uri, |
| 3766 | struct file *filep) { |
| 3767 | char mtime[64]; |
| 3768 | gmt_time_string(mtime, sizeof(mtime), &filep->modification_time); |
| 3769 | conn->num_bytes_sent += mg_printf(conn, |
| 3770 | "<d:response>" |
| 3771 | "<d:href>%s</d:href>" |
| 3772 | "<d:propstat>" |
| 3773 | "<d:prop>" |
| 3774 | "<d:resourcetype>%s</d:resourcetype>" |
| 3775 | "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>" |
| 3776 | "<d:getlastmodified>%s</d:getlastmodified>" |
| 3777 | "</d:prop>" |
| 3778 | "<d:status>HTTP/1.1 200 OK</d:status>" |
| 3779 | "</d:propstat>" |
| 3780 | "</d:response>\n", |
| 3781 | uri, |
| 3782 | filep->is_directory ? "<d:collection/>" : "", |
| 3783 | filep->size, |
| 3784 | mtime); |
| 3785 | } |
| 3786 | |
| 3787 | static void print_dav_dir_entry(struct de *de, void *data) { |
| 3788 | char href[PATH_MAX]; |
| 3789 | char href_encoded[PATH_MAX]; |
| 3790 | struct mg_connection *conn = (struct mg_connection *) data; |
| 3791 | mg_snprintf(conn, href, sizeof(href), "%s%s", |
| 3792 | conn->request_info.uri, de->file_name); |
| 3793 | mg_url_encode(href, href_encoded, PATH_MAX-1); |
| 3794 | print_props(conn, href_encoded, &de->file); |
| 3795 | } |
| 3796 | |
| 3797 | static void handle_propfind(struct mg_connection *conn, const char *path, |
| 3798 | struct file *filep) { |
| 3799 | const char *depth = mg_get_header(conn, "Depth"); |
| 3800 | |
| 3801 | conn->must_close = 1; |
| 3802 | conn->status_code = 207; |
| 3803 | mg_printf(conn, "HTTP/1.1 207 Multi-Status\r\n" |
| 3804 | "Connection: close\r\n" |
| 3805 | "Content-Type: text/xml; charset=utf-8\r\n\r\n"); |
| 3806 | |
| 3807 | conn->num_bytes_sent += mg_printf(conn, |
| 3808 | "<?xml version=\"1.0\" encoding=\"utf-8\"?>" |
| 3809 | "<d:multistatus xmlns:d='DAV:'>\n"); |
| 3810 | |
| 3811 | // Print properties for the requested resource itself |
| 3812 | print_props(conn, conn->request_info.uri, filep); |
| 3813 | |
| 3814 | // If it is a directory, print directory entries too if Depth is not 0 |
| 3815 | if (filep->is_directory && |
| 3816 | !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") && |
| 3817 | (depth == NULL || strcmp(depth, "0") != 0)) { |
| 3818 | scan_directory(conn, path, conn, &print_dav_dir_entry); |
| 3819 | } |
| 3820 | |
| 3821 | conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>"); |
| 3822 | } |
| 3823 | |
| 3824 | #if defined(USE_WEBSOCKET) |
| 3825 | |
| 3826 | // START OF SHA-1 code |
| 3827 | // Copyright(c) By Steve Reid <steve@edmweb.com> |
| 3828 | #define SHA1HANDSOFF |
| 3829 | #if defined(__sun) |
| 3830 | #include "solarisfixes.h" |
| 3831 | #endif |
| 3832 | |
| 3833 | union char64long16 { unsigned char c[64]; uint32_t l[16]; }; |
| 3834 | |
| 3835 | #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) |
| 3836 | |
| 3837 | static uint32_t blk0(union char64long16 *block, int i) { |
| 3838 | // Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN |
| 3839 | if (!is_big_endian()) { |
| 3840 | block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) | |
| 3841 | (rol(block->l[i], 8) & 0x00FF00FF); |
| 3842 | } |
| 3843 | return block->l[i]; |
| 3844 | } |
| 3845 | |
| 3846 | #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \ |
| 3847 | ^block->l[(i+2)&15]^block->l[i&15],1)) |
| 3848 | #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30); |
| 3849 | #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30); |
| 3850 | #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); |
| 3851 | #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30); |
| 3852 | #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); |
| 3853 | |
| 3854 | typedef struct { |
| 3855 | uint32_t state[5]; |
| 3856 | uint32_t count[2]; |
| 3857 | unsigned char buffer[64]; |
| 3858 | } SHA1_CTX; |
| 3859 | |
| 3860 | static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) { |
| 3861 | uint32_t a, b, c, d, e; |
| 3862 | union char64long16 block[1]; |
| 3863 | |
| 3864 | memcpy(block, buffer, 64); |
| 3865 | a = state[0]; |
| 3866 | b = state[1]; |
| 3867 | c = state[2]; |
| 3868 | d = state[3]; |
| 3869 | e = state[4]; |
| 3870 | R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3); |
| 3871 | R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7); |
| 3872 | R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11); |
| 3873 | R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15); |
| 3874 | R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19); |
| 3875 | R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23); |
| 3876 | R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27); |
| 3877 | R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31); |
| 3878 | R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35); |
| 3879 | R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39); |
| 3880 | R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43); |
| 3881 | R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47); |
| 3882 | R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51); |
| 3883 | R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55); |
| 3884 | R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59); |
| 3885 | R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63); |
| 3886 | R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67); |
| 3887 | R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71); |
| 3888 | R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75); |
| 3889 | R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79); |
| 3890 | state[0] += a; |
| 3891 | state[1] += b; |
| 3892 | state[2] += c; |
| 3893 | state[3] += d; |
| 3894 | state[4] += e; |
| 3895 | a = b = c = d = e = 0; |
| 3896 | memset(block, '\0', sizeof(block)); |
| 3897 | } |
| 3898 | |
| 3899 | static void SHA1Init(SHA1_CTX* context) { |
| 3900 | context->state[0] = 0x67452301; |
| 3901 | context->state[1] = 0xEFCDAB89; |
| 3902 | context->state[2] = 0x98BADCFE; |
| 3903 | context->state[3] = 0x10325476; |
| 3904 | context->state[4] = 0xC3D2E1F0; |
| 3905 | context->count[0] = context->count[1] = 0; |
| 3906 | } |
| 3907 | |
| 3908 | static void SHA1Update(SHA1_CTX* context, const unsigned char* data, |
| 3909 | uint32_t len) { |
| 3910 | uint32_t i, j; |
| 3911 | |
| 3912 | j = context->count[0]; |
| 3913 | if ((context->count[0] += len << 3) < j) |
| 3914 | context->count[1]++; |
| 3915 | context->count[1] += (len>>29); |
| 3916 | j = (j >> 3) & 63; |
| 3917 | if ((j + len) > 63) { |
| 3918 | memcpy(&context->buffer[j], data, (i = 64-j)); |
| 3919 | SHA1Transform(context->state, context->buffer); |
| 3920 | for ( ; i + 63 < len; i += 64) { |
| 3921 | SHA1Transform(context->state, &data[i]); |
| 3922 | } |
| 3923 | j = 0; |
| 3924 | } |
| 3925 | else i = 0; |
| 3926 | memcpy(&context->buffer[j], &data[i], len - i); |
| 3927 | } |
| 3928 | |
| 3929 | static void SHA1Final(unsigned char digest[20], SHA1_CTX* context) { |
| 3930 | unsigned i; |
| 3931 | unsigned char finalcount[8], c; |
| 3932 | |
| 3933 | for (i = 0; i < 8; i++) { |
| 3934 | finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)] |
| 3935 | >> ((3-(i & 3)) * 8) ) & 255); |
| 3936 | } |
| 3937 | c = 0200; |
| 3938 | SHA1Update(context, &c, 1); |
| 3939 | while ((context->count[0] & 504) != 448) { |
| 3940 | c = 0000; |
| 3941 | SHA1Update(context, &c, 1); |
| 3942 | } |
| 3943 | SHA1Update(context, finalcount, 8); |
| 3944 | for (i = 0; i < 20; i++) { |
| 3945 | digest[i] = (unsigned char) |
| 3946 | ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255); |
| 3947 | } |
| 3948 | memset(context, '\0', sizeof(*context)); |
| 3949 | memset(&finalcount, '\0', sizeof(finalcount)); |
| 3950 | } |
| 3951 | // END OF SHA1 CODE |
| 3952 | |
| 3953 | static void base64_encode(const unsigned char *src, int src_len, char *dst) { |
| 3954 | static const char *b64 = |
| 3955 | "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; |
| 3956 | int i, j, a, b, c; |
| 3957 | |
| 3958 | for (i = j = 0; i < src_len; i += 3) { |
| 3959 | a = src[i]; |
| 3960 | b = i + 1 >= src_len ? 0 : src[i + 1]; |
| 3961 | c = i + 2 >= src_len ? 0 : src[i + 2]; |
| 3962 | |
| 3963 | dst[j++] = b64[a >> 2]; |
| 3964 | dst[j++] = b64[((a & 3) << 4) | (b >> 4)]; |
| 3965 | if (i + 1 < src_len) { |
| 3966 | dst[j++] = b64[(b & 15) << 2 | (c >> 6)]; |
| 3967 | } |
| 3968 | if (i + 2 < src_len) { |
| 3969 | dst[j++] = b64[c & 63]; |
| 3970 | } |
| 3971 | } |
| 3972 | while (j % 4 != 0) { |
| 3973 | dst[j++] = '='; |
| 3974 | } |
| 3975 | dst[j++] = '\0'; |
| 3976 | } |
| 3977 | |
| 3978 | static void send_websocket_handshake(struct mg_connection *conn) { |
| 3979 | static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; |
| 3980 | char buf[100], sha[20], b64_sha[sizeof(sha) * 2]; |
| 3981 | SHA1_CTX sha_ctx; |
| 3982 | |
| 3983 | mg_snprintf(conn, buf, sizeof(buf), "%s%s", |
| 3984 | mg_get_header(conn, "Sec-WebSocket-Key"), magic); |
| 3985 | SHA1Init(&sha_ctx); |
| 3986 | SHA1Update(&sha_ctx, (unsigned char *) buf, strlen(buf)); |
| 3987 | SHA1Final((unsigned char *) sha, &sha_ctx); |
| 3988 | base64_encode((unsigned char *) sha, sizeof(sha), b64_sha); |
| 3989 | mg_printf(conn, "%s%s%s", |
| 3990 | "HTTP/1.1 101 Switching Protocols\r\n" |
| 3991 | "Upgrade: websocket\r\n" |
| 3992 | "Connection: Upgrade\r\n" |
| 3993 | "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n"); |
| 3994 | } |
| 3995 | |
| 3996 | static void read_websocket(struct mg_connection *conn) { |
| 3997 | // Pointer to the beginning of the portion of the incoming websocket message |
| 3998 | // queue. The original websocket upgrade request is never removed, |
| 3999 | // so the queue begins after it. |
| 4000 | unsigned char *buf = (unsigned char *) conn->buf + conn->request_len; |
| 4001 | int bits, n, stop = 0; |
| 4002 | size_t i, len, mask_len, data_len, header_len, body_len; |
| 4003 | // data points to the place where the message is stored when passed to the |
| 4004 | // websocket_data callback. This is either mem on the stack, |
| 4005 | // or a dynamically allocated buffer if it is too large. |
| 4006 | char mem[4 * 1024], mask[4], *data; |
| 4007 | |
| 4008 | assert(conn->content_len == 0); |
| 4009 | |
| 4010 | // Loop continuously, reading messages from the socket, invoking the callback, |
| 4011 | // and waiting repeatedly until an error occurs. |
| 4012 | while (!stop) { |
| 4013 | header_len = 0; |
| 4014 | // body_len is the length of the entire queue in bytes |
| 4015 | // len is the length of the current message |
| 4016 | // data_len is the length of the current message's data payload |
| 4017 | // header_len is the length of the current message's header |
| 4018 | if ((body_len = conn->data_len - conn->request_len) >= 2) { |
| 4019 | len = buf[1] & 127; |
| 4020 | mask_len = buf[1] & 128 ? 4 : 0; |
| 4021 | if (len < 126 && body_len >= mask_len) { |
| 4022 | data_len = len; |
| 4023 | header_len = 2 + mask_len; |
| 4024 | } else if (len == 126 && body_len >= 4 + mask_len) { |
| 4025 | header_len = 4 + mask_len; |
| 4026 | data_len = ((((int) buf[2]) << 8) + buf[3]); |
| 4027 | } else if (body_len >= 10 + mask_len) { |
| 4028 | header_len = 10 + mask_len; |
| 4029 | data_len = (((uint64_t) htonl(* (uint32_t *) &buf[2])) << 32) + |
| 4030 | htonl(* (uint32_t *) &buf[6]); |
| 4031 | } |
| 4032 | } |
| 4033 | |
| 4034 | // Data layout is as follows: |
| 4035 | // conn->buf buf |
| 4036 | // v v frame1 | frame2 |
| 4037 | // |---------------------|----------------|--------------|------- |
| 4038 | // | |<--header_len-->|<--data_len-->| |
| 4039 | // |<-conn->request_len->|<-----body_len----------->| |
| 4040 | // |<-------------------conn->data_len------------->| |
| 4041 | |
| 4042 | if (header_len > 0) { |
| 4043 | // Allocate space to hold websocket payload |
| 4044 | data = mem; |
| 4045 | if (data_len > sizeof(mem) && (data = malloc(data_len)) == NULL) { |
| 4046 | // Allocation failed, exit the loop and then close the connection |
| 4047 | // TODO: notify user about the failure |
| 4048 | break; |
| 4049 | } |
| 4050 | |
| 4051 | // Save mask and bits, otherwise it may be clobbered by memmove below |
| 4052 | bits = buf[0]; |
| 4053 | memcpy(mask, buf + header_len - mask_len, mask_len); |
| 4054 | |
| 4055 | // Read frame payload into the allocated buffer. |
| 4056 | assert(body_len >= header_len); |
| 4057 | if (data_len + header_len > body_len) { |
| 4058 | len = body_len - header_len; |
| 4059 | memcpy(data, buf + header_len, len); |
| 4060 | // TODO: handle pull error |
| 4061 | pull_all(NULL, conn, data + len, data_len - len); |
| 4062 | conn->data_len = conn->request_len; |
| 4063 | } else { |
| 4064 | len = data_len + header_len; |
| 4065 | memcpy(data, buf + header_len, data_len); |
| 4066 | memmove(buf, buf + len, body_len - len); |
| 4067 | conn->data_len -= len; |
| 4068 | } |
| 4069 | |
| 4070 | // Apply mask if necessary |
| 4071 | if (mask_len > 0) { |
| 4072 | for (i = 0; i < data_len; i++) { |
| 4073 | data[i] ^= mask[i % 4]; |
| 4074 | } |
| 4075 | } |
| 4076 | |
| 4077 | // Exit the loop if callback signalled to exit, |
| 4078 | // or "connection close" opcode received. |
| 4079 | if ((conn->ctx->callbacks.websocket_data != NULL && |
| 4080 | !conn->ctx->callbacks.websocket_data(conn, bits, data, data_len)) || |
| 4081 | (bits & 0xf) == 8) { // Opcode == 8, connection close |
| 4082 | stop = 1; |
| 4083 | } |
| 4084 | |
| 4085 | if (data != mem) { |
| 4086 | free(data); |
| 4087 | } |
| 4088 | // Not breaking the loop, process next websocket frame. |
| 4089 | } else { |
| 4090 | // Buffering websocket request |
| 4091 | if ((n = pull(NULL, conn, conn->buf + conn->data_len, |
| 4092 | conn->buf_size - conn->data_len)) <= 0) { |
| 4093 | break; |
| 4094 | } |
| 4095 | conn->data_len += n; |
| 4096 | } |
| 4097 | } |
| 4098 | } |
| 4099 | |
| 4100 | int mg_websocket_write(struct mg_connection* conn, int opcode, |
| 4101 | const char *data, size_t data_len) { |
| 4102 | unsigned char *copy; |
| 4103 | size_t copy_len = 0; |
| 4104 | int retval = -1; |
| 4105 | |
| 4106 | if ((copy = (unsigned char *) malloc(data_len + 10)) == NULL) { |
| 4107 | return -1; |
| 4108 | } |
| 4109 | |
| 4110 | copy[0] = 0x80 + (opcode & 0x0f); |
| 4111 | |
| 4112 | // Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 |
| 4113 | if (data_len < 126) { |
| 4114 | // Inline 7-bit length field |
| 4115 | copy[1] = data_len; |
| 4116 | memcpy(copy + 2, data, data_len); |
| 4117 | copy_len = 2 + data_len; |
| 4118 | } else if (data_len <= 0xFFFF) { |
| 4119 | // 16-bit length field |
| 4120 | copy[1] = 126; |
| 4121 | * (uint16_t *) (copy + 2) = htons(data_len); |
| 4122 | memcpy(copy + 4, data, data_len); |
| 4123 | copy_len = 4 + data_len; |
| 4124 | } else { |
| 4125 | // 64-bit length field |
| 4126 | copy[1] = 127; |
| 4127 | * (uint32_t *) (copy + 2) = htonl((uint64_t) data_len >> 32); |
| 4128 | * (uint32_t *) (copy + 6) = htonl(data_len & 0xffffffff); |
| 4129 | memcpy(copy + 10, data, data_len); |
| 4130 | copy_len = 10 + data_len; |
| 4131 | } |
| 4132 | |
| 4133 | // Not thread safe |
| 4134 | if (copy_len > 0) { |
| 4135 | retval = mg_write(conn, copy, copy_len); |
| 4136 | } |
| 4137 | free(copy); |
| 4138 | |
| 4139 | return retval; |
| 4140 | } |
| 4141 | |
| 4142 | static void handle_websocket_request(struct mg_connection *conn) { |
| 4143 | const char *version = mg_get_header(conn, "Sec-WebSocket-Version"); |
| 4144 | if (version == NULL || strcmp(version, "13") != 0) { |
| 4145 | send_http_error(conn, 426, "Upgrade Required", "%s", "Upgrade Required"); |
| 4146 | } else if (conn->ctx->callbacks.websocket_connect != NULL && |
| 4147 | conn->ctx->callbacks.websocket_connect(conn) != 0) { |
| 4148 | // Callback has returned non-zero, do not proceed with handshake |
| 4149 | } else { |
| 4150 | send_websocket_handshake(conn); |
| 4151 | if (conn->ctx->callbacks.websocket_ready != NULL) { |
| 4152 | conn->ctx->callbacks.websocket_ready(conn); |
| 4153 | } |
| 4154 | read_websocket(conn); |
| 4155 | } |
| 4156 | } |
| 4157 | |
| 4158 | static int is_websocket_request(const struct mg_connection *conn) { |
| 4159 | const char *host, *upgrade, *connection, *version, *key; |
| 4160 | |
| 4161 | host = mg_get_header(conn, "Host"); |
| 4162 | upgrade = mg_get_header(conn, "Upgrade"); |
| 4163 | connection = mg_get_header(conn, "Connection"); |
| 4164 | key = mg_get_header(conn, "Sec-WebSocket-Key"); |
| 4165 | version = mg_get_header(conn, "Sec-WebSocket-Version"); |
| 4166 | |
| 4167 | return host != NULL && upgrade != NULL && connection != NULL && |
| 4168 | key != NULL && version != NULL && |
| 4169 | mg_strcasestr(upgrade, "websocket") != NULL && |
| 4170 | mg_strcasestr(connection, "Upgrade") != NULL; |
| 4171 | } |
| 4172 | #endif // !USE_WEBSOCKET |
| 4173 | |
| 4174 | static int isbyte(int n) { |
| 4175 | return n >= 0 && n <= 255; |
| 4176 | } |
| 4177 | |
| 4178 | static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) { |
| 4179 | int n, a, b, c, d, slash = 32, len = 0; |
| 4180 | |
| 4181 | if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 || |
| 4182 | sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && |
| 4183 | isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && |
| 4184 | slash >= 0 && slash < 33) { |
| 4185 | len = n; |
| 4186 | *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d; |
| 4187 | *mask = slash ? 0xffffffffU << (32 - slash) : 0; |
| 4188 | } |
| 4189 | |
| 4190 | return len; |
| 4191 | } |
| 4192 | |
| 4193 | static int set_throttle(const char *spec, uint32_t remote_ip, const char *uri) { |
| 4194 | int throttle = 0; |
| 4195 | struct vec vec, val; |
| 4196 | uint32_t net, mask; |
| 4197 | char mult; |
| 4198 | double v; |
| 4199 | |
| 4200 | while ((spec = next_option(spec, &vec, &val)) != NULL) { |
| 4201 | mult = ','; |
| 4202 | if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0 || |
| 4203 | (lowercase(&mult) != 'k' && lowercase(&mult) != 'm' && mult != ',')) { |
| 4204 | continue; |
| 4205 | } |
| 4206 | v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576 : 1; |
| 4207 | if (vec.len == 1 && vec.ptr[0] == '*') { |
| 4208 | throttle = (int) v; |
| 4209 | } else if (parse_net(vec.ptr, &net, &mask) > 0) { |
| 4210 | if ((remote_ip & mask) == net) { |
| 4211 | throttle = (int) v; |
| 4212 | } |
| 4213 | } else if (match_prefix(vec.ptr, vec.len, uri) > 0) { |
| 4214 | throttle = (int) v; |
| 4215 | } |
| 4216 | } |
| 4217 | |
| 4218 | return throttle; |
| 4219 | } |
| 4220 | |
| 4221 | static uint32_t get_remote_ip(const struct mg_connection *conn) { |
| 4222 | return ntohl(* (uint32_t *) &conn->client.rsa.sin.sin_addr); |
| 4223 | } |
| 4224 | |
| 4225 | #ifdef USE_LUA |
| 4226 | #include "mod_lua.c" |
| 4227 | #endif // USE_LUA |
| 4228 | |
| 4229 | int mg_upload(struct mg_connection *conn, const char *destination_dir) { |
| 4230 | const char *content_type_header, *boundary_start; |
| 4231 | char buf[MG_BUF_LEN], path[PATH_MAX], fname[1024], boundary[100], *s; |
| 4232 | FILE *fp; |
| 4233 | int bl, n, i, j, headers_len, boundary_len, eof, |
| 4234 | len = 0, num_uploaded_files = 0; |
| 4235 | |
| 4236 | // Request looks like this: |
| 4237 | // |
| 4238 | // POST /upload HTTP/1.1 |
| 4239 | // Host: 127.0.0.1:8080 |
| 4240 | // Content-Length: 244894 |
| 4241 | // Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryRVr |
| 4242 | // |
| 4243 | // ------WebKitFormBoundaryRVr |
| 4244 | // Content-Disposition: form-data; name="file"; filename="accum.png" |
| 4245 | // Content-Type: image/png |
| 4246 | // |
| 4247 | // <89>PNG |
| 4248 | // <PNG DATA> |
| 4249 | // ------WebKitFormBoundaryRVr |
| 4250 | |
| 4251 | // Extract boundary string from the Content-Type header |
| 4252 | if ((content_type_header = mg_get_header(conn, "Content-Type")) == NULL || |
| 4253 | (boundary_start = mg_strcasestr(content_type_header, |
| 4254 | "boundary=")) == NULL || |
| 4255 | (sscanf(boundary_start, "boundary=\"%99[^\"]\"", boundary) == 0 && |
| 4256 | sscanf(boundary_start, "boundary=%99s", boundary) == 0) || |
| 4257 | boundary[0] == '\0') { |
| 4258 | return num_uploaded_files; |
| 4259 | } |
| 4260 | |
| 4261 | boundary_len = strlen(boundary); |
| 4262 | bl = boundary_len + 4; // \r\n--<boundary> |
| 4263 | for (;;) { |
| 4264 | // Pull in headers |
| 4265 | assert(len >= 0 && len <= (int) sizeof(buf)); |
| 4266 | while ((n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0) { |
| 4267 | len += n; |
| 4268 | } |
| 4269 | if ((headers_len = get_request_len(buf, len)) <= 0) { |
| 4270 | break; |
| 4271 | } |
| 4272 | |
| 4273 | // Fetch file name. |
| 4274 | fname[0] = '\0'; |
| 4275 | for (i = j = 0; i < headers_len; i++) { |
| 4276 | if (buf[i] == '\r' && buf[i + 1] == '\n') { |
| 4277 | buf[i] = buf[i + 1] = '\0'; |
| 4278 | // TODO(lsm): don't expect filename to be the 3rd field, |
| 4279 | // parse the header properly instead. |
| 4280 | sscanf(&buf[j], "Content-Disposition: %*s %*s filename=\"%1023[^\"]", |
| 4281 | fname); |
| 4282 | j = i + 2; |
| 4283 | } |
| 4284 | } |
| 4285 | |
| 4286 | // Give up if the headers are not what we expect |
| 4287 | if (fname[0] == '\0') { |
| 4288 | break; |
| 4289 | } |
| 4290 | |
| 4291 | // Move data to the beginning of the buffer |
| 4292 | assert(len >= headers_len); |
| 4293 | memmove(buf, &buf[headers_len], len - headers_len); |
| 4294 | len -= headers_len; |
| 4295 | |
| 4296 | // We open the file with exclusive lock held. This guarantee us |
| 4297 | // there is no other thread can save into the same file simultaneously. |
| 4298 | fp = NULL; |
| 4299 | // Construct destination file name. Do not allow paths to have slashes. |
| 4300 | if ((s = strrchr(fname, '/')) == NULL && |
| 4301 | (s = strrchr(fname, '\\')) == NULL) { |
| 4302 | s = fname; |
| 4303 | } |
| 4304 | |
| 4305 | // Open file in binary mode. TODO: set an exclusive lock. |
| 4306 | snprintf(path, sizeof(path), "%s/%s", destination_dir, s); |
| 4307 | if ((fp = fopen(path, "wb")) == NULL) { |
| 4308 | break; |
| 4309 | } |
| 4310 | |
| 4311 | // Read POST data, write into file until boundary is found. |
| 4312 | eof = n = 0; |
| 4313 | do { |
| 4314 | len += n; |
| 4315 | for (i = 0; i < len - bl; i++) { |
| 4316 | if (!memcmp(&buf[i], "\r\n--", 4) && |
| 4317 | !memcmp(&buf[i + 4], boundary, boundary_len)) { |
| 4318 | // Found boundary, that's the end of file data. |
| 4319 | fwrite(buf, 1, i, fp); |
| 4320 | eof = 1; |
| 4321 | memmove(buf, &buf[i + bl], len - (i + bl)); |
| 4322 | len -= i + bl; |
| 4323 | break; |
| 4324 | } |
| 4325 | } |
| 4326 | if (!eof && len > bl) { |
| 4327 | fwrite(buf, 1, len - bl, fp); |
| 4328 | memmove(buf, &buf[len - bl], bl); |
| 4329 | len = bl; |
| 4330 | } |
| 4331 | } while (!eof && (n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0); |
| 4332 | fclose(fp); |
| 4333 | if (eof) { |
| 4334 | num_uploaded_files++; |
| 4335 | if (conn->ctx->callbacks.upload != NULL) { |
| 4336 | conn->ctx->callbacks.upload(conn, path); |
| 4337 | } |
| 4338 | } |
| 4339 | } |
| 4340 | |
| 4341 | return num_uploaded_files; |
| 4342 | } |
| 4343 | |
| 4344 | static int is_put_or_delete_request(const struct mg_connection *conn) { |
| 4345 | const char *s = conn->request_info.request_method; |
| 4346 | return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE") || !strcmp(s, "MKCOL")); |
| 4347 | } |
| 4348 | |
| 4349 | static int get_first_ssl_listener_index(const struct mg_context *ctx) { |
| 4350 | int i, index = -1; |
| 4351 | for (i = 0; index == -1 && i < ctx->num_listening_sockets; i++) { |
| 4352 | index = ctx->listening_sockets[i].is_ssl ? i : -1; |
| 4353 | } |
| 4354 | return index; |
| 4355 | } |
| 4356 | |
| 4357 | static void redirect_to_https_port(struct mg_connection *conn, int ssl_index) { |
| 4358 | char host[1025]; |
| 4359 | const char *host_header; |
| 4360 | |
| 4361 | if ((host_header = mg_get_header(conn, "Host")) == NULL || |
| 4362 | sscanf(host_header, "%1024[^:]", host) == 0) { |
| 4363 | // Cannot get host from the Host: header. Fallback to our IP address. |
| 4364 | sockaddr_to_string(host, sizeof(host), &conn->client.lsa); |
| 4365 | } |
| 4366 | |
| 4367 | mg_printf(conn, "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s\r\n\r\n", |
| 4368 | host, (int) ntohs(conn->ctx->listening_sockets[ssl_index]. |
| 4369 | lsa.sin.sin_port), conn->request_info.uri); |
| 4370 | } |
| 4371 | |
| 4372 | // This is the heart of the Mongoose's logic. |
| 4373 | // This function is called when the request is read, parsed and validated, |
| 4374 | // and Mongoose must decide what action to take: serve a file, or |
| 4375 | // a directory, or call embedded function, etcetera. |
| 4376 | static void handle_request(struct mg_connection *conn) { |
| 4377 | struct mg_request_info *ri = &conn->request_info; |
| 4378 | char path[PATH_MAX]; |
| 4379 | int uri_len, ssl_index; |
| 4380 | struct file file = STRUCT_FILE_INITIALIZER; |
| 4381 | |
| 4382 | if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL) { |
| 4383 | * ((char *) conn->request_info.query_string++) = '\0'; |
| 4384 | } |
| 4385 | uri_len = (int) strlen(ri->uri); |
| 4386 | mg_url_decode(ri->uri, uri_len, (char *) ri->uri, uri_len + 1, 0); |
| 4387 | remove_double_dots_and_double_slashes((char *) ri->uri); |
| 4388 | convert_uri_to_file_name(conn, path, sizeof(path), &file); |
| 4389 | conn->throttle = set_throttle(conn->ctx->config[THROTTLE], |
| 4390 | get_remote_ip(conn), ri->uri); |
| 4391 | |
| 4392 | DEBUG_TRACE(("%s", ri->uri)); |
| 4393 | // Perform redirect and auth checks before calling begin_request() handler. |
| 4394 | // Otherwise, begin_request() would need to perform auth checks and redirects. |
| 4395 | if (!conn->client.is_ssl && conn->client.ssl_redir && |
| 4396 | (ssl_index = get_first_ssl_listener_index(conn->ctx)) > -1) { |
| 4397 | redirect_to_https_port(conn, ssl_index); |
| 4398 | } else if (!is_put_or_delete_request(conn) && |
| 4399 | !check_authorization(conn, path)) { |
| 4400 | send_authorization_request(conn); |
| 4401 | } else if (conn->ctx->callbacks.begin_request != NULL && |
| 4402 | conn->ctx->callbacks.begin_request(conn)) { |
| 4403 | // Do nothing, callback has served the request |
| 4404 | #if defined(USE_WEBSOCKET) |
| 4405 | } else if (is_websocket_request(conn)) { |
| 4406 | handle_websocket_request(conn); |
| 4407 | #endif |
| 4408 | } else if (!strcmp(ri->request_method, "OPTIONS")) { |
| 4409 | send_options(conn); |
| 4410 | } else if (conn->ctx->config[DOCUMENT_ROOT] == NULL) { |
| 4411 | send_http_error(conn, 404, "Not Found", "Not Found"); |
| 4412 | } else if (is_put_or_delete_request(conn) && |
| 4413 | (is_authorized_for_put(conn) != 1)) { |
| 4414 | send_authorization_request(conn); |
| 4415 | } else if (!strcmp(ri->request_method, "PUT")) { |
| 4416 | put_file(conn, path); |
| 4417 | } else if (!strcmp(ri->request_method, "MKCOL")) { |
| 4418 | mkcol(conn, path); |
| 4419 | } else if (!strcmp(ri->request_method, "DELETE")) { |
| 4420 | struct de de; |
| 4421 | memset(&de.file, 0, sizeof(de.file)); |
| 4422 | if(!mg_stat(conn, path, &de.file)) { |
| 4423 | send_http_error(conn, 404, "Not Found", "%s", "File not found"); |
| 4424 | } else { |
| 4425 | if(de.file.modification_time) { |
| 4426 | if(de.file.is_directory) { |
| 4427 | remove_directory(conn, path); |
| 4428 | send_http_error(conn, 204, "No Content", "%s", ""); |
| 4429 | } else if (mg_remove(path) == 0) { |
| 4430 | send_http_error(conn, 204, "No Content", "%s", ""); |
| 4431 | } else { |
| 4432 | send_http_error(conn, 423, "Locked", "remove(%s): %s", path, |
| 4433 | strerror(ERRNO)); |
| 4434 | } |
| 4435 | } |
| 4436 | else { |
| 4437 | send_http_error(conn, 500, http_500_error, "remove(%s): %s", path, |
| 4438 | strerror(ERRNO)); |
| 4439 | } |
| 4440 | } |
| 4441 | } else if ((file.membuf == NULL && file.modification_time == (time_t) 0) || |
| 4442 | must_hide_file(conn, path)) { |
| 4443 | send_http_error(conn, 404, "Not Found", "%s", "File not found"); |
| 4444 | } else if (file.is_directory && ri->uri[uri_len - 1] != '/') { |
| 4445 | mg_printf(conn, "HTTP/1.1 301 Moved Permanently\r\n" |
| 4446 | "Location: %s/\r\n\r\n", ri->uri); |
| 4447 | } else if (!strcmp(ri->request_method, "PROPFIND")) { |
| 4448 | handle_propfind(conn, path, &file); |
| 4449 | } else if (file.is_directory && |
| 4450 | !substitute_index_file(conn, path, sizeof(path), &file)) { |
| 4451 | if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")) { |
| 4452 | handle_directory_request(conn, path); |
| 4453 | } else { |
| 4454 | send_http_error(conn, 403, "Directory Listing Denied", |
| 4455 | "Directory listing denied"); |
| 4456 | } |
| 4457 | #ifdef USE_LUA |
| 4458 | } else if (match_prefix("**.lp$", 6, path) > 0) { |
| 4459 | handle_lsp_request(conn, path, &file, NULL); |
| 4460 | #endif |
| 4461 | #if !defined(NO_CGI) |
| 4462 | } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS], |
| 4463 | strlen(conn->ctx->config[CGI_EXTENSIONS]), |
| 4464 | path) > 0) { |
| 4465 | if (strcmp(ri->request_method, "POST") && |
| 4466 | strcmp(ri->request_method, "HEAD") && |
| 4467 | strcmp(ri->request_method, "GET")) { |
| 4468 | send_http_error(conn, 501, "Not Implemented", |
| 4469 | "Method %s is not implemented", ri->request_method); |
| 4470 | } else { |
| 4471 | handle_cgi_request(conn, path); |
| 4472 | } |
| 4473 | #endif // !NO_CGI |
| 4474 | } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS], |
| 4475 | strlen(conn->ctx->config[SSI_EXTENSIONS]), |
| 4476 | path) > 0) { |
| 4477 | handle_ssi_file_request(conn, path); |
| 4478 | } else if (is_not_modified(conn, &file)) { |
| 4479 | send_http_error(conn, 304, "Not Modified", "%s", ""); |
| 4480 | } else { |
| 4481 | handle_file_request(conn, path, &file); |
| 4482 | } |
| 4483 | } |
| 4484 | |
| 4485 | static void close_all_listening_sockets(struct mg_context *ctx) { |
| 4486 | int i; |
| 4487 | for (i = 0; i < ctx->num_listening_sockets; i++) { |
| 4488 | closesocket(ctx->listening_sockets[i].sock); |
| 4489 | } |
| 4490 | free(ctx->listening_sockets); |
| 4491 | } |
| 4492 | |
| 4493 | // Valid listening port specification is: [ip_address:]port[s] |
| 4494 | // Examples: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s |
| 4495 | // TODO(lsm): add parsing of the IPv6 address |
| 4496 | static int parse_port_string(const struct vec *vec, struct socket *so) { |
| 4497 | int a, b, c, d, port, len; |
| 4498 | |
| 4499 | // MacOS needs that. If we do not zero it, subsequent bind() will fail. |
| 4500 | // Also, all-zeroes in the socket address means binding to all addresses |
| 4501 | // for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). |
| 4502 | memset(so, 0, sizeof(*so)); |
| 4503 | |
| 4504 | if (sscanf(vec->ptr, "%d.%d.%d.%d:%d%n", &a, &b, &c, &d, &port, &len) == 5) { |
| 4505 | // Bind to a specific IPv4 address |
| 4506 | so->lsa.sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d); |
| 4507 | } else if (sscanf(vec->ptr, "%d%n", &port, &len) != 1 || |
| 4508 | len <= 0 || |
| 4509 | len > (int) vec->len || |
| 4510 | port < 1 || |
| 4511 | port > 65535 || |
| 4512 | (vec->ptr[len] && vec->ptr[len] != 's' && |
| 4513 | vec->ptr[len] != 'r' && vec->ptr[len] != ',')) { |
| 4514 | return 0; |
| 4515 | } |
| 4516 | |
| 4517 | so->is_ssl = vec->ptr[len] == 's'; |
| 4518 | so->ssl_redir = vec->ptr[len] == 'r'; |
| 4519 | #if defined(USE_IPV6) |
| 4520 | so->lsa.sin6.sin6_family = AF_INET6; |
| 4521 | so->lsa.sin6.sin6_port = htons((uint16_t) port); |
| 4522 | #else |
| 4523 | so->lsa.sin.sin_family = AF_INET; |
| 4524 | so->lsa.sin.sin_port = htons((uint16_t) port); |
| 4525 | #endif |
| 4526 | |
| 4527 | return 1; |
| 4528 | } |
| 4529 | |
| 4530 | static int set_ports_option(struct mg_context *ctx) { |
| 4531 | const char *list = ctx->config[LISTENING_PORTS]; |
| 4532 | int on = 1, success = 1; |
| 4533 | #if defined(USE_IPV6) |
| 4534 | int off = 0; |
| 4535 | #endif |
| 4536 | struct vec vec; |
| 4537 | struct socket so, *ptr; |
| 4538 | |
| 4539 | while (success && (list = next_option(list, &vec, NULL)) != NULL) { |
| 4540 | if (!parse_port_string(&vec, &so)) { |
| 4541 | cry(fc(ctx), "%s: %.*s: invalid port spec. Expecting list of: %s", |
| 4542 | __func__, (int) vec.len, vec.ptr, "[IP_ADDRESS:]PORT[s|p]"); |
| 4543 | success = 0; |
| 4544 | } else if (so.is_ssl && ctx->ssl_ctx == NULL) { |
| 4545 | cry(fc(ctx), "Cannot add SSL socket, is -ssl_certificate option set?"); |
| 4546 | success = 0; |
| 4547 | } else if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6)) == |
| 4548 | INVALID_SOCKET || |
| 4549 | // On Windows, SO_REUSEADDR is recommended only for |
| 4550 | // broadcast UDP sockets |
| 4551 | setsockopt(so.sock, SOL_SOCKET, SO_REUSEADDR, |
| 4552 | (SETSOCKOPT_CAST) &on, sizeof(on)) != 0 || |
| 4553 | #if defined(USE_IPV6) |
| 4554 | setsockopt(so.sock, IPPROTO_IPV6, IPV6_V6ONLY, (SETSOCKOPT_CAST) &off, |
| 4555 | sizeof(off)) != 0 || |
| 4556 | #endif |
| 4557 | bind(so.sock, &so.lsa.sa, sizeof(so.lsa)) != 0 || |
| 4558 | listen(so.sock, SOMAXCONN) != 0) { |
| 4559 | cry(fc(ctx), "%s: cannot bind to %.*s: %s", __func__, |
| 4560 | (int) vec.len, vec.ptr, strerror(ERRNO)); |
| 4561 | closesocket(so.sock); |
| 4562 | success = 0; |
| 4563 | } else if ((ptr = (struct socket*)realloc(ctx->listening_sockets, |
| 4564 | (ctx->num_listening_sockets + 1) * |
| 4565 | sizeof(ctx->listening_sockets[0]))) == NULL) { |
| 4566 | closesocket(so.sock); |
| 4567 | success = 0; |
| 4568 | } else { |
| 4569 | set_close_on_exec(so.sock); |
| 4570 | ctx->listening_sockets = ptr; |
| 4571 | ctx->listening_sockets[ctx->num_listening_sockets] = so; |
| 4572 | ctx->num_listening_sockets++; |
| 4573 | } |
| 4574 | } |
| 4575 | |
| 4576 | if (!success) { |
| 4577 | close_all_listening_sockets(ctx); |
| 4578 | } |
| 4579 | |
| 4580 | return success; |
| 4581 | } |
| 4582 | |
| 4583 | static void log_header(const struct mg_connection *conn, const char *header, |
| 4584 | FILE *fp) { |
| 4585 | const char *header_value; |
| 4586 | |
| 4587 | if ((header_value = mg_get_header(conn, header)) == NULL) { |
| 4588 | (void) fprintf(fp, "%s", " -"); |
| 4589 | } else { |
| 4590 | (void) fprintf(fp, " \"%s\"", header_value); |
| 4591 | } |
| 4592 | } |
| 4593 | |
| 4594 | static void log_access(const struct mg_connection *conn) { |
| 4595 | const struct mg_request_info *ri; |
| 4596 | FILE *fp; |
| 4597 | char date[64], src_addr[IP_ADDR_STR_LEN]; |
| 4598 | |
| 4599 | fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL ? NULL : |
| 4600 | fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+"); |
| 4601 | |
| 4602 | if (fp == NULL) |
| 4603 | return; |
| 4604 | |
| 4605 | strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", |
| 4606 | localtime(&conn->birth_time)); |
| 4607 | |
| 4608 | ri = &conn->request_info; |
| 4609 | flockfile(fp); |
| 4610 | |
| 4611 | sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa); |
| 4612 | fprintf(fp, "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT, |
| 4613 | src_addr, ri->remote_user == NULL ? "-" : ri->remote_user, date, |
| 4614 | ri->request_method ? ri->request_method : "-", |
| 4615 | ri->uri ? ri->uri : "-", ri->http_version, |
| 4616 | conn->status_code, conn->num_bytes_sent); |
| 4617 | log_header(conn, "Referer", fp); |
| 4618 | log_header(conn, "User-Agent", fp); |
| 4619 | fputc('\n', fp); |
| 4620 | fflush(fp); |
| 4621 | |
| 4622 | funlockfile(fp); |
| 4623 | fclose(fp); |
| 4624 | } |
| 4625 | |
| 4626 | // Verify given socket address against the ACL. |
| 4627 | // Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed. |
| 4628 | static int check_acl(struct mg_context *ctx, uint32_t remote_ip) { |
| 4629 | int allowed, flag; |
| 4630 | uint32_t net, mask; |
| 4631 | struct vec vec; |
| 4632 | const char *list = ctx->config[ACCESS_CONTROL_LIST]; |
| 4633 | |
| 4634 | // If any ACL is set, deny by default |
| 4635 | allowed = list == NULL ? '+' : '-'; |
| 4636 | |
| 4637 | while ((list = next_option(list, &vec, NULL)) != NULL) { |
| 4638 | flag = vec.ptr[0]; |
| 4639 | if ((flag != '+' && flag != '-') || |
| 4640 | parse_net(&vec.ptr[1], &net, &mask) == 0) { |
| 4641 | cry(fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__); |
| 4642 | return -1; |
| 4643 | } |
| 4644 | |
| 4645 | if (net == (remote_ip & mask)) { |
| 4646 | allowed = flag; |
| 4647 | } |
| 4648 | } |
| 4649 | |
| 4650 | return allowed == '+'; |
| 4651 | } |
| 4652 | |
| 4653 | #if !defined(_WIN32) |
| 4654 | static int set_uid_option(struct mg_context *ctx) { |
| 4655 | struct passwd *pw; |
| 4656 | const char *uid = ctx->config[RUN_AS_USER]; |
| 4657 | int success = 0; |
| 4658 | |
| 4659 | if (uid == NULL) { |
| 4660 | success = 1; |
| 4661 | } else { |
| 4662 | if ((pw = getpwnam(uid)) == NULL) { |
| 4663 | cry(fc(ctx), "%s: unknown user [%s]", __func__, uid); |
| 4664 | } else if (setgid(pw->pw_gid) == -1) { |
| 4665 | cry(fc(ctx), "%s: setgid(%s): %s", __func__, uid, strerror(errno)); |
| 4666 | } else if (setuid(pw->pw_uid) == -1) { |
| 4667 | cry(fc(ctx), "%s: setuid(%s): %s", __func__, uid, strerror(errno)); |
| 4668 | } else { |
| 4669 | success = 1; |
| 4670 | } |
| 4671 | } |
| 4672 | |
| 4673 | return success; |
| 4674 | } |
| 4675 | #endif // !_WIN32 |
| 4676 | |
| 4677 | #if !defined(NO_SSL) |
| 4678 | static pthread_mutex_t *ssl_mutexes; |
| 4679 | |
| 4680 | static int sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *)) { |
| 4681 | return (conn->ssl = SSL_new(s)) != NULL && |
| 4682 | SSL_set_fd(conn->ssl, conn->client.sock) == 1 && |
| 4683 | func(conn->ssl) == 1; |
| 4684 | } |
| 4685 | |
| 4686 | // Return OpenSSL error message |
| 4687 | static const char *ssl_error(void) { |
| 4688 | unsigned long err; |
| 4689 | err = ERR_get_error(); |
| 4690 | return err == 0 ? "" : ERR_error_string(err, NULL); |
| 4691 | } |
| 4692 | |
| 4693 | static void ssl_locking_callback(int mode, int mutex_num, const char *file, |
| 4694 | int line) { |
| 4695 | (void) line; |
| 4696 | (void) file; |
| 4697 | |
| 4698 | if (mode & 1) { // 1 is CRYPTO_LOCK |
| 4699 | (void) pthread_mutex_lock(&ssl_mutexes[mutex_num]); |
| 4700 | } else { |
| 4701 | (void) pthread_mutex_unlock(&ssl_mutexes[mutex_num]); |
| 4702 | } |
| 4703 | } |
| 4704 | |
| 4705 | static unsigned long ssl_id_callback(void) { |
| 4706 | return (unsigned long) pthread_self(); |
| 4707 | } |
| 4708 | |
| 4709 | #if !defined(NO_SSL_DL) |
| 4710 | static int load_dll(struct mg_context *ctx, const char *dll_name, |
| 4711 | struct ssl_func *sw) { |
| 4712 | union {void *p; void (*fp)(void);} u; |
| 4713 | void *dll_handle; |
| 4714 | struct ssl_func *fp; |
| 4715 | |
| 4716 | if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) { |
| 4717 | cry(fc(ctx), "%s: cannot load %s", __func__, dll_name); |
| 4718 | return 0; |
| 4719 | } |
| 4720 | |
| 4721 | for (fp = sw; fp->name != NULL; fp++) { |
| 4722 | #ifdef _WIN32 |
| 4723 | // GetProcAddress() returns pointer to function |
| 4724 | u.fp = (void (*)(void)) dlsym(dll_handle, fp->name); |
| 4725 | #else |
| 4726 | // dlsym() on UNIX returns void *. ISO C forbids casts of data pointers to |
| 4727 | // function pointers. We need to use a union to make a cast. |
| 4728 | u.p = dlsym(dll_handle, fp->name); |
| 4729 | #endif // _WIN32 |
| 4730 | if (u.fp == NULL) { |
| 4731 | cry(fc(ctx), "%s: %s: cannot find %s", __func__, dll_name, fp->name); |
| 4732 | return 0; |
| 4733 | } else { |
| 4734 | fp->ptr = u.fp; |
| 4735 | } |
| 4736 | } |
| 4737 | |
| 4738 | return 1; |
| 4739 | } |
| 4740 | #endif // NO_SSL_DL |
| 4741 | |
| 4742 | // Dynamically load SSL library. Set up ctx->ssl_ctx pointer. |
| 4743 | static int set_ssl_option(struct mg_context *ctx) { |
| 4744 | int i, size; |
| 4745 | const char *pem; |
| 4746 | |
| 4747 | // If PEM file is not specified, skip SSL initialization. |
| 4748 | if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL) { |
| 4749 | return 1; |
| 4750 | } |
| 4751 | |
| 4752 | #if !defined(NO_SSL_DL) |
| 4753 | if (!load_dll(ctx, SSL_LIB, ssl_sw) || |
| 4754 | !load_dll(ctx, CRYPTO_LIB, crypto_sw)) { |
| 4755 | return 0; |
| 4756 | } |
| 4757 | #endif // NO_SSL_DL |
| 4758 | |
| 4759 | // Initialize SSL library |
| 4760 | SSL_library_init(); |
| 4761 | SSL_load_error_strings(); |
| 4762 | |
| 4763 | if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) { |
| 4764 | cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error()); |
| 4765 | return 0; |
| 4766 | } |
| 4767 | |
| 4768 | // If user callback returned non-NULL, that means that user callback has |
| 4769 | // set up certificate itself. In this case, skip sertificate setting. |
| 4770 | if ((ctx->callbacks.init_ssl == NULL || |
| 4771 | !ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data)) && |
| 4772 | (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0 || |
| 4773 | SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0)) { |
| 4774 | cry(fc(ctx), "%s: cannot open %s: %s", __func__, pem, ssl_error()); |
| 4775 | return 0; |
| 4776 | } |
| 4777 | |
| 4778 | if (pem != NULL) { |
| 4779 | (void) SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem); |
| 4780 | } |
| 4781 | |
| 4782 | // Initialize locking callbacks, needed for thread safety. |
| 4783 | // http://www.openssl.org/support/faq.html#PROG1 |
| 4784 | size = sizeof(pthread_mutex_t) * CRYPTO_num_locks(); |
| 4785 | if ((ssl_mutexes = (pthread_mutex_t *) malloc((size_t)size)) == NULL) { |
| 4786 | cry(fc(ctx), "%s: cannot allocate mutexes: %s", __func__, ssl_error()); |
| 4787 | return 0; |
| 4788 | } |
| 4789 | |
| 4790 | for (i = 0; i < CRYPTO_num_locks(); i++) { |
| 4791 | pthread_mutex_init(&ssl_mutexes[i], NULL); |
| 4792 | } |
| 4793 | |
| 4794 | CRYPTO_set_locking_callback(&ssl_locking_callback); |
| 4795 | CRYPTO_set_id_callback(&ssl_id_callback); |
| 4796 | |
| 4797 | return 1; |
| 4798 | } |
| 4799 | |
| 4800 | static void uninitialize_ssl(struct mg_context *ctx) { |
| 4801 | int i; |
| 4802 | if (ctx->ssl_ctx != NULL) { |
| 4803 | CRYPTO_set_locking_callback(NULL); |
| 4804 | for (i = 0; i < CRYPTO_num_locks(); i++) { |
| 4805 | pthread_mutex_destroy(&ssl_mutexes[i]); |
| 4806 | } |
| 4807 | CRYPTO_set_locking_callback(NULL); |
| 4808 | CRYPTO_set_id_callback(NULL); |
| 4809 | } |
| 4810 | } |
| 4811 | #endif // !NO_SSL |
| 4812 | |
| 4813 | static int set_gpass_option(struct mg_context *ctx) { |
| 4814 | struct file file = STRUCT_FILE_INITIALIZER; |
| 4815 | const char *path = ctx->config[GLOBAL_PASSWORDS_FILE]; |
| 4816 | if (path != NULL && !mg_stat(fc(ctx), path, &file)) { |
| 4817 | cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO)); |
| 4818 | return 0; |
| 4819 | } |
| 4820 | return 1; |
| 4821 | } |
| 4822 | |
| 4823 | static int set_acl_option(struct mg_context *ctx) { |
| 4824 | return check_acl(ctx, (uint32_t) 0x7f000001UL) != -1; |
| 4825 | } |
| 4826 | |
| 4827 | static void reset_per_request_attributes(struct mg_connection *conn) { |
| 4828 | conn->path_info = NULL; |
| 4829 | conn->num_bytes_sent = conn->consumed_content = 0; |
| 4830 | conn->status_code = -1; |
| 4831 | conn->must_close = conn->request_len = conn->throttle = 0; |
| 4832 | } |
| 4833 | |
| 4834 | static void close_socket_gracefully(struct mg_connection *conn) { |
| 4835 | #if defined(_WIN32) |
| 4836 | char buf[MG_BUF_LEN]; |
| 4837 | int n; |
| 4838 | #endif |
| 4839 | struct linger linger; |
| 4840 | |
| 4841 | // Set linger option to avoid socket hanging out after close. This prevent |
| 4842 | // ephemeral port exhaust problem under high QPS. |
| 4843 | linger.l_onoff = 1; |
| 4844 | linger.l_linger = 1; |
| 4845 | setsockopt(conn->client.sock, SOL_SOCKET, SO_LINGER, |
| 4846 | (char *) &linger, sizeof(linger)); |
| 4847 | |
| 4848 | // Send FIN to the client |
| 4849 | shutdown(conn->client.sock, SHUT_WR); |
| 4850 | set_non_blocking_mode(conn->client.sock); |
| 4851 | |
| 4852 | #if defined(_WIN32) |
| 4853 | // Read and discard pending incoming data. If we do not do that and close the |
| 4854 | // socket, the data in the send buffer may be discarded. This |
| 4855 | // behaviour is seen on Windows, when client keeps sending data |
| 4856 | // when server decides to close the connection; then when client |
| 4857 | // does recv() it gets no data back. |
| 4858 | do { |
| 4859 | n = pull(NULL, conn, buf, sizeof(buf)); |
| 4860 | } while (n > 0); |
| 4861 | #endif |
| 4862 | |
| 4863 | // Now we know that our FIN is ACK-ed, safe to close |
| 4864 | closesocket(conn->client.sock); |
| 4865 | } |
| 4866 | |
| 4867 | static void close_connection(struct mg_connection *conn) { |
| 4868 | conn->must_close = 1; |
| 4869 | |
| 4870 | #ifndef NO_SSL |
| 4871 | if (conn->ssl != NULL) { |
| 4872 | // Run SSL_shutdown twice to ensure completly close SSL connection |
| 4873 | SSL_shutdown(conn->ssl); |
| 4874 | SSL_free(conn->ssl); |
| 4875 | conn->ssl = NULL; |
| 4876 | } |
| 4877 | #endif |
| 4878 | if (conn->client.sock != INVALID_SOCKET) { |
| 4879 | close_socket_gracefully(conn); |
| 4880 | conn->client.sock = INVALID_SOCKET; |
| 4881 | } |
| 4882 | } |
| 4883 | |
| 4884 | void mg_close_connection(struct mg_connection *conn) { |
| 4885 | #ifndef NO_SSL |
| 4886 | if (conn->client_ssl_ctx != NULL) { |
| 4887 | SSL_CTX_free((SSL_CTX *) conn->client_ssl_ctx); |
| 4888 | } |
| 4889 | #endif |
| 4890 | close_connection(conn); |
| 4891 | free(conn); |
| 4892 | } |
| 4893 | |
| 4894 | struct mg_connection *mg_connect(const char *host, int port, int use_ssl, |
| 4895 | char *ebuf, size_t ebuf_len) { |
| 4896 | static struct mg_context fake_ctx; |
| 4897 | struct mg_connection *conn = NULL; |
| 4898 | SOCKET sock; |
| 4899 | |
| 4900 | if ((sock = conn2(host, port, use_ssl, ebuf, ebuf_len)) == INVALID_SOCKET) { |
| 4901 | } else if ((conn = (struct mg_connection *) |
| 4902 | calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) { |
| 4903 | snprintf(ebuf, ebuf_len, "calloc(): %s", strerror(ERRNO)); |
| 4904 | closesocket(sock); |
| 4905 | #ifndef NO_SSL |
| 4906 | } else if (use_ssl && (conn->client_ssl_ctx = |
| 4907 | SSL_CTX_new(SSLv23_client_method())) == NULL) { |
| 4908 | snprintf(ebuf, ebuf_len, "SSL_CTX_new error"); |
| 4909 | closesocket(sock); |
| 4910 | free(conn); |
| 4911 | conn = NULL; |
| 4912 | #endif // NO_SSL |
| 4913 | } else { |
| 4914 | socklen_t len; |
| 4915 | conn->buf_size = MAX_REQUEST_SIZE; |
| 4916 | conn->buf = (char *) (conn + 1); |
| 4917 | conn->ctx = &fake_ctx; |
| 4918 | conn->client.sock = sock; |
| 4919 | getsockname(sock, &conn->client.rsa.sa, &len); |
| 4920 | conn->client.is_ssl = use_ssl; |
| 4921 | #ifndef NO_SSL |
| 4922 | if (use_ssl) { |
| 4923 | // SSL_CTX_set_verify call is needed to switch off server certificate |
| 4924 | // checking, which is off by default in OpenSSL and on in yaSSL. |
| 4925 | SSL_CTX_set_verify(conn->client_ssl_ctx, 0, 0); |
| 4926 | sslize(conn, conn->client_ssl_ctx, SSL_connect); |
| 4927 | } |
| 4928 | #endif |
| 4929 | } |
| 4930 | |
| 4931 | return conn; |
| 4932 | } |
| 4933 | |
| 4934 | static int is_valid_uri(const char *uri) { |
| 4935 | // Conform to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2 |
| 4936 | // URI can be an asterisk (*) or should start with slash. |
| 4937 | return uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0'); |
| 4938 | } |
| 4939 | |
| 4940 | static int getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len) { |
| 4941 | const char *cl; |
| 4942 | |
| 4943 | ebuf[0] = '\0'; |
| 4944 | reset_per_request_attributes(conn); |
| 4945 | conn->request_len = read_request(NULL, conn, conn->buf, conn->buf_size, |
| 4946 | &conn->data_len); |
| 4947 | assert(conn->request_len < 0 || conn->data_len >= conn->request_len); |
| 4948 | |
| 4949 | if (conn->request_len == 0 && conn->data_len == conn->buf_size) { |
| 4950 | snprintf(ebuf, ebuf_len, "%s", "Request Too Large"); |
| 4951 | } else if (conn->request_len <= 0) { |
| 4952 | snprintf(ebuf, ebuf_len, "%s", "Client closed connection"); |
| 4953 | } else if (parse_http_message(conn->buf, conn->buf_size, |
| 4954 | &conn->request_info) <= 0) { |
| 4955 | snprintf(ebuf, ebuf_len, "Bad request: [%.*s]", conn->data_len, conn->buf); |
| 4956 | } else { |
| 4957 | // Request is valid |
| 4958 | if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) { |
| 4959 | conn->content_len = strtoll(cl, NULL, 10); |
| 4960 | } else if (!mg_strcasecmp(conn->request_info.request_method, "POST") || |
| 4961 | !mg_strcasecmp(conn->request_info.request_method, "PUT")) { |
| 4962 | conn->content_len = -1; |
| 4963 | } else { |
| 4964 | conn->content_len = 0; |
| 4965 | } |
| 4966 | conn->birth_time = time(NULL); |
| 4967 | } |
| 4968 | return ebuf[0] == '\0'; |
| 4969 | } |
| 4970 | |
| 4971 | struct mg_connection *mg_download(const char *host, int port, int use_ssl, |
| 4972 | char *ebuf, size_t ebuf_len, |
| 4973 | const char *fmt, ...) { |
| 4974 | struct mg_connection *conn; |
| 4975 | va_list ap; |
| 4976 | |
| 4977 | va_start(ap, fmt); |
| 4978 | ebuf[0] = '\0'; |
| 4979 | if ((conn = mg_connect(host, port, use_ssl, ebuf, ebuf_len)) == NULL) { |
| 4980 | } else if (mg_vprintf(conn, fmt, ap) <= 0) { |
| 4981 | snprintf(ebuf, ebuf_len, "%s", "Error sending request"); |
| 4982 | } else { |
| 4983 | getreq(conn, ebuf, ebuf_len); |
| 4984 | } |
| 4985 | if (ebuf[0] != '\0' && conn != NULL) { |
| 4986 | mg_close_connection(conn); |
| 4987 | conn = NULL; |
| 4988 | } |
| 4989 | |
| 4990 | return conn; |
| 4991 | } |
| 4992 | |
| 4993 | static void process_new_connection(struct mg_connection *conn) { |
| 4994 | struct mg_request_info *ri = &conn->request_info; |
| 4995 | int keep_alive_enabled, keep_alive, discard_len; |
| 4996 | char ebuf[100]; |
| 4997 | |
| 4998 | keep_alive_enabled = !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes"); |
| 4999 | keep_alive = 0; |
| 5000 | |
| 5001 | // Important: on new connection, reset the receiving buffer. Credit goes |
| 5002 | // to crule42. |
| 5003 | conn->data_len = 0; |
| 5004 | do { |
| 5005 | if (!getreq(conn, ebuf, sizeof(ebuf))) { |
| 5006 | send_http_error(conn, 500, "Server Error", "%s", ebuf); |
| 5007 | conn->must_close = 1; |
| 5008 | } else if (!is_valid_uri(conn->request_info.uri)) { |
| 5009 | snprintf(ebuf, sizeof(ebuf), "Invalid URI: [%s]", ri->uri); |
| 5010 | send_http_error(conn, 400, "Bad Request", "%s", ebuf); |
| 5011 | } else if (strcmp(ri->http_version, "1.0") && |
| 5012 | strcmp(ri->http_version, "1.1")) { |
| 5013 | snprintf(ebuf, sizeof(ebuf), "Bad HTTP version: [%s]", ri->http_version); |
| 5014 | send_http_error(conn, 505, "Bad HTTP version", "%s", ebuf); |
| 5015 | } |
| 5016 | |
| 5017 | if (ebuf[0] == '\0') { |
| 5018 | handle_request(conn); |
| 5019 | if (conn->ctx->callbacks.end_request != NULL) { |
| 5020 | conn->ctx->callbacks.end_request(conn, conn->status_code); |
| 5021 | } |
| 5022 | log_access(conn); |
| 5023 | } |
| 5024 | if (ri->remote_user != NULL) { |
| 5025 | free((void *) ri->remote_user); |
| 5026 | // Important! When having connections with and without auth |
| 5027 | // would cause double free and then crash |
| 5028 | ri->remote_user = NULL; |
| 5029 | } |
| 5030 | |
| 5031 | // NOTE(lsm): order is important here. should_keep_alive() call |
| 5032 | // is using parsed request, which will be invalid after memmove's below. |
| 5033 | // Therefore, memorize should_keep_alive() result now for later use |
| 5034 | // in loop exit condition. |
| 5035 | keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled && |
| 5036 | conn->content_len >= 0 && should_keep_alive(conn); |
| 5037 | |
| 5038 | // Discard all buffered data for this request |
| 5039 | discard_len = conn->content_len >= 0 && conn->request_len > 0 && |
| 5040 | conn->request_len + conn->content_len < (int64_t) conn->data_len ? |
| 5041 | (int) (conn->request_len + conn->content_len) : conn->data_len; |
| 5042 | assert(discard_len >= 0); |
| 5043 | memmove(conn->buf, conn->buf + discard_len, conn->data_len - discard_len); |
| 5044 | conn->data_len -= discard_len; |
| 5045 | assert(conn->data_len >= 0); |
| 5046 | assert(conn->data_len <= conn->buf_size); |
| 5047 | } while (keep_alive); |
| 5048 | } |
| 5049 | |
| 5050 | // Worker threads take accepted socket from the queue |
| 5051 | static int consume_socket(struct mg_context *ctx, struct socket *sp) { |
| 5052 | (void) pthread_mutex_lock(&ctx->mutex); |
| 5053 | DEBUG_TRACE(("going idle")); |
| 5054 | |
| 5055 | // If the queue is empty, wait. We're idle at this point. |
| 5056 | while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) { |
| 5057 | pthread_cond_wait(&ctx->sq_full, &ctx->mutex); |
| 5058 | } |
| 5059 | |
| 5060 | // If we're stopping, sq_head may be equal to sq_tail. |
| 5061 | if (ctx->sq_head > ctx->sq_tail) { |
| 5062 | // Copy socket from the queue and increment tail |
| 5063 | *sp = ctx->queue[ctx->sq_tail % ARRAY_SIZE(ctx->queue)]; |
| 5064 | ctx->sq_tail++; |
| 5065 | DEBUG_TRACE(("grabbed socket %d, going busy", sp->sock)); |
| 5066 | |
| 5067 | // Wrap pointers if needed |
| 5068 | while (ctx->sq_tail > (int) ARRAY_SIZE(ctx->queue)) { |
| 5069 | ctx->sq_tail -= ARRAY_SIZE(ctx->queue); |
| 5070 | ctx->sq_head -= ARRAY_SIZE(ctx->queue); |
| 5071 | } |
| 5072 | } |
| 5073 | |
| 5074 | (void) pthread_cond_signal(&ctx->sq_empty); |
| 5075 | (void) pthread_mutex_unlock(&ctx->mutex); |
| 5076 | |
| 5077 | return !ctx->stop_flag; |
| 5078 | } |
| 5079 | |
| 5080 | static void *worker_thread(void *thread_func_param) { |
| 5081 | struct mg_context *ctx = (struct mg_context *)thread_func_param; |
| 5082 | struct mg_connection *conn; |
| 5083 | |
| 5084 | conn = (struct mg_connection *) calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE); |
| 5085 | if (conn == NULL) { |
| 5086 | cry(fc(ctx), "%s", "Cannot create new connection struct, OOM"); |
| 5087 | } else { |
| 5088 | conn->buf_size = MAX_REQUEST_SIZE; |
| 5089 | conn->buf = (char *) (conn + 1); |
| 5090 | conn->ctx = ctx; |
| 5091 | conn->request_info.user_data = ctx->user_data; |
| 5092 | |
| 5093 | // Call consume_socket() even when ctx->stop_flag > 0, to let it signal |
| 5094 | // sq_empty condvar to wake up the master waiting in produce_socket() |
| 5095 | while (consume_socket(ctx, &conn->client)) { |
| 5096 | conn->birth_time = time(NULL); |
| 5097 | |
| 5098 | // Fill in IP, port info early so even if SSL setup below fails, |
| 5099 | // error handler would have the corresponding info. |
| 5100 | // Thanks to Johannes Winkelmann for the patch. |
| 5101 | // TODO(lsm): Fix IPv6 case |
| 5102 | conn->request_info.remote_port = ntohs(conn->client.rsa.sin.sin_port); |
| 5103 | memcpy(&conn->request_info.remote_ip, |
| 5104 | &conn->client.rsa.sin.sin_addr.s_addr, 4); |
| 5105 | conn->request_info.remote_ip = ntohl(conn->request_info.remote_ip); |
| 5106 | conn->request_info.is_ssl = conn->client.is_ssl; |
| 5107 | |
| 5108 | if (!conn->client.is_ssl |
| 5109 | #ifndef NO_SSL |
| 5110 | || sslize(conn, conn->ctx->ssl_ctx, SSL_accept) |
| 5111 | #endif |
| 5112 | ) { |
| 5113 | process_new_connection(conn); |
| 5114 | } |
| 5115 | |
| 5116 | close_connection(conn); |
| 5117 | } |
| 5118 | free(conn); |
| 5119 | } |
| 5120 | |
| 5121 | // Signal master that we're done with connection and exiting |
| 5122 | (void) pthread_mutex_lock(&ctx->mutex); |
| 5123 | ctx->num_threads--; |
| 5124 | (void) pthread_cond_signal(&ctx->cond); |
| 5125 | assert(ctx->num_threads >= 0); |
| 5126 | (void) pthread_mutex_unlock(&ctx->mutex); |
| 5127 | |
| 5128 | DEBUG_TRACE(("exiting")); |
| 5129 | return NULL; |
| 5130 | } |
| 5131 | |
| 5132 | // Master thread adds accepted socket to a queue |
| 5133 | static void produce_socket(struct mg_context *ctx, const struct socket *sp) { |
| 5134 | (void) pthread_mutex_lock(&ctx->mutex); |
| 5135 | |
| 5136 | // If the queue is full, wait |
| 5137 | while (ctx->stop_flag == 0 && |
| 5138 | ctx->sq_head - ctx->sq_tail >= (int) ARRAY_SIZE(ctx->queue)) { |
| 5139 | (void) pthread_cond_wait(&ctx->sq_empty, &ctx->mutex); |
| 5140 | } |
| 5141 | |
| 5142 | if (ctx->sq_head - ctx->sq_tail < (int) ARRAY_SIZE(ctx->queue)) { |
| 5143 | // Copy socket to the queue and increment head |
| 5144 | ctx->queue[ctx->sq_head % ARRAY_SIZE(ctx->queue)] = *sp; |
| 5145 | ctx->sq_head++; |
| 5146 | DEBUG_TRACE(("queued socket %d", sp->sock)); |
| 5147 | } |
| 5148 | |
| 5149 | (void) pthread_cond_signal(&ctx->sq_full); |
| 5150 | (void) pthread_mutex_unlock(&ctx->mutex); |
| 5151 | } |
| 5152 | |
| 5153 | static int set_sock_timeout(SOCKET sock, int milliseconds) { |
| 5154 | #ifdef _WIN32 |
| 5155 | DWORD t = milliseconds; |
| 5156 | #else |
| 5157 | struct timeval t; |
| 5158 | t.tv_sec = milliseconds / 1000; |
| 5159 | t.tv_usec = (milliseconds * 1000) % 1000000; |
| 5160 | #endif |
| 5161 | return setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (SETSOCKOPT_CAST) &t, sizeof(t)) || |
| 5162 | setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (SETSOCKOPT_CAST) &t, sizeof(t)); |
| 5163 | } |
| 5164 | |
| 5165 | static void accept_new_connection(const struct socket *listener, |
| 5166 | struct mg_context *ctx) { |
| 5167 | struct socket so; |
| 5168 | char src_addr[IP_ADDR_STR_LEN]; |
| 5169 | socklen_t len = sizeof(so.rsa); |
| 5170 | int on = 1; |
| 5171 | |
| 5172 | if ((so.sock = accept(listener->sock, &so.rsa.sa, &len)) == INVALID_SOCKET) { |
| 5173 | } else if (!check_acl(ctx, ntohl(* (uint32_t *) &so.rsa.sin.sin_addr))) { |
| 5174 | sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa); |
| 5175 | cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr); |
| 5176 | closesocket(so.sock); |
| 5177 | } else { |
| 5178 | // Put so socket structure into the queue |
| 5179 | DEBUG_TRACE(("Accepted socket %d", (int) so.sock)); |
| 5180 | so.is_ssl = listener->is_ssl; |
| 5181 | so.ssl_redir = listener->ssl_redir; |
| 5182 | getsockname(so.sock, &so.lsa.sa, &len); |
| 5183 | // Set TCP keep-alive. This is needed because if HTTP-level keep-alive |
| 5184 | // is enabled, and client resets the connection, server won't get |
| 5185 | // TCP FIN or RST and will keep the connection open forever. With TCP |
| 5186 | // keep-alive, next keep-alive handshake will figure out that the client |
| 5187 | // is down and will close the server end. |
| 5188 | // Thanks to Igor Klopov who suggested the patch. |
| 5189 | setsockopt(so.sock, SOL_SOCKET, SO_KEEPALIVE, (SETSOCKOPT_CAST) &on, sizeof(on)); |
| 5190 | set_sock_timeout(so.sock, atoi(ctx->config[REQUEST_TIMEOUT])); |
| 5191 | produce_socket(ctx, &so); |
| 5192 | } |
| 5193 | } |
| 5194 | |
| 5195 | static void *master_thread(void *thread_func_param) { |
| 5196 | struct mg_context *ctx = (struct mg_context *)thread_func_param; |
| 5197 | struct pollfd *pfd; |
| 5198 | int i; |
| 5199 | |
| 5200 | // Increase priority of the master thread |
| 5201 | #if defined(_WIN32) |
| 5202 | SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); |
| 5203 | #endif |
| 5204 | |
| 5205 | #if defined(ISSUE_317) |
| 5206 | struct sched_param sched_param; |
| 5207 | sched_param.sched_priority = sched_get_priority_max(SCHED_RR); |
| 5208 | pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param); |
| 5209 | #endif |
| 5210 | |
| 5211 | pfd = (struct pollfd *)calloc(ctx->num_listening_sockets, sizeof(pfd[0])); |
| 5212 | while (pfd != NULL && ctx->stop_flag == 0) { |
| 5213 | for (i = 0; i < ctx->num_listening_sockets; i++) { |
| 5214 | pfd[i].fd = ctx->listening_sockets[i].sock; |
| 5215 | pfd[i].events = POLLIN; |
| 5216 | } |
| 5217 | |
| 5218 | if (poll(pfd, ctx->num_listening_sockets, 200) > 0) { |
| 5219 | for (i = 0; i < ctx->num_listening_sockets; i++) { |
| 5220 | // NOTE(lsm): on QNX, poll() returns POLLRDNORM after the |
| 5221 | // successfull poll, and POLLIN is defined as (POLLRDNORM | POLLRDBAND) |
| 5222 | // Therefore, we're checking pfd[i].revents & POLLIN, not |
| 5223 | // pfd[i].revents == POLLIN. |
| 5224 | if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) { |
| 5225 | accept_new_connection(&ctx->listening_sockets[i], ctx); |
| 5226 | } |
| 5227 | } |
| 5228 | } |
| 5229 | } |
| 5230 | free(pfd); |
| 5231 | DEBUG_TRACE(("stopping workers")); |
| 5232 | |
| 5233 | // Stop signal received: somebody called mg_stop. Quit. |
| 5234 | close_all_listening_sockets(ctx); |
| 5235 | |
| 5236 | // Wakeup workers that are waiting for connections to handle. |
| 5237 | pthread_cond_broadcast(&ctx->sq_full); |
| 5238 | |
| 5239 | // Wait until all threads finish |
| 5240 | (void) pthread_mutex_lock(&ctx->mutex); |
| 5241 | while (ctx->num_threads > 0) { |
| 5242 | (void) pthread_cond_wait(&ctx->cond, &ctx->mutex); |
| 5243 | } |
| 5244 | (void) pthread_mutex_unlock(&ctx->mutex); |
| 5245 | |
| 5246 | // All threads exited, no sync is needed. Destroy mutex and condvars |
| 5247 | (void) pthread_mutex_destroy(&ctx->mutex); |
| 5248 | (void) pthread_cond_destroy(&ctx->cond); |
| 5249 | (void) pthread_cond_destroy(&ctx->sq_empty); |
| 5250 | (void) pthread_cond_destroy(&ctx->sq_full); |
| 5251 | |
| 5252 | #if !defined(NO_SSL) |
| 5253 | uninitialize_ssl(ctx); |
| 5254 | #endif |
| 5255 | DEBUG_TRACE(("exiting")); |
| 5256 | |
| 5257 | // Signal mg_stop() that we're done. |
| 5258 | // WARNING: This must be the very last thing this |
| 5259 | // thread does, as ctx becomes invalid after this line. |
| 5260 | ctx->stop_flag = 2; |
| 5261 | return NULL; |
| 5262 | } |
| 5263 | |
| 5264 | static void free_context(struct mg_context *ctx) { |
| 5265 | int i; |
| 5266 | |
| 5267 | // Deallocate config parameters |
| 5268 | for (i = 0; i < NUM_OPTIONS; i++) { |
| 5269 | if (ctx->config[i] != NULL) |
| 5270 | free(ctx->config[i]); |
| 5271 | } |
| 5272 | |
| 5273 | #ifndef NO_SSL |
| 5274 | // Deallocate SSL context |
| 5275 | if (ctx->ssl_ctx != NULL) { |
| 5276 | SSL_CTX_free(ctx->ssl_ctx); |
| 5277 | } |
| 5278 | if (ssl_mutexes != NULL) { |
| 5279 | free(ssl_mutexes); |
| 5280 | ssl_mutexes = NULL; |
| 5281 | } |
| 5282 | #endif // !NO_SSL |
| 5283 | |
| 5284 | // Deallocate context itself |
| 5285 | free(ctx); |
| 5286 | } |
| 5287 | |
| 5288 | void mg_stop(struct mg_context *ctx) { |
| 5289 | ctx->stop_flag = 1; |
| 5290 | |
| 5291 | // Wait until mg_fini() stops |
| 5292 | while (ctx->stop_flag != 2) { |
| 5293 | (void) mg_sleep(10); |
| 5294 | } |
| 5295 | free_context(ctx); |
| 5296 | |
| 5297 | #if defined(_WIN32) && !defined(__SYMBIAN32__) |
| 5298 | (void) WSACleanup(); |
| 5299 | #endif // _WIN32 |
| 5300 | } |
| 5301 | |
| 5302 | struct mg_context *mg_start(const struct mg_callbacks *callbacks, |
| 5303 | void *user_data, |
| 5304 | const char **options) { |
| 5305 | struct mg_context *ctx; |
| 5306 | const char *name, *value, *default_value; |
| 5307 | int i; |
| 5308 | |
| 5309 | #if defined(_WIN32) && !defined(__SYMBIAN32__) |
| 5310 | WSADATA data; |
| 5311 | WSAStartup(MAKEWORD(2,2), &data); |
| 5312 | InitializeCriticalSection(&global_log_file_lock); |
| 5313 | #endif // _WIN32 |
| 5314 | |
| 5315 | // Allocate context and initialize reasonable general case defaults. |
| 5316 | // TODO(lsm): do proper error handling here. |
| 5317 | if ((ctx = (struct mg_context *) calloc(1, sizeof(*ctx))) == NULL) { |
| 5318 | return NULL; |
| 5319 | } |
| 5320 | ctx->callbacks = *callbacks; |
| 5321 | ctx->user_data = user_data; |
| 5322 | |
| 5323 | while (options && (name = *options++) != NULL) { |
| 5324 | if ((i = get_option_index(name)) == -1) { |
| 5325 | cry(fc(ctx), "Invalid option: %s", name); |
| 5326 | free_context(ctx); |
| 5327 | return NULL; |
| 5328 | } else if ((value = *options++) == NULL) { |
| 5329 | cry(fc(ctx), "%s: option value cannot be NULL", name); |
| 5330 | free_context(ctx); |
| 5331 | return NULL; |
| 5332 | } |
| 5333 | if (ctx->config[i] != NULL) { |
| 5334 | cry(fc(ctx), "warning: %s: duplicate option", name); |
| 5335 | free(ctx->config[i]); |
| 5336 | } |
| 5337 | ctx->config[i] = mg_strdup(value); |
| 5338 | DEBUG_TRACE(("[%s] -> [%s]", name, value)); |
| 5339 | } |
| 5340 | |
| 5341 | // Set default value if needed |
| 5342 | for (i = 0; config_options[i * 2] != NULL; i++) { |
| 5343 | default_value = config_options[i * 2 + 1]; |
| 5344 | if (ctx->config[i] == NULL && default_value != NULL) { |
| 5345 | ctx->config[i] = mg_strdup(default_value); |
| 5346 | } |
| 5347 | } |
| 5348 | |
| 5349 | // NOTE(lsm): order is important here. SSL certificates must |
| 5350 | // be initialized before listening ports. UID must be set last. |
| 5351 | if (!set_gpass_option(ctx) || |
| 5352 | #if !defined(NO_SSL) |
| 5353 | !set_ssl_option(ctx) || |
| 5354 | #endif |
| 5355 | !set_ports_option(ctx) || |
| 5356 | #if !defined(_WIN32) |
| 5357 | !set_uid_option(ctx) || |
| 5358 | #endif |
| 5359 | !set_acl_option(ctx)) { |
| 5360 | free_context(ctx); |
| 5361 | return NULL; |
| 5362 | } |
| 5363 | |
| 5364 | #if !defined(_WIN32) && !defined(__SYMBIAN32__) |
| 5365 | // Ignore SIGPIPE signal, so if browser cancels the request, it |
| 5366 | // won't kill the whole process. |
| 5367 | (void) signal(SIGPIPE, SIG_IGN); |
| 5368 | // Also ignoring SIGCHLD to let the OS to reap zombies properly. |
| 5369 | (void) signal(SIGCHLD, SIG_IGN); |
| 5370 | #endif // !_WIN32 |
| 5371 | |
| 5372 | (void) pthread_mutex_init(&ctx->mutex, NULL); |
| 5373 | (void) pthread_cond_init(&ctx->cond, NULL); |
| 5374 | (void) pthread_cond_init(&ctx->sq_empty, NULL); |
| 5375 | (void) pthread_cond_init(&ctx->sq_full, NULL); |
| 5376 | |
| 5377 | // Start master (listening) thread |
| 5378 | mg_start_thread(master_thread, ctx); |
| 5379 | |
| 5380 | // Start worker threads |
| 5381 | for (i = 0; i < atoi(ctx->config[NUM_THREADS]); i++) { |
| 5382 | if (mg_start_thread(worker_thread, ctx) != 0) { |
| 5383 | cry(fc(ctx), "Cannot start worker thread: %ld", (long) ERRNO); |
| 5384 | } else { |
| 5385 | ctx->num_threads++; |
| 5386 | } |
| 5387 | } |
| 5388 | |
| 5389 | return ctx; |
| 5390 | } |