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