1 // Copyright (c) 2004-2013 Sergey Lyubka <valenok@gmail.com>
2 // Copyright (c) 2013-2014 Cesanta Software Limited
3 // All rights reserved
4 //
5 // This library is dual-licensed: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License version 2 as
7 // published by the Free Software Foundation. For the terms of this
8 // license, see <http://www.gnu.org/licenses/>.
9 //
10 // You are free to use this library under the terms of the GNU General
11 // Public License, but WITHOUT ANY WARRANTY; without even the implied
12 // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 // See the GNU General Public License for more details.
14 //
15 // Alternatively, you can license this library under a commercial
16 // license, as set out in <http://cesanta.com/>.
17
18 #include <sys/socket.h>
19
20 #undef UNICODE // Use ANSI WinAPI functions
21 #undef _UNICODE // Use multibyte encoding on Windows
22 #define _MBCS // Use multibyte encoding on Windows
23 #define _INTEGRAL_MAX_BITS 64 // Enable _stati64() on Windows
24 #define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005+
25 //#undef WIN32_LEAN_AND_MEAN // Let windows.h always include winsock2.h
26 #define _XOPEN_SOURCE 600 // For flockfile() on Linux
27 #define __STDC_FORMAT_MACROS // <inttypes.h> wants this for C++
28 #define __STDC_LIMIT_MACROS // C++ wants that for INT64_MAX
29 #ifndef _LARGEFILE_SOURCE
30 # define _LARGEFILE_SOURCE // Enable fseeko() and ftello() functions
31 #endif
32 #define _FILE_OFFSET_BITS 64 // Enable 64-bit file offsets
33
34 #ifdef _MSC_VER
35 #pragma warning (disable : 4127) // FD_SET() emits warning, disable it
36 #pragma warning (disable : 4204) // missing c99 support
37 #endif
38
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <stddef.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <fcntl.h>
46 #include <assert.h>
47 #include <errno.h>
48 #include <time.h>
49 #include <ctype.h>
50 #include <stdarg.h>
51
52 #ifdef _WIN32
53 #include <winsock2.h>
54 #include <windows.h>
55 #include <process.h> // For _beginthread
56 #include <io.h> // For _lseeki64
57 #include <direct.h> // For _mkdir
58 typedef int socklen_t;
59 #if !defined(__MINGW32__) //|| !defined(_PID_T_) || defined(_NO_OLDNAMES)
60 typedef HANDLE pid_t;
61 #endif
62 typedef SOCKET sock_t;
63 typedef unsigned char uint8_t;
64 typedef unsigned int uint32_t;
65 typedef unsigned short uint16_t;
66 typedef unsigned __int64 uint64_t;
67 typedef __int64 int64_t;
68 typedef CRITICAL_SECTION mutex_t;
69 typedef struct _stati64 file_stat_t;
70 //#pragma comment(lib, "ws2_32.lib")
71 #define snprintf _snprintf
72 #define vsnprintf _vsnprintf
73 #define INT64_FMT "I64d"
74 #ifndef EINPROGRESS
75 #define EINPROGRESS WSAEINPROGRESS
76 #endif
77 #ifndef EWOULDBLOCK
78 #define EWOULDBLOCK WSAEWOULDBLOCK
79 #endif
80 #define mutex_init(x) InitializeCriticalSection(x)
81 #define mutex_destroy(x) DeleteCriticalSection(x)
82 #define mutex_lock(x) EnterCriticalSection(x)
83 #define mutex_unlock(x) LeaveCriticalSection(x)
84 #define get_thread_id() ((unsigned long) GetCurrentThreadId())
85 #ifndef S_ISDIR
86 #define S_ISDIR(x) ((x) & _S_IFDIR)
87 #endif
88 #define sleep(x) Sleep((x) * 1000)
89 #define stat(x, y) mg_stat((x), (y))
90 #define fopen(x, y) mg_fopen((x), (y))
91 #define open(x, y) mg_open((x), (y))
92 #define lseek(x, y, z) _lseeki64((x), (y), (z))
93 #define mkdir(x, y) _mkdir(x)
94 #define to64(x) _atoi64(x)
95 #define flockfile(x)
96 #define funlockfile(x)
97 #ifndef va_copy
98 #define va_copy(x,y) x = y
99 #endif // MINGW #defines va_copy
100 #ifndef __func__
101 #define STRX(x) #x
102 #define STR(x) STRX(x)
103 #define __func__ __FILE__ ":" STR(__LINE__)
104 #endif
105 #else
106 #include <dirent.h>
107 #include <inttypes.h>
108 #include <pthread.h>
109 #include <pwd.h>
110 #include <signal.h>
111 #include <unistd.h>
112 #include <netdb.h>
113 #include <arpa/inet.h> // For inet_pton() when MONGOOSE_USE_IPV6 is defined
114 #include <netinet/in.h>
115 #include <sys/socket.h>
116 #include <sys/select.h>
117 #define closesocket(x) close(x)
118 typedef int sock_t;
119 typedef pthread_mutex_t mutex_t;
120 typedef struct stat file_stat_t;
121 #define mutex_init(x) pthread_mutex_init(x, NULL)
122 #define mutex_destroy(x) pthread_mutex_destroy(x)
123 #define mutex_lock(x) pthread_mutex_lock(x)
124 #define mutex_unlock(x) pthread_mutex_unlock(x)
125 #define get_thread_id() ((unsigned long) pthread_self())
126 #define INVALID_SOCKET ((sock_t) -1)
127 #define INT64_FMT PRId64
128 #define to64(x) strtoll(x, NULL, 10)
129 #define __cdecl
130 #define O_BINARY 0
131 #endif
132
133 #ifdef MONGOOSE_USE_SSL
134 #ifdef __APPLE__
135 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
136 #endif
137 #include <openssl/ssl.h>
138 #endif
139
140 #include "mongoose.h"
141
142 struct ll { struct ll *prev, *next; };
143 #define LINKED_LIST_INIT(N) ((N)->next = (N)->prev = (N))
144 #define LINKED_LIST_DECLARE_AND_INIT(H) struct ll H = { &H, &H }
145 #define LINKED_LIST_ENTRY(P,T,N) ((T *)((char *)(P) - offsetof(T, N)))
146 #define LINKED_LIST_IS_EMPTY(N) ((N)->next == (N))
147 #define LINKED_LIST_FOREACH(H,N,T) \
148 for (N = (H)->next, T = (N)->next; N != (H); N = (T), T = (N)->next)
149 #define LINKED_LIST_ADD_TO_FRONT(H,N) do { ((H)->next)->prev = (N); \
150 (N)->next = ((H)->next); (N)->prev = (H); (H)->next = (N); } while (0)
151 #define LINKED_LIST_ADD_TO_TAIL(H,N) do { ((H)->prev)->next = (N); \
152 (N)->prev = ((H)->prev); (N)->next = (H); (H)->prev = (N); } while (0)
153 #define LINKED_LIST_REMOVE(N) do { ((N)->next)->prev = ((N)->prev); \
154 ((N)->prev)->next = ((N)->next); LINKED_LIST_INIT(N); } while (0)
155
156 #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
157 #define MAX_REQUEST_SIZE 16384
158 #define IOBUF_SIZE 8192
159 #define MAX_PATH_SIZE 8192
160 #define LUA_SCRIPT_PATTERN "**.lp$"
161 #define DEFAULT_CGI_PATTERN "**.cgi$|**.pl$|**.php$"
162 #define CGI_ENVIRONMENT_SIZE 4096
163 #define MAX_CGI_ENVIR_VARS 64
164 #define ENV_EXPORT_TO_CGI "MONGOOSE_CGI"
165 #define PASSWORDS_FILE_NAME ".htpasswd"
166
167 #ifndef MONGOOSE_USE_WEBSOCKET_PING_INTERVAL
168 #define MONGOOSE_USE_WEBSOCKET_PING_INTERVAL 5
169 #endif
170
171 // Extra HTTP headers to send in every static file reply
172 #if !defined(MONGOOSE_USE_EXTRA_HTTP_HEADERS)
173 #define MONGOOSE_USE_EXTRA_HTTP_HEADERS ""
174 #endif
175
176 #ifndef MONGOOSE_USE_POST_SIZE_LIMIT
177 #define MONGOOSE_USE_POST_SIZE_LIMIT 0
178 #endif
179
180 #ifndef MONGOOSE_USE_IDLE_TIMEOUT_SECONDS
181 #define MONGOOSE_USE_IDLE_TIMEOUT_SECONDS 30
182 #endif
183
184 #ifdef MONGOOSE_ENABLE_DEBUG
185 #define DBG(x) do { printf("%-20s ", __func__); printf x; putchar('\n'); \
186 fflush(stdout); } while(0)
187 #else
188 #define DBG(x)
189 #endif
190
191 #ifdef MONGOOSE_NO_FILESYSTEM
192 #define MONGOOSE_NO_AUTH
193 #define MONGOOSE_NO_CGI
194 #define MONGOOSE_NO_DAV
195 #define MONGOOSE_NO_DIRECTORY_LISTING
196 #define MONGOOSE_NO_LOGGING
197 #endif
198
199 union socket_address {
200 struct sockaddr sa;
201 struct sockaddr_in sin;
202 #ifdef MONGOOSE_USE_IPV6
203 struct sockaddr_in6 sin6;
204 #endif
205 };
206
207 struct vec {
208 const char *ptr;
209 int len;
210 };
211
212 // For directory listing and WevDAV support
213 struct dir_entry {
214 struct connection *conn;
215 char *file_name;
216 file_stat_t st;
217 };
218
219 // NOTE(lsm): this enum shoulds be in sync with the config_options.
220 enum {
221 ACCESS_CONTROL_LIST,
222 #ifndef MONGOOSE_NO_FILESYSTEM
223 ACCESS_LOG_FILE,
224 #ifndef MONGOOSE_NO_AUTH
225 AUTH_DOMAIN,
226 #endif
227 #ifndef MONGOOSE_NO_CGI
228 CGI_INTERPRETER,
229 CGI_PATTERN,
230 #endif
231 #ifndef MONGOOSE_NO_DAV
232 DAV_AUTH_FILE,
233 #endif
234 DOCUMENT_ROOT,
235 #ifndef MONGOOSE_NO_DIRECTORY_LISTING
236 ENABLE_DIRECTORY_LISTING,
237 #endif
238 #endif
239 EXTRA_MIME_TYPES,
240 #if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_AUTH)
241 GLOBAL_AUTH_FILE,
242 #endif
243 HIDE_FILES_PATTERN,
244 #ifndef MONGOOSE_NO_FILESYSTEM
245 INDEX_FILES,
246 #endif
247 LISTENING_PORT,
248 #ifndef _WIN32
249 RUN_AS_USER,
250 #endif
251 #ifdef MONGOOSE_USE_SSL
252 SSL_CERTIFICATE,
253 #endif
254 URL_REWRITES,
255 NUM_OPTIONS
256 };
257
258 static const char *static_config_options[] = {
259 "access_control_list", NULL,
260 #ifndef MONGOOSE_NO_FILESYSTEM
261 "access_log_file", NULL,
262 #ifndef MONGOOSE_NO_AUTH
263 "auth_domain", "mydomain.com",
264 #endif
265 #ifndef MONGOOSE_NO_CGI
266 "cgi_interpreter", NULL,
267 "cgi_pattern", DEFAULT_CGI_PATTERN,
268 #endif
269 #ifndef MONGOOSE_NO_DAV
270 "dav_auth_file", NULL,
271 #endif
272 "document_root", NULL,
273 #ifndef MONGOOSE_NO_DIRECTORY_LISTING
274 "enable_directory_listing", "yes",
275 #endif
276 #endif
277 "extra_mime_types", NULL,
278 #if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_AUTH)
279 "global_auth_file", NULL,
280 #endif
281 "hide_files_patterns", NULL,
282 #ifndef MONGOOSE_NO_FILESYSTEM
283 "index_files","index.html,index.htm,index.cgi,index.php,index.lp",
284 #endif
285 "listening_port", NULL,
286 #ifndef _WIN32
287 "run_as_user", NULL,
288 #endif
289 #ifdef MONGOOSE_USE_SSL
290 "ssl_certificate", NULL,
291 #endif
292 "url_rewrites", NULL,
293 NULL
294 };
295
296 struct mg_server {
297 sock_t listening_sock;
298 union socket_address lsa; // Listening socket address
299 struct ll active_connections;
300 mg_handler_t request_handler;
301 mg_handler_t error_handler;
302 mg_handler_t auth_handler;
303 char *config_options[NUM_OPTIONS];
304 char local_ip[48];
305 void *server_data;
306 #ifdef MONGOOSE_USE_SSL
307 SSL_CTX *ssl_ctx; // Server SSL context
308 SSL_CTX *client_ssl_ctx; // Client SSL context
309 #endif
310 sock_t ctl[2]; // Control socketpair. Used to wake up from select() call
311 };
312
313 // Expandable IO buffer
314 struct iobuf {
315 char *buf; // Buffer that holds the data
316 int size; // Buffer size
317 int len; // Number of bytes currently in a buffer
318 };
319
320 // Local endpoint representation
321 union endpoint {
322 int fd; // Opened regular local file
323 sock_t cgi_sock; // CGI socket
324 void *ssl; // SSL descriptor
325 };
326
327 enum endpoint_type { EP_NONE, EP_FILE, EP_CGI, EP_USER, EP_PUT, EP_CLIENT };
328 enum connection_flags {
329 CONN_CLOSE = 1, // Connection must be closed at the end of the poll
330 CONN_SPOOL_DONE = 2, // All data has been buffered for sending
331 CONN_SSL_HANDS_SHAKEN = 4, // SSL handshake has completed. Only for SSL
332 CONN_HEADERS_SENT = 8, // User callback has sent HTTP headers
333 CONN_BUFFER = 16, // CGI only. Holds data send until CGI prints
334 // all HTTP headers
335 CONN_CONNECTING = 32, // HTTP client is doing non-blocking connect()
336 CONN_LONG_RUNNING = 64 // Long-running URI handlers
337 };
338
339 struct connection {
340 struct mg_connection mg_conn; // XXX: Must be first
341 struct ll link; // Linkage to server->active_connections
342 struct mg_server *server;
343 sock_t client_sock; // Connected client
344 struct iobuf local_iobuf;
345 struct iobuf remote_iobuf;
346 union endpoint endpoint;
347 enum endpoint_type endpoint_type;
348 time_t birth_time;
349 time_t last_activity_time;
350 char *path_info;
351 char *request;
352 int64_t num_bytes_sent; // Total number of bytes sent
353 int64_t cl; // Reply content length, for Range support
354 int request_len; // Request length, including last \r\n after last header
355 int flags; // CONN_* flags: CONN_CLOSE, CONN_SPOOL_DONE, etc
356 mg_handler_t handler; // Callback for HTTP client
357 #ifdef MONGOOSE_USE_SSL
358 SSL *ssl; // SSL descriptor
359 #endif
360 };
361
362 static void open_local_endpoint(struct connection *conn, int skip_user);
363 static void close_local_endpoint(struct connection *conn);
364
365 static const struct {
366 const char *extension;
367 size_t ext_len;
368 const char *mime_type;
369 } static_builtin_mime_types[] = {
370 {".html", 5, "text/html"},
371 {".htm", 4, "text/html"},
372 {".shtm", 5, "text/html"},
373 {".shtml", 6, "text/html"},
374 {".css", 4, "text/css"},
375 {".js", 3, "application/x-javascript"},
376 {".ico", 4, "image/x-icon"},
377 {".gif", 4, "image/gif"},
378 {".jpg", 4, "image/jpeg"},
379 {".jpeg", 5, "image/jpeg"},
380 {".png", 4, "image/png"},
381 {".svg", 4, "image/svg+xml"},
382 {".txt", 4, "text/plain"},
383 {".torrent", 8, "application/x-bittorrent"},
384 {".wav", 4, "audio/x-wav"},
385 {".mp3", 4, "audio/x-mp3"},
386 {".mid", 4, "audio/mid"},
387 {".m3u", 4, "audio/x-mpegurl"},
388 {".ogg", 4, "application/ogg"},
389 {".ram", 4, "audio/x-pn-realaudio"},
390 {".xml", 4, "text/xml"},
391 {".json", 5, "text/json"},
392 {".xslt", 5, "application/xml"},
393 {".xsl", 4, "application/xml"},
394 {".ra", 3, "audio/x-pn-realaudio"},
395 {".doc", 4, "application/msword"},
396 {".exe", 4, "application/octet-stream"},
397 {".zip", 4, "application/x-zip-compressed"},
398 {".xls", 4, "application/excel"},
399 {".tgz", 4, "application/x-tar-gz"},
400 {".tar", 4, "application/x-tar"},
401 {".gz", 3, "application/x-gunzip"},
402 {".arj", 4, "application/x-arj-compressed"},
403 {".rar", 4, "application/x-arj-compressed"},
404 {".rtf", 4, "application/rtf"},
405 {".pdf", 4, "application/pdf"},
406 {".swf", 4, "application/x-shockwave-flash"},
407 {".mpg", 4, "video/mpeg"},
408 {".webm", 5, "video/webm"},
409 {".mpeg", 5, "video/mpeg"},
410 {".mov", 4, "video/quicktime"},
411 {".mp4", 4, "video/mp4"},
412 {".m4v", 4, "video/x-m4v"},
413 {".asf", 4, "video/x-ms-asf"},
414 {".avi", 4, "video/x-msvideo"},
415 {".bmp", 4, "image/bmp"},
416 {".ttf", 4, "application/x-font-ttf"},
417 {NULL, 0, NULL}
418 };
419
420 #ifndef MONGOOSE_NO_THREADS
mg_start_thread(void * (* f)(void *),void * p)421 void *mg_start_thread(void *(*f)(void *), void *p) {
422 #ifdef _WIN32
423 return (void *) _beginthread((void (__cdecl *)(void *)) f, 0, p);
424 #else
425 pthread_t thread_id = (pthread_t) 0;
426 pthread_attr_t attr;
427
428 (void) pthread_attr_init(&attr);
429 (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
430
431 #if MONGOOSE_USE_STACK_SIZE > 1
432 (void) pthread_attr_setstacksize(&attr, MONGOOSE_USE_STACK_SIZE);
433 #endif
434
435 pthread_create(&thread_id, &attr, f, p);
436 pthread_attr_destroy(&attr);
437
438 return (void *) thread_id;
439 #endif
440 }
441 #endif // MONGOOSE_NO_THREADS
442
443 #ifdef _WIN32
444 // Encode 'path' which is assumed UTF-8 string, into UNICODE string.
445 // wbuf and wbuf_len is a target buffer and its length.
to_wchar(const char * path,wchar_t * wbuf,size_t wbuf_len)446 static void to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
447 char buf[MAX_PATH_SIZE * 2], buf2[MAX_PATH_SIZE * 2], *p;
448
449 strncpy(buf, path, sizeof(buf));
450 buf[sizeof(buf) - 1] = '\0';
451
452 // Trim trailing slashes
453 p = buf + strlen(buf) - 1;
454 while ((p > buf) && ((p[0] == '\\') || (p[0] == '/'))) *p-- = '\0';
455 //change_slashes_to_backslashes(buf);
456
457 // Convert to Unicode and back. If doubly-converted string does not
458 // match the original, something is fishy, reject.
459 memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
460 MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
461 WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
462 NULL, NULL);
463 if (strcmp(buf, buf2) != 0) {
464 wbuf[0] = L'\0';
465 }
466 }
467
mg_stat(const char * path,file_stat_t * st)468 static int mg_stat(const char *path, file_stat_t *st) {
469 wchar_t wpath[MAX_PATH_SIZE];
470 to_wchar(path, wpath, ARRAY_SIZE(wpath));
471 DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
472 return _wstati64(wpath, st);
473 }
474
mg_fopen(const char * path,const char * mode)475 static FILE *mg_fopen(const char *path, const char *mode) {
476 wchar_t wpath[MAX_PATH_SIZE], wmode[10];
477 to_wchar(path, wpath, ARRAY_SIZE(wpath));
478 to_wchar(mode, wmode, ARRAY_SIZE(wmode));
479 return _wfopen(wpath, wmode);
480 }
481
mg_open(const char * path,int flag)482 static int mg_open(const char *path, int flag) {
483 wchar_t wpath[MAX_PATH_SIZE];
484 to_wchar(path, wpath, ARRAY_SIZE(wpath));
485 return _wopen(wpath, flag);
486 }
487 #endif
488
set_close_on_exec(int fd)489 static void set_close_on_exec(int fd) {
490 #ifdef _WIN32
491 (void) SetHandleInformation((HANDLE) fd, HANDLE_FLAG_INHERIT, 0);
492 #else
493 fcntl(fd, F_SETFD, FD_CLOEXEC);
494 #endif
495 }
496
set_non_blocking_mode(sock_t sock)497 static void set_non_blocking_mode(sock_t sock) {
498 #ifdef _WIN32
499 unsigned long on = 1;
500 ioctlsocket(sock, FIONBIO, &on);
501 #else
502 int flags = fcntl(sock, F_GETFL, 0);
503 fcntl(sock, F_SETFL, flags | O_NONBLOCK);
504 #endif
505 }
506
507 // A helper function for traversing a comma separated list of values.
508 // It returns a list pointer shifted to the next value, or NULL if the end
509 // of the list found.
510 // Value is stored in val vector. If value has form "x=y", then eq_val
511 // vector is initialized to point to the "y" part, and val vector length
512 // is adjusted to point only to "x".
next_option(const char * list,struct vec * val,struct vec * eq_val)513 static const char *next_option(const char *list, struct vec *val,
514 struct vec *eq_val) {
515 if (list == NULL || *list == '\0') {
516 // End of the list
517 list = NULL;
518 } else {
519 val->ptr = list;
520 if ((list = strchr(val->ptr, ',')) != NULL) {
521 // Comma found. Store length and shift the list ptr
522 val->len = list - val->ptr;
523 list++;
524 } else {
525 // This value is the last one
526 list = val->ptr + strlen(val->ptr);
527 val->len = list - val->ptr;
528 }
529
530 if (eq_val != NULL) {
531 // Value has form "x=y", adjust pointers and lengths
532 // so that val points to "x", and eq_val points to "y".
533 eq_val->len = 0;
534 eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);
535 if (eq_val->ptr != NULL) {
536 eq_val->ptr++; // Skip over '=' character
537 eq_val->len = val->ptr + val->len - eq_val->ptr;
538 val->len = (eq_val->ptr - val->ptr) - 1;
539 }
540 }
541 }
542
543 return list;
544 }
545
spool(struct iobuf * io,const void * buf,int len)546 static int spool(struct iobuf *io, const void *buf, int len) {
547 static const double mult = 1.2;
548 char *p = NULL;
549 int new_len = 0;
550
551 assert(io->len >= 0);
552 assert(io->len <= io->size);
553
554 //DBG(("1. %d %d %d", len, io->len, io->size));
555 if (len <= 0) {
556 } else if ((new_len = io->len + len) < io->size) {
557 memcpy(io->buf + io->len, buf, len);
558 io->len = new_len;
559 } else if ((p = (char *) realloc(io->buf, (int) (new_len * mult))) != NULL) {
560 io->buf = p;
561 memcpy(io->buf + io->len, buf, len);
562 io->len = new_len;
563 io->size = (int) (new_len * mult);
564 } else {
565 len = 0;
566 }
567 //DBG(("%d %d %d", len, io->len, io->size));
568
569 return len;
570 }
571
572 // Like snprintf(), but never returns negative value, or a value
573 // that is larger than a supplied buffer.
mg_vsnprintf(char * buf,size_t buflen,const char * fmt,va_list ap)574 static int mg_vsnprintf(char *buf, size_t buflen, const char *fmt, va_list ap) {
575 int n;
576 if (buflen < 1) return 0;
577 n = vsnprintf(buf, buflen, fmt, ap);
578 if (n < 0) {
579 n = 0;
580 } else if (n >= (int) buflen) {
581 n = (int) buflen - 1;
582 }
583 buf[n] = '\0';
584 return n;
585 }
586
mg_snprintf(char * buf,size_t buflen,const char * fmt,...)587 static int mg_snprintf(char *buf, size_t buflen, const char *fmt, ...) {
588 va_list ap;
589 int n;
590 va_start(ap, fmt);
591 n = mg_vsnprintf(buf, buflen, fmt, ap);
592 va_end(ap);
593 return n;
594 }
595
596 // Check whether full request is buffered. Return:
597 // -1 if request is malformed
598 // 0 if request is not yet fully buffered
599 // >0 actual request length, including last \r\n\r\n
get_request_len(const char * s,int buf_len)600 static int get_request_len(const char *s, int buf_len) {
601 const unsigned char *buf = (unsigned char *) s;
602 int i;
603
604 for (i = 0; i < buf_len; i++) {
605 // Control characters are not allowed but >=128 are.
606 // Abort scan as soon as one malformed character is found.
607 if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
608 return -1;
609 } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
610 return i + 2;
611 } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
612 buf[i + 2] == '\n') {
613 return i + 3;
614 }
615 }
616
617 return 0;
618 }
619
620 // Skip the characters until one of the delimiters characters found.
621 // 0-terminate resulting word. Skip the rest of the delimiters if any.
622 // Advance pointer to buffer to the next word. Return found 0-terminated word.
skip(char ** buf,const char * delimiters)623 static char *skip(char **buf, const char *delimiters) {
624 char *p, *begin_word, *end_word, *end_delimiters;
625
626 begin_word = *buf;
627 end_word = begin_word + strcspn(begin_word, delimiters);
628 end_delimiters = end_word + strspn(end_word, delimiters);
629
630 for (p = end_word; p < end_delimiters; p++) {
631 *p = '\0';
632 }
633
634 *buf = end_delimiters;
635
636 return begin_word;
637 }
638
639 // Parse HTTP headers from the given buffer, advance buffer to the point
640 // where parsing stopped.
parse_http_headers(char ** buf,struct mg_connection * ri)641 static void parse_http_headers(char **buf, struct mg_connection *ri) {
642 size_t i;
643
644 for (i = 0; i < ARRAY_SIZE(ri->http_headers); i++) {
645 ri->http_headers[i].name = skip(buf, ": ");
646 ri->http_headers[i].value = skip(buf, "\r\n");
647 if (ri->http_headers[i].name[0] == '\0')
648 break;
649 ri->num_headers = i + 1;
650 }
651 }
652
status_code_to_str(int status_code)653 static const char *status_code_to_str(int status_code) {
654 switch (status_code) {
655 case 200: return "OK";
656 case 201: return "Created";
657 case 204: return "No Content";
658 case 301: return "Moved Permanently";
659 case 302: return "Found";
660 case 304: return "Not Modified";
661 case 400: return "Bad Request";
662 case 403: return "Forbidden";
663 case 404: return "Not Found";
664 case 405: return "Method Not Allowed";
665 case 409: return "Conflict";
666 case 411: return "Length Required";
667 case 413: return "Request Entity Too Large";
668 case 415: return "Unsupported Media Type";
669 case 423: return "Locked";
670 case 500: return "Server Error";
671 case 501: return "Not Implemented";
672 default: return "Server Error";
673 }
674 }
675
send_http_error(struct connection * conn,int code,const char * fmt,...)676 static void send_http_error(struct connection *conn, int code,
677 const char *fmt, ...) {
678 const char *message = status_code_to_str(code);
679 const char *rewrites = conn->server->config_options[URL_REWRITES];
680 char headers[200], body[200];
681 struct vec a, b;
682 va_list ap;
683 int body_len, headers_len, match_code;
684
685 conn->mg_conn.status_code = code;
686
687 // Invoke error handler if it is set
688 if (conn->server->error_handler != NULL &&
689 conn->server->error_handler(&conn->mg_conn) == MG_ERROR_PROCESSED) {
690 close_local_endpoint(conn);
691 return;
692 }
693
694 // Handle error code rewrites
695 while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
696 if ((match_code = atoi(a.ptr)) > 0 && match_code == code) {
697 conn->mg_conn.status_code = 302;
698 mg_printf(&conn->mg_conn, "HTTP/1.1 %d Moved\r\n"
699 "Location: %.*s?code=%d&orig_uri=%s\r\n\r\n",
700 conn->mg_conn.status_code, b.len, b.ptr, code,
701 conn->mg_conn.uri);
702 close_local_endpoint(conn);
703 return;
704 }
705 }
706
707 body_len = mg_snprintf(body, sizeof(body), "%d %s\n", code, message);
708 if (fmt != NULL) {
709 va_start(ap, fmt);
710 body_len += mg_vsnprintf(body + body_len, sizeof(body) - body_len, fmt, ap);
711 va_end(ap);
712 }
713 if (code >= 300 && code <= 399) {
714 // 3xx errors do not have body
715 body_len = 0;
716 }
717 headers_len = mg_snprintf(headers, sizeof(headers),
718 "HTTP/1.1 %d %s\r\nContent-Length: %d\r\n"
719 "Content-Type: text/plain\r\n\r\n",
720 code, message, body_len);
721 spool(&conn->remote_iobuf, headers, headers_len);
722 spool(&conn->remote_iobuf, body, body_len);
723 close_local_endpoint(conn); // This will write to the log file
724 }
725
726 // Print message to buffer. If buffer is large enough to hold the message,
727 // return buffer. If buffer is to small, allocate large enough buffer on heap,
728 // and return allocated buffer.
alloc_vprintf(char ** buf,size_t size,const char * fmt,va_list ap)729 static int alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap) {
730 va_list ap_copy;
731 int len;
732
733 // Windows is not standard-compliant, and vsnprintf() returns -1 if
734 // buffer is too small. Also, older versions of msvcrt.dll do not have
735 // _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
736 // Therefore, we make two passes: on first pass, get required message length.
737 // On second pass, actually print the message.
738 va_copy(ap_copy, ap);
739 len = vsnprintf(NULL, 0, fmt, ap_copy);
740
741 if (len > (int) size &&
742 (size = len + 1) > 0 &&
743 (*buf = (char *) malloc(size)) == NULL) {
744 len = -1; // Allocation failed, mark failure
745 } else {
746 va_copy(ap_copy, ap);
747 vsnprintf(*buf, size, fmt, ap_copy);
748 }
749
750 return len;
751 }
752
write_chunk(struct connection * conn,const char * buf,int len)753 static void write_chunk(struct connection *conn, const char *buf, int len) {
754 char chunk_size[50];
755 int n = mg_snprintf(chunk_size, sizeof(chunk_size), "%X\r\n", len);
756 spool(&conn->remote_iobuf, chunk_size, n);
757 spool(&conn->remote_iobuf, buf, len);
758 spool(&conn->remote_iobuf, "\r\n", 2);
759 }
760
mg_vprintf(struct mg_connection * conn,const char * fmt,va_list ap,int chunked)761 int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap,
762 int chunked) {
763 char mem[IOBUF_SIZE], *buf = mem;
764 int len;
765
766 if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
767 if (chunked) {
768 write_chunk((struct connection *) conn, buf, len);
769 } else {
770 len = mg_write(conn, buf, (size_t) len);
771 }
772 }
773 if (buf != mem && buf != NULL) {
774 free(buf);
775 }
776
777 return len;
778 }
779
mg_printf(struct mg_connection * conn,const char * fmt,...)780 int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
781 int len;
782 va_list ap;
783 va_start(ap, fmt);
784 len = mg_vprintf(conn, fmt, ap, 0);
785 va_end(ap);
786 return len;
787 }
788
mg_socketpair(sock_t sp[2])789 static int mg_socketpair(sock_t sp[2]) {
790 struct sockaddr_in sa;
791 sock_t sock, ret = -1;
792 socklen_t len = sizeof(sa);
793
794 sp[0] = sp[1] = INVALID_SOCKET;
795
796 (void) memset(&sa, 0, sizeof(sa));
797 sa.sin_family = AF_INET;
798 sa.sin_port = htons(0);
799 sa.sin_addr.s_addr = htonl(0x7f000001);
800
801 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) != INVALID_SOCKET &&
802 !bind(sock, (struct sockaddr *) &sa, len) &&
803 !listen(sock, 1) &&
804 !getsockname(sock, (struct sockaddr *) &sa, &len) &&
805 (sp[0] = socket(AF_INET, SOCK_STREAM, 6)) != -1 &&
806 !connect(sp[0], (struct sockaddr *) &sa, len) &&
807 (sp[1] = accept(sock,(struct sockaddr *) &sa, &len)) != INVALID_SOCKET) {
808 set_close_on_exec(sp[0]);
809 set_close_on_exec(sp[1]);
810 ret = 0;
811 } else {
812 if (sp[0] != INVALID_SOCKET) closesocket(sp[0]);
813 if (sp[1] != INVALID_SOCKET) closesocket(sp[1]);
814 sp[0] = sp[1] = INVALID_SOCKET;
815 }
816 closesocket(sock);
817
818 return ret;
819 }
820
is_error(int n)821 static int is_error(int n) {
822 return n == 0 ||
823 (n < 0 && errno != EINTR && errno != EINPROGRESS &&
824 errno != EAGAIN && errno != EWOULDBLOCK
825 #ifdef _WIN32
826 && WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK
827 #endif
828 );
829 }
830
discard_leading_iobuf_bytes(struct iobuf * io,int n)831 static void discard_leading_iobuf_bytes(struct iobuf *io, int n) {
832 if (n >= 0 && n <= io->len) {
833 memmove(io->buf, io->buf + n, io->len - n);
834 io->len -= n;
835 }
836 }
837
838 #ifndef MONGOOSE_NO_CGI
839 #ifdef _WIN32
840 struct threadparam {
841 sock_t s;
842 HANDLE hPipe;
843 };
844
wait_until_ready(sock_t sock,int for_read)845 static int wait_until_ready(sock_t sock, int for_read) {
846 fd_set set;
847 FD_ZERO(&set);
848 FD_SET(sock, &set);
849 select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0);
850 return 1;
851 }
852
push_to_stdin(void * arg)853 static void *push_to_stdin(void *arg) {
854 struct threadparam *tp = arg;
855 int n, sent, stop = 0;
856 DWORD k;
857 char buf[IOBUF_SIZE];
858
859 while (!stop && wait_until_ready(tp->s, 1) &&
860 (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
861 if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
862 for (sent = 0; !stop && sent < n; sent += k) {
863 if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
864 }
865 }
866 DBG(("%s", "FORWARED EVERYTHING TO CGI"));
867 CloseHandle(tp->hPipe);
868 free(tp);
869 _endthread();
870 return NULL;
871 }
872
pull_from_stdout(void * arg)873 static void *pull_from_stdout(void *arg) {
874 struct threadparam *tp = arg;
875 int k, stop = 0;
876 DWORD n, sent;
877 char buf[IOBUF_SIZE];
878
879 while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
880 for (sent = 0; !stop && sent < n; sent += k) {
881 if (wait_until_ready(tp->s, 0) &&
882 (k = send(tp->s, buf + sent, n - sent, 0)) <= 0) stop = 1;
883 }
884 }
885 DBG(("%s", "EOF FROM CGI"));
886 CloseHandle(tp->hPipe);
887 shutdown(tp->s, 2); // Without this, IO thread may get truncated data
888 closesocket(tp->s);
889 free(tp);
890 _endthread();
891 return NULL;
892 }
893
spawn_stdio_thread(sock_t sock,HANDLE hPipe,void * (* func)(void *))894 static void spawn_stdio_thread(sock_t sock, HANDLE hPipe,
895 void *(*func)(void *)) {
896 struct threadparam *tp = malloc(sizeof(*tp));
897 if (tp != NULL) {
898 tp->s = sock;
899 tp->hPipe = hPipe;
900 mg_start_thread(func, tp);
901 }
902 }
903
abs_path(const char * utf8_path,char * abs_path,size_t len)904 static void abs_path(const char *utf8_path, char *abs_path, size_t len) {
905 wchar_t buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE];
906 to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
907 GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
908 WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
909 }
910
start_process(char * interp,const char * cmd,const char * env,const char * envp[],const char * dir,sock_t sock)911 static pid_t start_process(char *interp, const char *cmd, const char *env,
912 const char *envp[], const char *dir, sock_t sock) {
913 STARTUPINFOW si = {0};
914 PROCESS_INFORMATION pi = {0};
915 HANDLE a[2], b[2], me = GetCurrentProcess();
916 wchar_t wcmd[MAX_PATH_SIZE], full_dir[MAX_PATH_SIZE];
917 char buf[MAX_PATH_SIZE], buf4[MAX_PATH_SIZE], buf5[MAX_PATH_SIZE],
918 cmdline[MAX_PATH_SIZE], *p;
919 DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
920 FILE *fp;
921
922 si.cb = sizeof(si);
923 si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
924 si.wShowWindow = SW_HIDE;
925 si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
926
927 CreatePipe(&a[0], &a[1], NULL, 0);
928 CreatePipe(&b[0], &b[1], NULL, 0);
929 DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
930 DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
931
932 if (interp == NULL && (fp = fopen(cmd, "r")) != NULL) {
933 buf[0] = buf[1] = '\0';
934 fgets(buf, sizeof(buf), fp);
935 buf[sizeof(buf) - 1] = '\0';
936 if (buf[0] == '#' && buf[1] == '!') {
937 interp = buf + 2;
938 for (p = interp + strlen(interp);
939 isspace(* (uint8_t *) p) && p > interp; p--) *p = '\0';
940 }
941 fclose(fp);
942 }
943
944 if (interp != NULL) {
945 abs_path(interp, buf4, ARRAY_SIZE(buf4));
946 interp = buf4;
947 }
948 abs_path(dir, buf5, ARRAY_SIZE(buf5));
949 to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
950 mg_snprintf(cmdline, sizeof(cmdline), "%s%s\"%s\"",
951 interp ? interp : "", interp ? " " : "", cmd);
952 to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
953
954 if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
955 (void *) env, full_dir, &si, &pi) != 0) {
956 spawn_stdio_thread(sock, a[1], push_to_stdin);
957 spawn_stdio_thread(sock, b[0], pull_from_stdout);
958 } else {
959 CloseHandle(a[1]);
960 CloseHandle(b[0]);
961 closesocket(sock);
962 }
963 DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
964
965 CloseHandle(si.hStdOutput);
966 CloseHandle(si.hStdInput);
967 CloseHandle(a[0]);
968 CloseHandle(b[1]);
969 CloseHandle(pi.hThread);
970 CloseHandle(pi.hProcess);
971
972 int retint = (int)pi.hProcess;
973
974 return retint;
975 }
976 #else
start_process(const char * interp,const char * cmd,const char * env,const char * envp[],const char * dir,sock_t sock)977 static pid_t start_process(const char *interp, const char *cmd, const char *env,
978 const char *envp[], const char *dir, sock_t sock) {
979 char buf[16384];
980 pid_t pid = fork();
981 (void) env;
982
983 if (pid == 0) {
984 if (chdir(dir) == -1) {
985 exit(EXIT_FAILURE);
986 }
987 (void) dup2(sock, 0);
988 (void) dup2(sock, 1);
989 closesocket(sock);
990
991 // After exec, all signal handlers are restored to their default values,
992 // with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
993 // implementation, SIGCHLD's handler will leave unchanged after exec
994 // if it was set to be ignored. Restore it to default action.
995 signal(SIGCHLD, SIG_DFL);
996
997 if (interp == NULL) {
998 execle(cmd, cmd, NULL, envp);
999 } else {
1000 execle(interp, interp, cmd, NULL, envp);
1001 }
1002 memset(buf, 0, sizeof(buf));
1003 snprintf(buf, sizeof(buf), "Server Error: %s %s: %s", (interp == NULL ? "" : interp), cmd, strerror(errno));
1004 send(1, buf, strlen(buf), 0);
1005 exit(EXIT_FAILURE); // exec call failed
1006 }
1007
1008 return pid;
1009 }
1010 #endif // _WIN32
1011
1012 // This structure helps to create an environment for the spawned CGI program.
1013 // Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
1014 // last element must be NULL.
1015 // However, on Windows there is a requirement that all these VARIABLE=VALUE\0
1016 // strings must reside in a contiguous buffer. The end of the buffer is
1017 // marked by two '\0' characters.
1018 // We satisfy both worlds: we create an envp array (which is vars), all
1019 // entries are actually pointers inside buf.
1020 struct cgi_env_block {
1021 struct mg_connection *conn;
1022 char buf[CGI_ENVIRONMENT_SIZE]; // Environment buffer
1023 const char *vars[MAX_CGI_ENVIR_VARS]; // char *envp[]
1024 int len; // Space taken
1025 int nvars; // Number of variables in envp[]
1026 };
1027
1028 // Append VARIABLE=VALUE\0 string to the buffer, and add a respective
1029 // pointer into the vars array.
addenv(struct cgi_env_block * block,const char * fmt,...)1030 static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {
1031 int n, space;
1032 char *added;
1033 va_list ap;
1034
1035 // Calculate how much space is left in the buffer
1036 space = sizeof(block->buf) - block->len - 2;
1037 assert(space >= 0);
1038
1039 // Make a pointer to the free space int the buffer
1040 added = block->buf + block->len;
1041
1042 // Copy VARIABLE=VALUE\0 string into the free space
1043 va_start(ap, fmt);
1044 n = mg_vsnprintf(added, (size_t) space, fmt, ap);
1045 va_end(ap);
1046
1047 // Make sure we do not overflow buffer and the envp array
1048 if (n > 0 && n + 1 < space &&
1049 block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
1050 // Append a pointer to the added string into the envp array
1051 block->vars[block->nvars++] = added;
1052 // Bump up used length counter. Include \0 terminator
1053 block->len += n + 1;
1054 }
1055
1056 return added;
1057 }
1058
addenv2(struct cgi_env_block * blk,const char * name)1059 static void addenv2(struct cgi_env_block *blk, const char *name) {
1060 const char *s;
1061 if ((s = getenv(name)) != NULL) addenv(blk, "%s=%s", name, s);
1062 }
1063
prepare_cgi_environment(struct connection * conn,const char * prog,struct cgi_env_block * blk)1064 static void prepare_cgi_environment(struct connection *conn,
1065 const char *prog,
1066 struct cgi_env_block *blk) {
1067 struct mg_connection *ri = &conn->mg_conn;
1068 const char *s, *slash;
1069 char *p, **opts = conn->server->config_options;
1070 int i;
1071
1072 blk->len = blk->nvars = 0;
1073 blk->conn = ri;
1074
1075 addenv(blk, "SERVER_NAME=%s", opts[AUTH_DOMAIN]);
1076 addenv(blk, "SERVER_ROOT=%s", opts[DOCUMENT_ROOT]);
1077 addenv(blk, "DOCUMENT_ROOT=%s", opts[DOCUMENT_ROOT]);
1078 addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MONGOOSE_VERSION);
1079
1080 // Prepare the environment block
1081 addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
1082 addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
1083 addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP
1084
1085 // TODO(lsm): fix this for IPv6 case
1086 //addenv(blk, "SERVER_PORT=%d", ri->remote_port);
1087
1088 addenv(blk, "REQUEST_METHOD=%s", ri->request_method);
1089 addenv(blk, "REMOTE_ADDR=%s", ri->remote_ip);
1090 addenv(blk, "REMOTE_PORT=%d", ri->remote_port);
1091 addenv(blk, "REQUEST_URI=%s%s%s", ri->uri,
1092 ri->query_string == NULL ? "" : "?",
1093 ri->query_string == NULL ? "" : ri->query_string);
1094
1095 // SCRIPT_NAME
1096 if (conn->path_info != NULL) {
1097 addenv(blk, "SCRIPT_NAME=%.*s",
1098 (int) (strlen(ri->uri) - strlen(conn->path_info)), ri->uri);
1099 addenv(blk, "PATH_INFO=%s", conn->path_info);
1100 } else {
1101 s = strrchr(prog, '/');
1102 slash = strrchr(ri->uri, '/');
1103 addenv(blk, "SCRIPT_NAME=%.*s%s",
1104 slash == NULL ? 0 : (int) (slash - ri->uri), ri->uri,
1105 s == NULL ? prog : s);
1106 }
1107
1108 addenv(blk, "SCRIPT_FILENAME=%s", prog);
1109 addenv(blk, "PATH_TRANSLATED=%s", prog);
1110 #ifdef MONGOOSE_USE_SSL
1111 addenv(blk, "HTTPS=%s", conn->ssl != NULL ? "on" : "off");
1112 #else
1113 addenv(blk, "HTTPS=%s", "off");
1114 #endif
1115
1116 if ((s = mg_get_header(ri, "Content-Type")) != NULL)
1117 addenv(blk, "CONTENT_TYPE=%s", s);
1118
1119 if (ri->query_string != NULL)
1120 addenv(blk, "QUERY_STRING=%s", ri->query_string);
1121
1122 if ((s = mg_get_header(ri, "Content-Length")) != NULL)
1123 addenv(blk, "CONTENT_LENGTH=%s", s);
1124
1125 addenv2(blk, "PATH");
1126 addenv2(blk, "PERLLIB");
1127 addenv2(blk, ENV_EXPORT_TO_CGI);
1128
1129 #if defined(_WIN32)
1130 addenv2(blk, "COMSPEC");
1131 addenv2(blk, "SYSTEMROOT");
1132 addenv2(blk, "SystemDrive");
1133 addenv2(blk, "ProgramFiles");
1134 addenv2(blk, "ProgramFiles(x86)");
1135 addenv2(blk, "CommonProgramFiles(x86)");
1136 #else
1137 addenv2(blk, "LD_LIBRARY_PATH");
1138 #endif // _WIN32
1139
1140 // Add all headers as HTTP_* variables
1141 for (i = 0; i < ri->num_headers; i++) {
1142 p = addenv(blk, "HTTP_%s=%s",
1143 ri->http_headers[i].name, ri->http_headers[i].value);
1144
1145 // Convert variable name into uppercase, and change - to _
1146 for (; *p != '=' && *p != '\0'; p++) {
1147 if (*p == '-')
1148 *p = '_';
1149 *p = (char) toupper(* (unsigned char *) p);
1150 }
1151 }
1152
1153 blk->vars[blk->nvars++] = NULL;
1154 blk->buf[blk->len++] = '\0';
1155
1156 assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
1157 assert(blk->len > 0);
1158 assert(blk->len < (int) sizeof(blk->buf));
1159 }
1160
1161 static const char cgi_status[] = "HTTP/1.1 200 OK\r\n";
1162
open_cgi_endpoint(struct connection * conn,const char * prog)1163 static void open_cgi_endpoint(struct connection *conn, const char *prog) {
1164 struct cgi_env_block blk;
1165 char dir[MAX_PATH_SIZE], *p;
1166 sock_t fds[2];
1167
1168 prepare_cgi_environment(conn, prog, &blk);
1169 // CGI must be executed in its own directory. 'dir' must point to the
1170 // directory containing executable program, 'p' must point to the
1171 // executable program name relative to 'dir'.
1172 if ((p = strrchr(prog, '/')) == NULL) {
1173 mg_snprintf(dir, sizeof(dir), "%s", ".");
1174 } else {
1175 mg_snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
1176 }
1177
1178 // Try to create socketpair in a loop until success. mg_socketpair()
1179 // can be interrupted by a signal and fail.
1180 // TODO(lsm): use sigaction to restart interrupted syscall
1181 do {
1182 mg_socketpair(fds);
1183 } while (fds[0] == INVALID_SOCKET);
1184
1185 if (start_process(conn->server->config_options[CGI_INTERPRETER],
1186 prog, blk.buf, blk.vars, dir, fds[1]) > 0) {
1187 conn->endpoint_type = EP_CGI;
1188 conn->endpoint.cgi_sock = fds[0];
1189 spool(&conn->remote_iobuf, cgi_status, sizeof(cgi_status) - 1);
1190 conn->mg_conn.status_code = 200;
1191 conn->flags |= CONN_BUFFER;
1192 } else {
1193 closesocket(fds[0]);
1194 send_http_error(conn, 500, "start_process(%s) failed", prog);
1195 }
1196
1197 #ifndef _WIN32
1198 closesocket(fds[1]); // On Windows, CGI stdio thread closes that socket
1199 #endif
1200 }
1201
read_from_cgi(struct connection * conn)1202 static void read_from_cgi(struct connection *conn) {
1203 struct iobuf *io = &conn->remote_iobuf;
1204 char buf[IOBUF_SIZE], buf2[sizeof(buf)], *s = buf2;
1205 const char *status = "500";
1206 struct mg_connection c;
1207 int len, s_len = sizeof(cgi_status) - 1,
1208 n = recv(conn->endpoint.cgi_sock, buf, sizeof(buf), 0);
1209
1210 DBG(("%p %d", conn, n));
1211 if (is_error(n)) {
1212 close_local_endpoint(conn);
1213 } else if (n > 0) {
1214 spool(&conn->remote_iobuf, buf, n);
1215 if (conn->flags & CONN_BUFFER) {
1216 len = get_request_len(io->buf + s_len, io->len - s_len);
1217 if (len == 0) return;
1218 if (len > 0) {
1219 memset(&c, 0, sizeof(c));
1220 memcpy(buf2, io->buf + s_len, len);
1221 buf2[len - 1] = '\0';
1222 parse_http_headers(&s, &c);
1223 if (mg_get_header(&c, "Location") != NULL) {
1224 status = "302";
1225 } else if ((status = (char *) mg_get_header(&c, "Status")) == NULL) {
1226 status = "200";
1227 }
1228 }
1229 memcpy(io->buf + 9, status, 3);
1230 conn->mg_conn.status_code = atoi(status);
1231 conn->flags &= ~CONN_BUFFER;
1232 }
1233 }
1234 }
1235
forward_post_data(struct connection * conn)1236 static void forward_post_data(struct connection *conn) {
1237 struct iobuf *io = &conn->local_iobuf;
1238 int n = send(conn->endpoint.cgi_sock, io->buf, io->len, 0);
1239 discard_leading_iobuf_bytes(io, n);
1240 }
1241 #endif // !MONGOOSE_NO_CGI
1242
1243 const char *mg_open_msg = "";
1244
1245 // 'sa' must be an initialized address to bind to
open_listening_socket(union socket_address * sa)1246 static sock_t open_listening_socket(union socket_address *sa) {
1247 socklen_t len = sizeof(*sa);
1248 sock_t on = 1, sock = INVALID_SOCKET;
1249 int ret1 = 0, ret2 = 0, ret3 = 0;
1250 static char message[500];
1251 mg_open_msg = "";
1252 sock = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
1253 if (sock == INVALID_SOCKET) {
1254 mg_open_msg = "Cannot open socket";
1255 goto ret_err;
1256 }
1257 #ifdef __WIN32__
1258 ret1 = setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char *) &on, sizeof(on));
1259 #else
1260 ret1 = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on));
1261 #endif
1262 if (ret1 != 0) {
1263 snprintf(message, sizeof(message), "set socket error %d:", ret1);
1264 mg_open_msg = message;
1265 closesocket(sock);
1266 sock = INVALID_SOCKET;
1267 goto ret_err;
1268 } else {
1269 snprintf(message, sizeof(message), "set socket: %d:", ret1);
1270 mg_open_msg = message;
1271 }
1272
1273 ret2 = bind(sock,
1274 &sa->sa,
1275 sa->sa.sa_family == AF_INET ?
1276 sizeof(sa->sin) : sizeof(sa->sa));
1277 if (ret2 != 0) {
1278 snprintf(message, sizeof(message), "bind error %d:", ret2);
1279 mg_open_msg = message;
1280 closesocket(sock);
1281 sock = INVALID_SOCKET;
1282 goto ret_err;
1283 }
1284 ret3 = listen(sock, SOMAXCONN);
1285 if (ret3 != 0) {
1286 snprintf(message, sizeof(message), "listen error %d:", ret2);
1287 mg_open_msg = message;
1288 closesocket(sock);
1289 sock = INVALID_SOCKET;
1290 goto ret_err;
1291 }
1292 // everything passed
1293 set_non_blocking_mode(sock);
1294 (void) getsockname(sock, &sa->sa, &len);
1295 snprintf(message, sizeof(message),
1296 "Socket %d, options %d, bind %d, listen %d",
1297 sock, ret1, ret2, ret3);
1298 mg_open_msg = message;
1299
1300 ret_err:
1301 return sock;
1302
1303 }
1304
mg_strdup(const char * str)1305 static char *mg_strdup(const char *str) {
1306 char *copy = (char *) malloc(strlen(str) + 1);
1307 if (copy != NULL) {
1308 strcpy(copy, str);
1309 }
1310 return copy;
1311 }
1312
isbyte(int n)1313 static int isbyte(int n) {
1314 return n >= 0 && n <= 255;
1315 }
1316
parse_net(const char * spec,uint32_t * net,uint32_t * mask)1317 static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
1318 int n, a, b, c, d, slash = 32, len = 0;
1319
1320 if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
1321 sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
1322 isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&
1323 slash >= 0 && slash < 33) {
1324 len = n;
1325 *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
1326 *mask = slash ? 0xffffffffU << (32 - slash) : 0;
1327 }
1328
1329 return len;
1330 }
1331
1332 // Verify given socket address against the ACL.
1333 // Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
check_acl(const char * acl,uint32_t remote_ip)1334 static int check_acl(const char *acl, uint32_t remote_ip) {
1335 int allowed, flag;
1336 uint32_t net, mask;
1337 struct vec vec;
1338
1339 // If any ACL is set, deny by default
1340 allowed = acl == NULL ? '+' : '-';
1341
1342 while ((acl = next_option(acl, &vec, NULL)) != NULL) {
1343 flag = vec.ptr[0];
1344 if ((flag != '+' && flag != '-') ||
1345 parse_net(&vec.ptr[1], &net, &mask) == 0) {
1346 return -1;
1347 }
1348
1349 if (net == (remote_ip & mask)) {
1350 allowed = flag;
1351 }
1352 }
1353
1354 return allowed == '+';
1355 }
1356
sockaddr_to_string(char * buf,size_t len,const union socket_address * usa)1357 static void sockaddr_to_string(char *buf, size_t len,
1358 const union socket_address *usa) {
1359 buf[0] = '\0';
1360 #if defined(MONGOOSE_USE_IPV6)
1361 inet_ntop(usa->sa.sa_family, usa->sa.sa_family == AF_INET ?
1362 (void *) &usa->sin.sin_addr :
1363 (void *) &usa->sin6.sin6_addr, buf, len);
1364 #elif defined(_WIN32)
1365 // Only Windoze Vista (and newer) have inet_ntop()
1366 strncpy(buf, inet_ntoa(usa->sin.sin_addr), len);
1367 #else
1368 inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, len);
1369 #endif
1370 }
1371
accept_new_connection(struct mg_server * server)1372 static struct connection *accept_new_connection(struct mg_server *server) {
1373 union socket_address sa;
1374 socklen_t len = sizeof(sa);
1375 sock_t sock = INVALID_SOCKET;
1376 struct connection *conn = NULL;
1377
1378 // NOTE(lsm): on Windows, sock is always > FD_SETSIZE
1379 if ((sock = accept(server->listening_sock, &sa.sa, &len)) == INVALID_SOCKET) {
1380 } else if (!check_acl(server->config_options[ACCESS_CONTROL_LIST],
1381 ntohl(* (uint32_t *) &sa.sin.sin_addr))) {
1382 // NOTE(lsm): check_acl doesn't work for IPv6
1383 closesocket(sock);
1384 } else if ((conn = (struct connection *) calloc(1, sizeof(*conn))) == NULL) {
1385 closesocket(sock);
1386 #ifdef MONGOOSE_USE_SSL
1387 } else if (server->ssl_ctx != NULL &&
1388 ((conn->ssl = SSL_new(server->ssl_ctx)) == NULL ||
1389 SSL_set_fd(conn->ssl, sock) != 1)) {
1390 DBG(("SSL error"));
1391 closesocket(sock);
1392 free(conn);
1393 conn = NULL;
1394 #endif
1395 } else {
1396 set_close_on_exec(sock);
1397 set_non_blocking_mode(sock);
1398 conn->server = server;
1399 conn->client_sock = sock;
1400 sockaddr_to_string(conn->mg_conn.remote_ip,
1401 sizeof(conn->mg_conn.remote_ip), &sa);
1402 conn->mg_conn.remote_port = ntohs(sa.sin.sin_port);
1403 conn->mg_conn.server_param = server->server_data;
1404 conn->mg_conn.local_ip = server->local_ip;
1405 conn->mg_conn.local_port = ntohs(server->lsa.sin.sin_port);
1406 LINKED_LIST_ADD_TO_FRONT(&server->active_connections, &conn->link);
1407 DBG(("added conn %p", conn));
1408 }
1409
1410 return conn;
1411 }
1412
close_conn(struct connection * conn)1413 static void close_conn(struct connection *conn) {
1414 LINKED_LIST_REMOVE(&conn->link);
1415 closesocket(conn->client_sock);
1416 close_local_endpoint(conn);
1417 DBG(("%p %d %d", conn, conn->flags, conn->endpoint_type));
1418 free(conn->request); // It's OK to free(NULL), ditto below
1419 free(conn->path_info);
1420 free(conn->remote_iobuf.buf);
1421 free(conn->local_iobuf.buf);
1422 #ifdef MONGOOSE_USE_SSL
1423 if (conn->ssl != NULL) SSL_free(conn->ssl);
1424 #endif
1425 free(conn);
1426 }
1427
1428 // Protect against directory disclosure attack by removing '..',
1429 // excessive '/' and '\' characters
remove_double_dots_and_double_slashes(char * s)1430 static void remove_double_dots_and_double_slashes(char *s) {
1431 char *p = s;
1432
1433 while (*s != '\0') {
1434 *p++ = *s++;
1435 if (s[-1] == '/' || s[-1] == '\\') {
1436 // Skip all following slashes, backslashes and double-dots
1437 while (s[0] != '\0') {
1438 if (s[0] == '/' || s[0] == '\\') { s++; }
1439 else if (s[0] == '.' && s[1] == '.') { s += 2; }
1440 else { break; }
1441 }
1442 }
1443 }
1444 *p = '\0';
1445 }
1446
mg_url_decode(const char * src,int src_len,char * dst,int dst_len,int is_form_url_encoded)1447 int mg_url_decode(const char *src, int src_len, char *dst,
1448 int dst_len, int is_form_url_encoded) {
1449 int i, j, a, b;
1450 #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
1451
1452 for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
1453 if (src[i] == '%' && i < src_len - 2 &&
1454 isxdigit(* (const unsigned char *) (src + i + 1)) &&
1455 isxdigit(* (const unsigned char *) (src + i + 2))) {
1456 a = tolower(* (const unsigned char *) (src + i + 1));
1457 b = tolower(* (const unsigned char *) (src + i + 2));
1458 dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
1459 i += 2;
1460 } else if (is_form_url_encoded && src[i] == '+') {
1461 dst[j] = ' ';
1462 } else {
1463 dst[j] = src[i];
1464 }
1465 }
1466
1467 dst[j] = '\0'; // Null-terminate the destination
1468
1469 return i >= src_len ? j : -1;
1470 }
1471
is_valid_http_method(const char * method)1472 static int is_valid_http_method(const char *method) {
1473 return !strcmp(method, "GET") || !strcmp(method, "POST") ||
1474 !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||
1475 !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||
1476 !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND")
1477 || !strcmp(method, "MKCOL");
1478 }
1479
1480 // Parse HTTP request, fill in mg_request structure.
1481 // This function modifies the buffer by NUL-terminating
1482 // HTTP request components, header names and header values.
1483 // Note that len must point to the last \n of HTTP headers.
parse_http_message(char * buf,int len,struct mg_connection * ri)1484 static int parse_http_message(char *buf, int len, struct mg_connection *ri) {
1485 int is_request, n;
1486
1487 // Reset the connection. Make sure that we don't touch fields that are
1488 // set elsewhere: remote_ip, remote_port, server_param
1489 ri->request_method = ri->uri = ri->http_version = ri->query_string = NULL;
1490 ri->num_headers = ri->status_code = ri->is_websocket = ri->content_len = 0;
1491
1492 buf[len - 1] = '\0';
1493
1494 // RFC says that all initial whitespaces should be ingored
1495 while (*buf != '\0' && isspace(* (unsigned char *) buf)) {
1496 buf++;
1497 }
1498 ri->request_method = skip(&buf, " ");
1499 ri->uri = skip(&buf, " ");
1500 ri->http_version = skip(&buf, "\r\n");
1501
1502 // HTTP message could be either HTTP request or HTTP response, e.g.
1503 // "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..."
1504 is_request = is_valid_http_method(ri->request_method);
1505 if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) ||
1506 (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
1507 len = -1;
1508 } else {
1509 if (is_request) {
1510 ri->http_version += 5;
1511 }
1512 parse_http_headers(&buf, ri);
1513
1514 if ((ri->query_string = strchr(ri->uri, '?')) != NULL) {
1515 *(char *) ri->query_string++ = '\0';
1516 }
1517 n = (int) strlen(ri->uri);
1518 mg_url_decode(ri->uri, n, (char *) ri->uri, n + 1, 0);
1519 remove_double_dots_and_double_slashes((char *) ri->uri);
1520 }
1521
1522 return len;
1523 }
1524
lowercase(const char * s)1525 static int lowercase(const char *s) {
1526 return tolower(* (const unsigned char *) s);
1527 }
1528
mg_strcasecmp(const char * s1,const char * s2)1529 static int mg_strcasecmp(const char *s1, const char *s2) {
1530 int diff;
1531
1532 do {
1533 diff = lowercase(s1++) - lowercase(s2++);
1534 } while (diff == 0 && s1[-1] != '\0');
1535
1536 return diff;
1537 }
1538
mg_strncasecmp(const char * s1,const char * s2,size_t len)1539 static int mg_strncasecmp(const char *s1, const char *s2, size_t len) {
1540 int diff = 0;
1541
1542 if (len > 0)
1543 do {
1544 diff = lowercase(s1++) - lowercase(s2++);
1545 } while (diff == 0 && s1[-1] != '\0' && --len > 0);
1546
1547 return diff;
1548 }
1549
1550 // Return HTTP header value, or NULL if not found.
mg_get_header(const struct mg_connection * ri,const char * s)1551 const char *mg_get_header(const struct mg_connection *ri, const char *s) {
1552 int i;
1553
1554 for (i = 0; i < ri->num_headers; i++)
1555 if (!mg_strcasecmp(s, ri->http_headers[i].name))
1556 return ri->http_headers[i].value;
1557
1558 return NULL;
1559 }
1560
1561 #ifndef MONGOOSE_NO_FILESYSTEM
1562 // Perform case-insensitive match of string against pattern
match_prefix(const char * pattern,int pattern_len,const char * str)1563 static int match_prefix(const char *pattern, int pattern_len, const char *str) {
1564 const char *or_str;
1565 int len, res, i = 0, j = 0;
1566
1567 if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
1568 res = match_prefix(pattern, or_str - pattern, str);
1569 return res > 0 ? res :
1570 match_prefix(or_str + 1, (pattern + pattern_len) - (or_str + 1), str);
1571 }
1572
1573 for (; i < pattern_len; i++, j++) {
1574 if (pattern[i] == '?' && str[j] != '\0') {
1575 continue;
1576 } else if (pattern[i] == '$') {
1577 return str[j] == '\0' ? j : -1;
1578 } else if (pattern[i] == '*') {
1579 i++;
1580 if (pattern[i] == '*') {
1581 i++;
1582 len = (int) strlen(str + j);
1583 } else {
1584 len = (int) strcspn(str + j, "/");
1585 }
1586 if (i == pattern_len) {
1587 return j + len;
1588 }
1589 do {
1590 res = match_prefix(pattern + i, pattern_len - i, str + j + len);
1591 } while (res == -1 && len-- > 0);
1592 return res == -1 ? -1 : j + res + len;
1593 } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
1594 return -1;
1595 }
1596 }
1597 return j;
1598 }
1599
must_hide_file(struct connection * conn,const char * path)1600 static int must_hide_file(struct connection *conn, const char *path) {
1601 const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
1602 const char *pattern = conn->server->config_options[HIDE_FILES_PATTERN];
1603 return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 ||
1604 (pattern != NULL && match_prefix(pattern, strlen(pattern), path) > 0);
1605 }
1606
1607 // Return 1 if real file has been found, 0 otherwise
convert_uri_to_file_name(struct connection * conn,char * buf,size_t buf_len,file_stat_t * st)1608 static int convert_uri_to_file_name(struct connection *conn, char *buf,
1609 size_t buf_len, file_stat_t *st) {
1610 struct vec a, b;
1611 const char *rewrites = conn->server->config_options[URL_REWRITES];
1612 const char *root = conn->server->config_options[DOCUMENT_ROOT];
1613 #ifndef MONGOOSE_NO_CGI
1614 const char *cgi_pat = conn->server->config_options[CGI_PATTERN];
1615 char *p;
1616 #endif
1617 const char *uri = conn->mg_conn.uri;
1618 int match_len;
1619
1620 // No filesystem access
1621 if (root == NULL) return 0;
1622
1623 // Handle URL rewrites
1624 mg_snprintf(buf, buf_len, "%s%s", root, uri);
1625 while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
1626 if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
1627 mg_snprintf(buf, buf_len, "%.*s%s", (int) b.len, b.ptr, uri + match_len);
1628 break;
1629 }
1630 }
1631
1632 if (stat(buf, st) == 0) return 1;
1633
1634 #ifndef MONGOOSE_NO_CGI
1635 // Support PATH_INFO for CGI scripts.
1636 for (p = buf + strlen(root) + 2; *p != '\0'; p++) {
1637 if (*p == '/') {
1638 *p = '\0';
1639 if (match_prefix(cgi_pat, strlen(cgi_pat), buf) > 0 && !stat(buf, st)) {
1640 DBG(("!!!! [%s]", buf));
1641 *p = '/';
1642 conn->path_info = mg_strdup(p);
1643 *p = '\0';
1644 return 1;
1645 }
1646 *p = '/';
1647 }
1648 }
1649 #endif
1650
1651 return 0;
1652 }
1653 #endif // MONGOOSE_NO_FILESYSTEM
1654
should_keep_alive(const struct mg_connection * conn)1655 static int should_keep_alive(const struct mg_connection *conn) {
1656 const char *method = conn->request_method;
1657 const char *http_version = conn->http_version;
1658 const char *header = mg_get_header(conn, "Connection");
1659 return method != NULL && (!strcmp(method, "GET") ||
1660 ((struct connection *) conn)->endpoint_type == EP_USER) &&
1661 ((header != NULL && !mg_strcasecmp(header, "keep-alive")) ||
1662 (header == NULL && http_version && !strcmp(http_version, "1.1")));
1663 }
1664
mg_write(struct mg_connection * c,const void * buf,int len)1665 int mg_write(struct mg_connection *c, const void *buf, int len) {
1666 return spool(&((struct connection *) c)->remote_iobuf, buf, len);
1667 }
1668
mg_send_status(struct mg_connection * c,int status)1669 void mg_send_status(struct mg_connection *c, int status) {
1670 if (c->status_code == 0) {
1671 c->status_code = status;
1672 mg_printf(c, "HTTP/1.1 %d %s\r\n", status, status_code_to_str(status));
1673 }
1674 }
1675
mg_send_header(struct mg_connection * c,const char * name,const char * v)1676 void mg_send_header(struct mg_connection *c, const char *name, const char *v) {
1677 if (c->status_code == 0) {
1678 c->status_code = 200;
1679 mg_printf(c, "HTTP/1.1 %d %s\r\n", 200, status_code_to_str(200));
1680 }
1681 mg_printf(c, "%s: %s\r\n", name, v);
1682 }
1683
terminate_headers(struct mg_connection * c)1684 static void terminate_headers(struct mg_connection *c) {
1685 struct connection *conn = (struct connection *) c;
1686 if (!(conn->flags & CONN_HEADERS_SENT)) {
1687 mg_send_header(c, "Transfer-Encoding", "chunked");
1688 mg_write(c, "\r\n", 2);
1689 conn->flags |= CONN_HEADERS_SENT;
1690 }
1691 }
1692
mg_send_data(struct mg_connection * c,const void * data,int data_len)1693 void mg_send_data(struct mg_connection *c, const void *data, int data_len) {
1694 terminate_headers(c);
1695 write_chunk((struct connection *) c, (const char *) data, data_len);
1696 }
1697
mg_printf_data(struct mg_connection * c,const char * fmt,...)1698 void mg_printf_data(struct mg_connection *c, const char *fmt, ...) {
1699 va_list ap;
1700
1701 terminate_headers(c);
1702
1703 va_start(ap, fmt);
1704 mg_vprintf(c, fmt, ap, 1);
1705 va_end(ap);
1706 }
1707
1708 #if !defined(NO_WEBSOCKET) || !defined(MONGOOSE_NO_AUTH)
is_big_endian(void)1709 static int is_big_endian(void) {
1710 static const int n = 1;
1711 return ((char *) &n)[0] == 0;
1712 }
1713 #endif
1714
1715 #ifndef MONGOOSE_NO_WEBSOCKET
1716 // START OF SHA-1 code
1717 // Copyright(c) By Steve Reid <steve@edmweb.com>
1718 #define SHA1HANDSOFF
1719 #if defined(__sun)
1720 #include "solarisfixes.h"
1721 #endif
1722
1723 union char64long16 { unsigned char c[64]; uint32_t l[16]; };
1724
1725 #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
1726
blk0(union char64long16 * block,int i)1727 static uint32_t blk0(union char64long16 *block, int i) {
1728 // Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN
1729 if (!is_big_endian()) {
1730 block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
1731 (rol(block->l[i], 8) & 0x00FF00FF);
1732 }
1733 return block->l[i];
1734 }
1735
1736 #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
1737 ^block->l[(i+2)&15]^block->l[i&15],1))
1738 #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30);
1739 #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
1740 #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
1741 #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
1742 #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
1743
1744 typedef struct {
1745 uint32_t state[5];
1746 uint32_t count[2];
1747 unsigned char buffer[64];
1748 } SHA1_CTX;
1749
SHA1Transform(uint32_t state[5],const unsigned char buffer[64])1750 static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) {
1751 uint32_t a, b, c, d, e;
1752 union char64long16 block[1];
1753
1754 memcpy(block, buffer, 64);
1755 a = state[0];
1756 b = state[1];
1757 c = state[2];
1758 d = state[3];
1759 e = state[4];
1760 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);
1761 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);
1762 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);
1763 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);
1764 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);
1765 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);
1766 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);
1767 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);
1768 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);
1769 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);
1770 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);
1771 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);
1772 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);
1773 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);
1774 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);
1775 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);
1776 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);
1777 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);
1778 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);
1779 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);
1780 state[0] += a;
1781 state[1] += b;
1782 state[2] += c;
1783 state[3] += d;
1784 state[4] += e;
1785 // Erase working structures. The order of operations is important,
1786 // used to ensure that compiler doesn't optimize those out.
1787 memset(block, 0, sizeof(block));
1788 a = b = c = d = e = 0;
1789 (void) a; (void) b; (void) c; (void) d; (void) e;
1790 }
1791
SHA1Init(SHA1_CTX * context)1792 static void SHA1Init(SHA1_CTX* context) {
1793 context->state[0] = 0x67452301;
1794 context->state[1] = 0xEFCDAB89;
1795 context->state[2] = 0x98BADCFE;
1796 context->state[3] = 0x10325476;
1797 context->state[4] = 0xC3D2E1F0;
1798 context->count[0] = context->count[1] = 0;
1799 }
1800
SHA1Update(SHA1_CTX * context,const unsigned char * data,uint32_t len)1801 static void SHA1Update(SHA1_CTX* context, const unsigned char* data,
1802 uint32_t len) {
1803 uint32_t i, j;
1804
1805 j = context->count[0];
1806 if ((context->count[0] += len << 3) < j)
1807 context->count[1]++;
1808 context->count[1] += (len>>29);
1809 j = (j >> 3) & 63;
1810 if ((j + len) > 63) {
1811 memcpy(&context->buffer[j], data, (i = 64-j));
1812 SHA1Transform(context->state, context->buffer);
1813 for ( ; i + 63 < len; i += 64) {
1814 SHA1Transform(context->state, &data[i]);
1815 }
1816 j = 0;
1817 }
1818 else i = 0;
1819 memcpy(&context->buffer[j], &data[i], len - i);
1820 }
1821
SHA1Final(unsigned char digest[20],SHA1_CTX * context)1822 static void SHA1Final(unsigned char digest[20], SHA1_CTX* context) {
1823 unsigned i;
1824 unsigned char finalcount[8], c;
1825
1826 for (i = 0; i < 8; i++) {
1827 finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
1828 >> ((3-(i & 3)) * 8) ) & 255);
1829 }
1830 c = 0200;
1831 SHA1Update(context, &c, 1);
1832 while ((context->count[0] & 504) != 448) {
1833 c = 0000;
1834 SHA1Update(context, &c, 1);
1835 }
1836 SHA1Update(context, finalcount, 8);
1837 for (i = 0; i < 20; i++) {
1838 digest[i] = (unsigned char)
1839 ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
1840 }
1841 memset(context, '\0', sizeof(*context));
1842 memset(&finalcount, '\0', sizeof(finalcount));
1843 }
1844 // END OF SHA1 CODE
1845
base64_encode(const unsigned char * src,int src_len,char * dst)1846 static void base64_encode(const unsigned char *src, int src_len, char *dst) {
1847 static const char *b64 =
1848 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1849 int i, j, a, b, c;
1850
1851 for (i = j = 0; i < src_len; i += 3) {
1852 a = src[i];
1853 b = i + 1 >= src_len ? 0 : src[i + 1];
1854 c = i + 2 >= src_len ? 0 : src[i + 2];
1855
1856 dst[j++] = b64[a >> 2];
1857 dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
1858 if (i + 1 < src_len) {
1859 dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
1860 }
1861 if (i + 2 < src_len) {
1862 dst[j++] = b64[c & 63];
1863 }
1864 }
1865 while (j % 4 != 0) {
1866 dst[j++] = '=';
1867 }
1868 dst[j++] = '\0';
1869 }
1870
send_websocket_handshake(struct mg_connection * conn,const char * key)1871 static void send_websocket_handshake(struct mg_connection *conn,
1872 const char *key) {
1873 static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
1874 char buf[500], sha[20], b64_sha[sizeof(sha) * 2];
1875 SHA1_CTX sha_ctx;
1876
1877 mg_snprintf(buf, sizeof(buf), "%s%s", key, magic);
1878 SHA1Init(&sha_ctx);
1879 SHA1Update(&sha_ctx, (unsigned char *) buf, strlen(buf));
1880 SHA1Final((unsigned char *) sha, &sha_ctx);
1881 base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
1882 mg_snprintf(buf, sizeof(buf), "%s%s%s",
1883 "HTTP/1.1 101 Switching Protocols\r\n"
1884 "Upgrade: websocket\r\n"
1885 "Connection: Upgrade\r\n"
1886 "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n");
1887
1888 mg_write(conn, buf, strlen(buf));
1889 }
1890
deliver_websocket_frame(struct connection * conn)1891 static int deliver_websocket_frame(struct connection *conn) {
1892 // Having buf unsigned char * is important, as it is used below in arithmetic
1893 unsigned char *buf = (unsigned char *) conn->local_iobuf.buf;
1894 int i, len, buf_len = conn->local_iobuf.len, frame_len = 0,
1895 mask_len = 0, header_len = 0, data_len = 0, buffered = 0;
1896
1897 if (buf_len >= 2) {
1898 len = buf[1] & 127;
1899 mask_len = buf[1] & 128 ? 4 : 0;
1900 if (len < 126 && buf_len >= mask_len) {
1901 data_len = len;
1902 header_len = 2 + mask_len;
1903 } else if (len == 126 && buf_len >= 4 + mask_len) {
1904 header_len = 4 + mask_len;
1905 data_len = ((((int) buf[2]) << 8) + buf[3]);
1906 } else if (buf_len >= 10 + mask_len) {
1907 header_len = 10 + mask_len;
1908 data_len = (int) (((uint64_t) htonl(* (uint32_t *) &buf[2])) << 32) +
1909 htonl(* (uint32_t *) &buf[6]);
1910 }
1911 }
1912
1913 frame_len = header_len + data_len;
1914 buffered = frame_len > 0 && frame_len <= buf_len;
1915
1916 if (buffered) {
1917 conn->mg_conn.content_len = data_len;
1918 conn->mg_conn.content = (char *) buf + header_len;
1919 conn->mg_conn.wsbits = buf[0];
1920
1921 // Apply mask if necessary
1922 if (mask_len > 0) {
1923 for (i = 0; i < data_len; i++) {
1924 buf[i + header_len] ^= (buf + header_len - mask_len)[i % 4];
1925 }
1926 }
1927
1928 // Call the handler and remove frame from the iobuf
1929 if (conn->server->request_handler(&conn->mg_conn) == MG_CLIENT_CLOSE) {
1930 conn->flags |= CONN_SPOOL_DONE;
1931 }
1932 discard_leading_iobuf_bytes(&conn->local_iobuf, frame_len);
1933 }
1934
1935 return buffered;
1936 }
1937
mg_websocket_write(struct mg_connection * conn,int opcode,const char * data,size_t data_len)1938 int mg_websocket_write(struct mg_connection* conn, int opcode,
1939 const char *data, size_t data_len) {
1940 unsigned char *copy;
1941 size_t copy_len = 0;
1942 int retval = -1;
1943
1944 if ((copy = (unsigned char *) malloc(data_len + 10)) == NULL) {
1945 return -1;
1946 }
1947
1948 copy[0] = 0x80 + (opcode & 0x0f);
1949
1950 // Frame format: http://tools.ietf.org/html/rfc6455#section-5.2
1951 if (data_len < 126) {
1952 // Inline 7-bit length field
1953 copy[1] = data_len;
1954 memcpy(copy + 2, data, data_len);
1955 copy_len = 2 + data_len;
1956 } else if (data_len <= 0xFFFF) {
1957 // 16-bit length field
1958 copy[1] = 126;
1959 * (uint16_t *) (copy + 2) = (uint16_t) htons((uint16_t) data_len);
1960 memcpy(copy + 4, data, data_len);
1961 copy_len = 4 + data_len;
1962 } else {
1963 // 64-bit length field
1964 copy[1] = 127;
1965 * (uint32_t *) (copy + 2) = (uint32_t)
1966 htonl((uint32_t) ((uint64_t) data_len >> 32));
1967 * (uint32_t *) (copy + 6) = (uint32_t) htonl(data_len & 0xffffffff);
1968 memcpy(copy + 10, data, data_len);
1969 copy_len = 10 + data_len;
1970 }
1971
1972 if (copy_len > 0) {
1973 retval = mg_write(conn, copy, copy_len);
1974 }
1975 free(copy);
1976
1977 return retval;
1978 }
1979
send_websocket_handshake_if_requested(struct mg_connection * conn)1980 static void send_websocket_handshake_if_requested(struct mg_connection *conn) {
1981 const char *ver = mg_get_header(conn, "Sec-WebSocket-Version"),
1982 *key = mg_get_header(conn, "Sec-WebSocket-Key");
1983 if (ver != NULL && key != NULL) {
1984 conn->is_websocket = 1;
1985 send_websocket_handshake(conn, key);
1986 }
1987 }
1988
ping_idle_websocket_connection(struct connection * conn,time_t t)1989 static void ping_idle_websocket_connection(struct connection *conn, time_t t) {
1990 if (t - conn->last_activity_time > MONGOOSE_USE_WEBSOCKET_PING_INTERVAL) {
1991 mg_websocket_write(&conn->mg_conn, 0x9, "", 0);
1992 }
1993 }
1994 #else
1995 #define ping_idle_websocket_connection(conn, t)
1996 #endif // !MONGOOSE_NO_WEBSOCKET
1997
write_terminating_chunk(struct connection * conn)1998 static void write_terminating_chunk(struct connection *conn) {
1999 mg_write(&conn->mg_conn, "0\r\n\r\n", 5);
2000 }
2001
call_request_handler(struct connection * conn)2002 static int call_request_handler(struct connection *conn) {
2003 int result;
2004 conn->mg_conn.content = conn->local_iobuf.buf;
2005 switch ((result = conn->server->request_handler(&conn->mg_conn))) {
2006 case MG_REQUEST_CALL_AGAIN: conn->flags |= CONN_LONG_RUNNING; break;
2007 case MG_REQUEST_NOT_PROCESSED: break;
2008 default:
2009 if (conn->flags & CONN_HEADERS_SENT) {
2010 write_terminating_chunk(conn);
2011 }
2012 close_local_endpoint(conn);
2013 break;
2014 }
2015 return result;
2016 }
2017
callback_http_client_on_connect(struct connection * conn)2018 static void callback_http_client_on_connect(struct connection *conn) {
2019 int ok = 1, ret;
2020 socklen_t len = sizeof(ok);
2021
2022 conn->flags &= ~CONN_CONNECTING;
2023 ret = getsockopt(conn->client_sock, SOL_SOCKET, SO_ERROR, (char *) &ok, &len);
2024 #ifdef MONGOOSE_USE_SSL
2025 if (ret == 0 && ok == 0 && conn->ssl != NULL) {
2026 int res = SSL_connect(conn->ssl), ssl_err = SSL_get_error(conn->ssl, res);
2027 //DBG(("%p res %d %d", conn, res, ssl_err));
2028 if (res == 1) {
2029 conn->flags = CONN_SSL_HANDS_SHAKEN;
2030 } else if (res == 0 || ssl_err == 2 || ssl_err == 3) {
2031 conn->flags |= CONN_CONNECTING;
2032 return; // Call us again
2033 } else {
2034 ok = 1;
2035 }
2036 }
2037 #endif
2038 conn->mg_conn.status_code =
2039 (ret == 0 && ok == 0) ? MG_CONNECT_SUCCESS : MG_CONNECT_FAILURE;
2040 if (conn->handler(&conn->mg_conn) || ok != 0) {
2041 conn->flags |= CONN_CLOSE;
2042 }
2043 }
2044
write_to_socket(struct connection * conn)2045 static void write_to_socket(struct connection *conn) {
2046 struct iobuf *io = &conn->remote_iobuf;
2047 int n = 0;
2048
2049 if (conn->endpoint_type == EP_CLIENT && conn->flags & CONN_CONNECTING) {
2050 callback_http_client_on_connect(conn);
2051 return;
2052 }
2053
2054 #ifdef MONGOOSE_USE_SSL
2055 if (conn->ssl != NULL) {
2056 n = SSL_write(conn->ssl, io->buf, io->len);
2057 } else
2058 #endif
2059 { n = send(conn->client_sock, io->buf, io->len, 0); }
2060
2061 DBG(("%p Written %d of %d(%d): [%.*s ...]",
2062 conn, n, io->len, io->size, io->len < 40 ? io->len : 40, io->buf));
2063
2064 if (is_error(n)) {
2065 conn->flags |= CONN_CLOSE;
2066 } else if (n > 0) {
2067 discard_leading_iobuf_bytes(io, n);
2068 conn->num_bytes_sent += n;
2069 }
2070
2071 if (io->len == 0 && conn->flags & CONN_SPOOL_DONE) {
2072 conn->flags |= CONN_CLOSE;
2073 }
2074 }
2075
mg_get_mime_type(const char * path,const char * default_mime_type)2076 const char *mg_get_mime_type(const char *path, const char *default_mime_type) {
2077 const char *ext;
2078 size_t i, path_len;
2079
2080 path_len = strlen(path);
2081
2082 for (i = 0; static_builtin_mime_types[i].extension != NULL; i++) {
2083 ext = path + (path_len - static_builtin_mime_types[i].ext_len);
2084 if (path_len > static_builtin_mime_types[i].ext_len &&
2085 mg_strcasecmp(ext, static_builtin_mime_types[i].extension) == 0) {
2086 return static_builtin_mime_types[i].mime_type;
2087 }
2088 }
2089
2090 return default_mime_type;
2091 }
2092
2093 #ifndef MONGOOSE_NO_FILESYSTEM
2094 // Convert month to the month number. Return -1 on error, or month number
get_month_index(const char * s)2095 static int get_month_index(const char *s) {
2096 static const char *month_names[] = {
2097 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2098 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2099 };
2100 int i;
2101
2102 for (i = 0; i < (int) ARRAY_SIZE(month_names); i++)
2103 if (!strcmp(s, month_names[i]))
2104 return i;
2105
2106 return -1;
2107 }
2108
num_leap_years(int year)2109 static int num_leap_years(int year) {
2110 return year / 4 - year / 100 + year / 400;
2111 }
2112
2113 // Parse UTC date-time string, and return the corresponding time_t value.
parse_date_string(const char * datetime)2114 static time_t parse_date_string(const char *datetime) {
2115 static const unsigned short days_before_month[] = {
2116 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
2117 };
2118 char month_str[32];
2119 int second, minute, hour, day, month, year, leap_days, days;
2120 time_t result = (time_t) 0;
2121
2122 if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d",
2123 &day, month_str, &year, &hour, &minute, &second) == 6) ||
2124 (sscanf(datetime, "%d %3s %d %d:%d:%d",
2125 &day, month_str, &year, &hour, &minute, &second) == 6) ||
2126 (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",
2127 &day, month_str, &year, &hour, &minute, &second) == 6) ||
2128 (sscanf(datetime, "%d-%3s-%d %d:%d:%d",
2129 &day, month_str, &year, &hour, &minute, &second) == 6)) &&
2130 year > 1970 &&
2131 (month = get_month_index(month_str)) != -1) {
2132 leap_days = num_leap_years(year) - num_leap_years(1970);
2133 year -= 1970;
2134 days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
2135 result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
2136 }
2137
2138 return result;
2139 }
2140
2141 // Look at the "path" extension and figure what mime type it has.
2142 // Store mime type in the vector.
get_mime_type(const struct mg_server * server,const char * path,struct vec * vec)2143 static void get_mime_type(const struct mg_server *server, const char *path,
2144 struct vec *vec) {
2145 struct vec ext_vec, mime_vec;
2146 const char *list, *ext;
2147 size_t path_len;
2148
2149 path_len = strlen(path);
2150
2151 // Scan user-defined mime types first, in case user wants to
2152 // override default mime types.
2153 list = server->config_options[EXTRA_MIME_TYPES];
2154 while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
2155 // ext now points to the path suffix
2156 ext = path + path_len - ext_vec.len;
2157 if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
2158 *vec = mime_vec;
2159 return;
2160 }
2161 }
2162
2163 vec->ptr = mg_get_mime_type(path, "text/plain");
2164 vec->len = strlen(vec->ptr);
2165 }
2166
suggest_connection_header(const struct mg_connection * conn)2167 static const char *suggest_connection_header(const struct mg_connection *conn) {
2168 return should_keep_alive(conn) ? "keep-alive" : "close";
2169 }
2170
construct_etag(char * buf,size_t buf_len,const file_stat_t * st)2171 static void construct_etag(char *buf, size_t buf_len, const file_stat_t *st) {
2172 mg_snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"",
2173 (unsigned long) st->st_mtime, (int64_t) st->st_size);
2174 }
2175
2176 // Return True if we should reply 304 Not Modified.
is_not_modified(const struct connection * conn,const file_stat_t * stp)2177 static int is_not_modified(const struct connection *conn,
2178 const file_stat_t *stp) {
2179 char etag[64];
2180 const char *ims = mg_get_header(&conn->mg_conn, "If-Modified-Since");
2181 const char *inm = mg_get_header(&conn->mg_conn, "If-None-Match");
2182 construct_etag(etag, sizeof(etag), stp);
2183 return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
2184 (ims != NULL && stp->st_mtime <= parse_date_string(ims));
2185 }
2186
2187 // For given directory path, substitute it to valid index file.
2188 // Return 0 if index file has been found, -1 if not found.
2189 // If the file is found, it's stats is returned in stp.
find_index_file(struct connection * conn,char * path,size_t path_len,file_stat_t * stp)2190 static int find_index_file(struct connection *conn, char *path,
2191 size_t path_len, file_stat_t *stp) {
2192 const char *list = conn->server->config_options[INDEX_FILES];
2193 file_stat_t st;
2194 struct vec filename_vec;
2195 size_t n = strlen(path), found = 0;
2196
2197 // The 'path' given to us points to the directory. Remove all trailing
2198 // directory separator characters from the end of the path, and
2199 // then append single directory separator character.
2200 while (n > 0 && path[n - 1] == '/') {
2201 n--;
2202 }
2203 path[n] = '/';
2204
2205 // Traverse index files list. For each entry, append it to the given
2206 // path and see if the file exists. If it exists, break the loop
2207 while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
2208
2209 // Ignore too long entries that may overflow path buffer
2210 if (filename_vec.len > (int) (path_len - (n + 2)))
2211 continue;
2212
2213 // Prepare full path to the index file
2214 strncpy(path + n + 1, filename_vec.ptr, filename_vec.len);
2215 path[n + 1 + filename_vec.len] = '\0';
2216
2217 //DBG(("[%s]", path));
2218
2219 // Does it exist?
2220 if (!stat(path, &st)) {
2221 // Yes it does, break the loop
2222 *stp = st;
2223 found = 1;
2224 break;
2225 }
2226 }
2227
2228 // If no index file exists, restore directory path
2229 if (!found) {
2230 path[n] = '\0';
2231 }
2232
2233 return found;
2234 }
2235
parse_range_header(const char * header,int64_t * a,int64_t * b)2236 static int parse_range_header(const char *header, int64_t *a, int64_t *b) {
2237 return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
2238 }
2239
gmt_time_string(char * buf,size_t buf_len,time_t * t)2240 static void gmt_time_string(char *buf, size_t buf_len, time_t *t) {
2241 strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
2242 }
2243
open_file_endpoint(struct connection * conn,const char * path,file_stat_t * st)2244 static void open_file_endpoint(struct connection *conn, const char *path,
2245 file_stat_t *st) {
2246 char date[64], lm[64], etag[64], range[64], headers[500];
2247 const char *msg = "OK", *hdr;
2248 time_t curtime = time(NULL);
2249 int64_t r1, r2;
2250 struct vec mime_vec;
2251 int n;
2252
2253 conn->endpoint_type = EP_FILE;
2254 set_close_on_exec(conn->endpoint.fd);
2255 conn->mg_conn.status_code = 200;
2256
2257 get_mime_type(conn->server, path, &mime_vec);
2258 conn->cl = st->st_size;
2259 range[0] = '\0';
2260
2261 // If Range: header specified, act accordingly
2262 r1 = r2 = 0;
2263 hdr = mg_get_header(&conn->mg_conn, "Range");
2264 if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 &&
2265 r1 >= 0 && r2 >= 0) {
2266 conn->mg_conn.status_code = 206;
2267 conn->cl = n == 2 ? (r2 > conn->cl ? conn->cl : r2) - r1 + 1: conn->cl - r1;
2268 mg_snprintf(range, sizeof(range), "Content-Range: bytes "
2269 "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
2270 r1, r1 + conn->cl - 1, (int64_t) st->st_size);
2271 msg = "Partial Content";
2272 lseek(conn->endpoint.fd, r1, SEEK_SET);
2273 }
2274
2275 // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
2276 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
2277 gmt_time_string(date, sizeof(date), &curtime);
2278 gmt_time_string(lm, sizeof(lm), &st->st_mtime);
2279 construct_etag(etag, sizeof(etag), st);
2280
2281 n = mg_snprintf(headers, sizeof(headers),
2282 "HTTP/1.1 %d %s\r\n"
2283 "Date: %s\r\n"
2284 "Last-Modified: %s\r\n"
2285 "Etag: %s\r\n"
2286 "Content-Type: %.*s\r\n"
2287 "Content-Length: %" INT64_FMT "\r\n"
2288 "Connection: %s\r\n"
2289 "Accept-Ranges: bytes\r\n"
2290 "%s%s\r\n",
2291 conn->mg_conn.status_code, msg, date, lm, etag,
2292 (int) mime_vec.len, mime_vec.ptr, conn->cl,
2293 suggest_connection_header(&conn->mg_conn),
2294 range, MONGOOSE_USE_EXTRA_HTTP_HEADERS);
2295 spool(&conn->remote_iobuf, headers, n);
2296
2297 if (!strcmp(conn->mg_conn.request_method, "HEAD")) {
2298 conn->flags |= CONN_SPOOL_DONE;
2299 close(conn->endpoint.fd);
2300 conn->endpoint_type = EP_NONE;
2301 }
2302 }
2303
2304 #endif // MONGOOSE_NO_FILESYSTEM
2305
call_request_handler_if_data_is_buffered(struct connection * conn)2306 static void call_request_handler_if_data_is_buffered(struct connection *conn) {
2307 struct iobuf *loc = &conn->local_iobuf;
2308 struct mg_connection *c = &conn->mg_conn;
2309
2310 #ifndef MONGOOSE_NO_WEBSOCKET
2311 if (conn->mg_conn.is_websocket) {
2312 do { } while (deliver_websocket_frame(conn));
2313 } else
2314 #endif
2315 if ((size_t) loc->len >= c->content_len &&
2316 call_request_handler(conn) == MG_REQUEST_NOT_PROCESSED) {
2317 open_local_endpoint(conn, 1);
2318 }
2319 }
2320
2321 #if !defined(MONGOOSE_NO_DIRECTORY_LISTING) || !defined(MONGOOSE_NO_DAV)
2322
2323 #ifdef _WIN32
2324 struct dirent {
2325 char d_name[MAX_PATH_SIZE];
2326 };
2327
2328 typedef struct DIR {
2329 HANDLE handle;
2330 WIN32_FIND_DATAW info;
2331 struct dirent result;
2332 } DIR;
2333
2334 // Implementation of POSIX opendir/closedir/readdir for Windows.
opendir(const char * name)2335 static DIR *opendir(const char *name) {
2336 DIR *dir = NULL;
2337 wchar_t wpath[MAX_PATH_SIZE];
2338 DWORD attrs;
2339
2340 if (name == NULL) {
2341 SetLastError(ERROR_BAD_ARGUMENTS);
2342 } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) {
2343 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
2344 } else {
2345 to_wchar(name, wpath, ARRAY_SIZE(wpath));
2346 attrs = GetFileAttributesW(wpath);
2347 if (attrs != 0xFFFFFFFF &&
2348 ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
2349 (void) wcscat(wpath, L"\\*");
2350 dir->handle = FindFirstFileW(wpath, &dir->info);
2351 dir->result.d_name[0] = '\0';
2352 } else {
2353 free(dir);
2354 dir = NULL;
2355 }
2356 }
2357
2358 return dir;
2359 }
2360
closedir(DIR * dir)2361 static int closedir(DIR *dir) {
2362 int result = 0;
2363
2364 if (dir != NULL) {
2365 if (dir->handle != INVALID_HANDLE_VALUE)
2366 result = FindClose(dir->handle) ? 0 : -1;
2367
2368 free(dir);
2369 } else {
2370 result = -1;
2371 SetLastError(ERROR_BAD_ARGUMENTS);
2372 }
2373
2374 return result;
2375 }
2376
readdir(DIR * dir)2377 static struct dirent *readdir(DIR *dir) {
2378 struct dirent *result = 0;
2379
2380 if (dir) {
2381 if (dir->handle != INVALID_HANDLE_VALUE) {
2382 result = &dir->result;
2383 (void) WideCharToMultiByte(CP_UTF8, 0,
2384 dir->info.cFileName, -1, result->d_name,
2385 sizeof(result->d_name), NULL, NULL);
2386
2387 if (!FindNextFileW(dir->handle, &dir->info)) {
2388 (void) FindClose(dir->handle);
2389 dir->handle = INVALID_HANDLE_VALUE;
2390 }
2391
2392 } else {
2393 SetLastError(ERROR_FILE_NOT_FOUND);
2394 }
2395 } else {
2396 SetLastError(ERROR_BAD_ARGUMENTS);
2397 }
2398
2399 return result;
2400 }
2401 #endif // _WIN32 POSIX opendir/closedir/readdir implementation
2402
scan_directory(struct connection * conn,const char * dir,struct dir_entry ** arr)2403 static int scan_directory(struct connection *conn, const char *dir,
2404 struct dir_entry **arr) {
2405 char path[MAX_PATH_SIZE];
2406 struct dir_entry *p;
2407 struct dirent *dp;
2408 int arr_size = 0, arr_ind = 0, inc = 100;
2409 DIR *dirp;
2410
2411 *arr = NULL;
2412 if ((dirp = (opendir(dir))) == NULL) return 0;
2413
2414 while ((dp = readdir(dirp)) != NULL) {
2415 // Do not show current dir and hidden files
2416 if (!strcmp(dp->d_name, ".") ||
2417 !strcmp(dp->d_name, "..") ||
2418 must_hide_file(conn, dp->d_name)) {
2419 continue;
2420 }
2421 mg_snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
2422
2423 // Resize the array if nesessary
2424 if (arr_ind >= arr_size) {
2425 if ((p = (struct dir_entry *)
2426 realloc(*arr, (inc + arr_size) * sizeof(**arr))) != NULL) {
2427 // Memset new chunk to zero, otherwize st_mtime will have garbage which
2428 // can make strftime() segfault, see
2429 // http://code.google.com/p/mongoose/issues/detail?id=79
2430 memset(p + arr_size, 0, sizeof(**arr) * inc);
2431
2432 *arr = p;
2433 arr_size += inc;
2434 }
2435 }
2436
2437 if (arr_ind < arr_size) {
2438 (*arr)[arr_ind].conn = conn;
2439 (*arr)[arr_ind].file_name = strdup(dp->d_name);
2440 stat(path, &(*arr)[arr_ind].st);
2441 arr_ind++;
2442 }
2443 }
2444 closedir(dirp);
2445
2446 return arr_ind;
2447 }
2448
mg_url_encode(const char * src,char * dst,size_t dst_len)2449 static void mg_url_encode(const char *src, char *dst, size_t dst_len) {
2450 static const char *dont_escape = "._-$,;~()";
2451 static const char *hex = "0123456789abcdef";
2452 const char *end = dst + dst_len - 1;
2453
2454 for (; *src != '\0' && dst < end; src++, dst++) {
2455 if (isalnum(*(const unsigned char *) src) ||
2456 strchr(dont_escape, * (const unsigned char *) src) != NULL) {
2457 *dst = *src;
2458 } else if (dst + 2 < end) {
2459 dst[0] = '%';
2460 dst[1] = hex[(* (const unsigned char *) src) >> 4];
2461 dst[2] = hex[(* (const unsigned char *) src) & 0xf];
2462 dst += 2;
2463 }
2464 }
2465
2466 *dst = '\0';
2467 }
2468 #endif // !NO_DIRECTORY_LISTING || !MONGOOSE_NO_DAV
2469
2470 #ifndef MONGOOSE_NO_DIRECTORY_LISTING
2471
print_dir_entry(const struct dir_entry * de)2472 static void print_dir_entry(const struct dir_entry *de) {
2473 char size[64], mod[64], href[MAX_PATH_SIZE * 3], chunk[MAX_PATH_SIZE * 4];
2474 int64_t fsize = de->st.st_size;
2475 int is_dir = S_ISDIR(de->st.st_mode), n;
2476 const char *slash = is_dir ? "/" : "";
2477
2478 if (is_dir) {
2479 mg_snprintf(size, sizeof(size), "%s", "[DIRECTORY]");
2480 } else {
2481 // We use (signed) cast below because MSVC 6 compiler cannot
2482 // convert unsigned __int64 to double.
2483 if (fsize < 1024) {
2484 mg_snprintf(size, sizeof(size), "%d", (int) fsize);
2485 } else if (fsize < 0x100000) {
2486 mg_snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0);
2487 } else if (fsize < 0x40000000) {
2488 mg_snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576);
2489 } else {
2490 mg_snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824);
2491 }
2492 }
2493 strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&de->st.st_mtime));
2494 mg_url_encode(de->file_name, href, sizeof(href));
2495 n = mg_snprintf(chunk, sizeof(chunk),
2496 "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
2497 "<td> %s</td><td> %s</td></tr>\n",
2498 de->conn->mg_conn.uri, href, slash, de->file_name, slash,
2499 mod, size);
2500 write_chunk((struct connection *) de->conn, chunk, n);
2501 }
2502
2503 // Sort directory entries by size, or name, or modification time.
2504 // On windows, __cdecl specification is needed in case if project is built
2505 // with __stdcall convention. qsort always requires __cdels callback.
compare_dir_entries(const void * p1,const void * p2)2506 static int __cdecl compare_dir_entries(const void *p1, const void *p2) {
2507 const struct dir_entry *a = (const struct dir_entry *) p1,
2508 *b = (const struct dir_entry *) p2;
2509 const char *qs = a->conn->mg_conn.query_string ?
2510 a->conn->mg_conn.query_string : "na";
2511 int cmp_result = 0;
2512
2513 if (S_ISDIR(a->st.st_mode) && !S_ISDIR(b->st.st_mode)) {
2514 return -1; // Always put directories on top
2515 } else if (!S_ISDIR(a->st.st_mode) && S_ISDIR(b->st.st_mode)) {
2516 return 1; // Always put directories on top
2517 } else if (*qs == 'n') {
2518 cmp_result = strcmp(a->file_name, b->file_name);
2519 } else if (*qs == 's') {
2520 cmp_result = a->st.st_size == b->st.st_size ? 0 :
2521 a->st.st_size > b->st.st_size ? 1 : -1;
2522 } else if (*qs == 'd') {
2523 cmp_result = a->st.st_mtime == b->st.st_mtime ? 0 :
2524 a->st.st_mtime > b->st.st_mtime ? 1 : -1;
2525 }
2526
2527 return qs[1] == 'd' ? -cmp_result : cmp_result;
2528 }
2529
send_directory_listing(struct connection * conn,const char * dir)2530 static void send_directory_listing(struct connection *conn, const char *dir) {
2531 char buf[2000];
2532 struct dir_entry *arr = NULL;
2533 int i, num_entries, sort_direction = conn->mg_conn.query_string != NULL &&
2534 conn->mg_conn.query_string[1] == 'd' ? 'a' : 'd';
2535
2536 conn->mg_conn.status_code = 200;
2537 mg_snprintf(buf, sizeof(buf), "%s",
2538 "HTTP/1.1 200 OK\r\n"
2539 "Transfer-Encoding: Chunked\r\n"
2540 "Content-Type: text/html; charset=utf-8\r\n\r\n");
2541 spool(&conn->remote_iobuf, buf, strlen(buf));
2542
2543 mg_snprintf(buf, sizeof(buf),
2544 "<html><head><title>Index of %s</title>"
2545 "<style>th {text-align: left;}</style></head>"
2546 "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
2547 "<tr><th><a href=\"?n%c\">Name</a></th>"
2548 "<th><a href=\"?d%c\">Modified</a></th>"
2549 "<th><a href=\"?s%c\">Size</a></th></tr>"
2550 "<tr><td colspan=\"3\"><hr></td></tr>",
2551 conn->mg_conn.uri, conn->mg_conn.uri,
2552 sort_direction, sort_direction, sort_direction);
2553 write_chunk(conn, buf, strlen(buf));
2554
2555 num_entries = scan_directory(conn, dir, &arr);
2556 qsort(arr, num_entries, sizeof(arr[0]), compare_dir_entries);
2557 for (i = 0; i < num_entries; i++) {
2558 print_dir_entry(&arr[i]);
2559 free(arr[i].file_name);
2560 }
2561 free(arr);
2562
2563 write_terminating_chunk(conn);
2564 close_local_endpoint(conn);
2565 }
2566 #endif // MONGOOSE_NO_DIRECTORY_LISTING
2567
2568 #ifndef MONGOOSE_NO_DAV
print_props(struct connection * conn,const char * uri,file_stat_t * stp)2569 static void print_props(struct connection *conn, const char *uri,
2570 file_stat_t *stp) {
2571 char mtime[64], buf[MAX_PATH_SIZE + 200];
2572
2573 gmt_time_string(mtime, sizeof(mtime), &stp->st_mtime);
2574 mg_snprintf(buf, sizeof(buf),
2575 "<d:response>"
2576 "<d:href>%s</d:href>"
2577 "<d:propstat>"
2578 "<d:prop>"
2579 "<d:resourcetype>%s</d:resourcetype>"
2580 "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
2581 "<d:getlastmodified>%s</d:getlastmodified>"
2582 "</d:prop>"
2583 "<d:status>HTTP/1.1 200 OK</d:status>"
2584 "</d:propstat>"
2585 "</d:response>\n",
2586 uri, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "",
2587 (int64_t) stp->st_size, mtime);
2588 spool(&conn->remote_iobuf, buf, strlen(buf));
2589 }
2590
handle_propfind(struct connection * conn,const char * path,file_stat_t * stp)2591 static void handle_propfind(struct connection *conn, const char *path,
2592 file_stat_t *stp) {
2593 static const char header[] = "HTTP/1.1 207 Multi-Status\r\n"
2594 "Connection: close\r\n"
2595 "Content-Type: text/xml; charset=utf-8\r\n\r\n"
2596 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
2597 "<d:multistatus xmlns:d='DAV:'>\n";
2598 static const char footer[] = "</d:multistatus>";
2599 const char *depth = mg_get_header(&conn->mg_conn, "Depth"),
2600 *list_dir = conn->server->config_options[ENABLE_DIRECTORY_LISTING];
2601
2602 conn->mg_conn.status_code = 207;
2603 spool(&conn->remote_iobuf, header, sizeof(header) - 1);
2604
2605 // Print properties for the requested resource itself
2606 print_props(conn, conn->mg_conn.uri, stp);
2607
2608 // If it is a directory, print directory entries too if Depth is not 0
2609 if (S_ISDIR(stp->st_mode) && !mg_strcasecmp(list_dir, "yes") &&
2610 (depth == NULL || strcmp(depth, "0") != 0)) {
2611 struct dir_entry *arr = NULL;
2612 int i, num_entries = scan_directory(conn, path, &arr);
2613
2614 for (i = 0; i < num_entries; i++) {
2615 char buf[MAX_PATH_SIZE], buf2[sizeof(buf) * 3];
2616 struct dir_entry *de = &arr[i];
2617
2618 mg_snprintf(buf, sizeof(buf), "%s%s", de->conn->mg_conn.uri,
2619 de->file_name);
2620 mg_url_encode(buf, buf2, sizeof(buf2) - 1);
2621 print_props(conn, buf, &de->st);
2622 }
2623 }
2624
2625 spool(&conn->remote_iobuf, footer, sizeof(footer) - 1);
2626 close_local_endpoint(conn);
2627 }
2628
handle_mkcol(struct connection * conn,const char * path)2629 static void handle_mkcol(struct connection *conn, const char *path) {
2630 int status_code = 500;
2631
2632 if (conn->mg_conn.content_len > 0) {
2633 status_code = 415;
2634 } else if (!mkdir(path, 0755)) {
2635 status_code = 201;
2636 } else if (errno == EEXIST) {
2637 status_code = 405;
2638 } else if (errno == EACCES) {
2639 status_code = 403;
2640 } else if (errno == ENOENT) {
2641 status_code = 409;
2642 }
2643 send_http_error(conn, status_code, NULL);
2644 }
2645
remove_directory(const char * dir)2646 static int remove_directory(const char *dir) {
2647 char path[MAX_PATH_SIZE];
2648 struct dirent *dp;
2649 file_stat_t st;
2650 DIR *dirp;
2651
2652 if ((dirp = opendir(dir)) == NULL) return 0;
2653
2654 while ((dp = readdir(dirp)) != NULL) {
2655 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue;
2656 mg_snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
2657 stat(path, &st);
2658 if (S_ISDIR(st.st_mode)) {
2659 remove_directory(path);
2660 } else {
2661 remove(path);
2662 }
2663 }
2664 closedir(dirp);
2665 rmdir(dir);
2666
2667 return 1;
2668 }
2669
handle_delete(struct connection * conn,const char * path)2670 static void handle_delete(struct connection *conn, const char *path) {
2671 file_stat_t st;
2672
2673 if (stat(path, &st) != 0) {
2674 send_http_error(conn, 404, NULL);
2675 } else if (S_ISDIR(st.st_mode)) {
2676 remove_directory(path);
2677 send_http_error(conn, 204, NULL);
2678 } else if (!remove(path) == 0) {
2679 send_http_error(conn, 204, NULL);
2680 } else {
2681 send_http_error(conn, 423, NULL);
2682 }
2683 }
2684
2685 // For a given PUT path, create all intermediate subdirectories
2686 // for given path. Return 0 if the path itself is a directory,
2687 // or -1 on error, 1 if OK.
put_dir(const char * path)2688 static int put_dir(const char *path) {
2689 char buf[MAX_PATH_SIZE];
2690 const char *s, *p;
2691 file_stat_t st;
2692
2693 // Create intermediate directories if they do not exist
2694 for (s = p = path + 1; (p = strchr(s, '/')) != NULL; s = ++p) {
2695 if (p - path >= (int) sizeof(buf)) return -1; // Buffer overflow
2696 memcpy(buf, path, p - path);
2697 buf[p - path] = '\0';
2698 if (stat(buf, &st) != 0 && mkdir(buf, 0755) != 0) return -1;
2699 if (p[1] == '\0') return 0; // Path is a directory itself
2700 }
2701
2702 return 1;
2703 }
2704
handle_put(struct connection * conn,const char * path)2705 static void handle_put(struct connection *conn, const char *path) {
2706 file_stat_t st;
2707 const char *range, *cl_hdr = mg_get_header(&conn->mg_conn, "Content-Length");
2708 int64_t r1, r2;
2709 int rc;
2710
2711 conn->mg_conn.status_code = !stat(path, &st) ? 200 : 201;
2712 if ((rc = put_dir(path)) == 0) {
2713 mg_printf(&conn->mg_conn, "HTTP/1.1 %d OK\r\n\r\n",
2714 conn->mg_conn.status_code);
2715 close_local_endpoint(conn);
2716 } else if (rc == -1) {
2717 send_http_error(conn, 500, "put_dir: %s", strerror(errno));
2718 } else if (cl_hdr == NULL) {
2719 send_http_error(conn, 411, NULL);
2720 #ifdef _WIN32
2721 //On Windows, open() is a macro with 2 params
2722 } else if ((conn->endpoint.fd =
2723 open(path, O_RDWR | O_CREAT | O_TRUNC)) < 0) {
2724 #else
2725 } else if ((conn->endpoint.fd =
2726 open(path, O_RDWR | O_CREAT | O_TRUNC, 0644)) < 0) {
2727 #endif
2728 send_http_error(conn, 500, "open(%s): %s", path, strerror(errno));
2729 } else {
2730 DBG(("PUT [%s] %d", path, conn->local_iobuf.len));
2731 conn->endpoint_type = EP_PUT;
2732 set_close_on_exec(conn->endpoint.fd);
2733 range = mg_get_header(&conn->mg_conn, "Content-Range");
2734 conn->cl = to64(cl_hdr);
2735 r1 = r2 = 0;
2736 if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
2737 conn->mg_conn.status_code = 206;
2738 lseek(conn->endpoint.fd, r1, SEEK_SET);
2739 conn->cl = r2 > r1 ? r2 - r1 + 1: conn->cl - r1;
2740 }
2741 mg_printf(&conn->mg_conn, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n",
2742 conn->mg_conn.status_code);
2743 }
2744 }
2745
forward_put_data(struct connection * conn)2746 static void forward_put_data(struct connection *conn) {
2747 struct iobuf *io = &conn->local_iobuf;
2748 int n = write(conn->endpoint.fd, io->buf, io->len);
2749 if (n > 0) {
2750 discard_leading_iobuf_bytes(io, n);
2751 conn->cl -= n;
2752 if (conn->cl <= 0) {
2753 close_local_endpoint(conn);
2754 }
2755 }
2756 }
2757 #endif // MONGOOSE_NO_DAV
2758
send_options(struct connection * conn)2759 static void send_options(struct connection *conn) {
2760 static const char reply[] = "HTTP/1.1 200 OK\r\nAllow: GET, POST, HEAD, "
2761 "CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL\r\nDAV: 1\r\n\r\n";
2762 spool(&conn->remote_iobuf, reply, sizeof(reply) - 1);
2763 conn->flags |= CONN_SPOOL_DONE;
2764 }
2765
2766 #ifndef MONGOOSE_NO_AUTH
mg_send_digest_auth_request(struct mg_connection * c)2767 void mg_send_digest_auth_request(struct mg_connection *c) {
2768 struct connection *conn = (struct connection *) c;
2769 c->status_code = 401;
2770 mg_printf(c,
2771 "HTTP/1.1 401 Unauthorized\r\n"
2772 "WWW-Authenticate: Digest qop=\"auth\", "
2773 "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
2774 conn->server->config_options[AUTH_DOMAIN],
2775 (unsigned long) time(NULL));
2776 close_local_endpoint(conn);
2777 }
2778
2779 // Use the global passwords file, if specified by auth_gpass option,
2780 // or search for .htpasswd in the requested directory.
open_auth_file(struct connection * conn,const char * path)2781 static FILE *open_auth_file(struct connection *conn, const char *path) {
2782 char name[MAX_PATH_SIZE];
2783 const char *p, *gpass = conn->server->config_options[GLOBAL_AUTH_FILE];
2784 file_stat_t st;
2785 FILE *fp = NULL;
2786
2787 if (gpass != NULL) {
2788 // Use global passwords file
2789 fp = fopen(gpass, "r");
2790 } else if (!stat(path, &st) && S_ISDIR(st.st_mode)) {
2791 mg_snprintf(name, sizeof(name), "%s%c%s", path, '/', PASSWORDS_FILE_NAME);
2792 fp = fopen(name, "r");
2793 } else {
2794 // Try to find .htpasswd in requested directory.
2795 if ((p = strrchr(path, '/')) == NULL) p = path;
2796 mg_snprintf(name, sizeof(name), "%.*s%c%s",
2797 (int) (p - path), path, '/', PASSWORDS_FILE_NAME);
2798 fp = fopen(name, "r");
2799 }
2800
2801 return fp;
2802 }
2803
2804 #if !defined(HAVE_MD5) && !defined(MONGOOSE_NO_AUTH)
2805 typedef struct MD5Context {
2806 uint32_t buf[4];
2807 uint32_t bits[2];
2808 unsigned char in[64];
2809 } MD5_CTX;
2810
byteReverse(unsigned char * buf,unsigned longs)2811 static void byteReverse(unsigned char *buf, unsigned longs) {
2812 uint32_t t;
2813
2814 // Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN
2815 if (is_big_endian()) {
2816 do {
2817 t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
2818 ((unsigned) buf[1] << 8 | buf[0]);
2819 * (uint32_t *) buf = t;
2820 buf += 4;
2821 } while (--longs);
2822 }
2823 }
2824
2825 #define F1(x, y, z) (z ^ (x & (y ^ z)))
2826 #define F2(x, y, z) F1(z, x, y)
2827 #define F3(x, y, z) (x ^ y ^ z)
2828 #define F4(x, y, z) (y ^ (x | ~z))
2829
2830 #define MD5STEP(f, w, x, y, z, data, s) \
2831 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
2832
2833 // Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
2834 // initialization constants.
MD5Init(MD5_CTX * ctx)2835 static void MD5Init(MD5_CTX *ctx) {
2836 ctx->buf[0] = 0x67452301;
2837 ctx->buf[1] = 0xefcdab89;
2838 ctx->buf[2] = 0x98badcfe;
2839 ctx->buf[3] = 0x10325476;
2840
2841 ctx->bits[0] = 0;
2842 ctx->bits[1] = 0;
2843 }
2844
MD5Transform(uint32_t buf[4],uint32_t const in[16])2845 static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
2846 register uint32_t a, b, c, d;
2847
2848 a = buf[0];
2849 b = buf[1];
2850 c = buf[2];
2851 d = buf[3];
2852
2853 MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
2854 MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
2855 MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
2856 MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
2857 MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
2858 MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
2859 MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
2860 MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
2861 MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
2862 MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
2863 MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
2864 MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
2865 MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
2866 MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
2867 MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
2868 MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
2869
2870 MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
2871 MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
2872 MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
2873 MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
2874 MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
2875 MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
2876 MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
2877 MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
2878 MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
2879 MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
2880 MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
2881 MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
2882 MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
2883 MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
2884 MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
2885 MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
2886
2887 MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
2888 MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
2889 MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
2890 MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
2891 MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
2892 MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
2893 MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
2894 MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
2895 MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
2896 MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
2897 MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
2898 MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
2899 MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
2900 MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
2901 MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
2902 MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
2903
2904 MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
2905 MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
2906 MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
2907 MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
2908 MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
2909 MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
2910 MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
2911 MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
2912 MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
2913 MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
2914 MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
2915 MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
2916 MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
2917 MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
2918 MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
2919 MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
2920
2921 buf[0] += a;
2922 buf[1] += b;
2923 buf[2] += c;
2924 buf[3] += d;
2925 }
2926
MD5Update(MD5_CTX * ctx,unsigned char const * buf,unsigned len)2927 static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) {
2928 uint32_t t;
2929
2930 t = ctx->bits[0];
2931 if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
2932 ctx->bits[1]++;
2933 ctx->bits[1] += len >> 29;
2934
2935 t = (t >> 3) & 0x3f;
2936
2937 if (t) {
2938 unsigned char *p = (unsigned char *) ctx->in + t;
2939
2940 t = 64 - t;
2941 if (len < t) {
2942 memcpy(p, buf, len);
2943 return;
2944 }
2945 memcpy(p, buf, t);
2946 byteReverse(ctx->in, 16);
2947 MD5Transform(ctx->buf, (uint32_t *) ctx->in);
2948 buf += t;
2949 len -= t;
2950 }
2951
2952 while (len >= 64) {
2953 memcpy(ctx->in, buf, 64);
2954 byteReverse(ctx->in, 16);
2955 MD5Transform(ctx->buf, (uint32_t *) ctx->in);
2956 buf += 64;
2957 len -= 64;
2958 }
2959
2960 memcpy(ctx->in, buf, len);
2961 }
2962
MD5Final(unsigned char digest[16],MD5_CTX * ctx)2963 static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) {
2964 unsigned count;
2965 unsigned char *p;
2966 uint32_t *a;
2967
2968 count = (ctx->bits[0] >> 3) & 0x3F;
2969
2970 p = ctx->in + count;
2971 *p++ = 0x80;
2972 count = 64 - 1 - count;
2973 if (count < 8) {
2974 memset(p, 0, count);
2975 byteReverse(ctx->in, 16);
2976 MD5Transform(ctx->buf, (uint32_t *) ctx->in);
2977 memset(ctx->in, 0, 56);
2978 } else {
2979 memset(p, 0, count - 8);
2980 }
2981 byteReverse(ctx->in, 14);
2982
2983 a = (uint32_t *)ctx->in;
2984 a[14] = ctx->bits[0];
2985 a[15] = ctx->bits[1];
2986
2987 MD5Transform(ctx->buf, (uint32_t *) ctx->in);
2988 byteReverse((unsigned char *) ctx->buf, 4);
2989 memcpy(digest, ctx->buf, 16);
2990 memset((char *) ctx, 0, sizeof(*ctx));
2991 }
2992 #endif // !HAVE_MD5
2993
2994
2995
2996 // Stringify binary data. Output buffer must be twice as big as input,
2997 // because each byte takes 2 bytes in string representation
bin2str(char * to,const unsigned char * p,size_t len)2998 static void bin2str(char *to, const unsigned char *p, size_t len) {
2999 static const char *hex = "0123456789abcdef";
3000
3001 for (; len--; p++) {
3002 *to++ = hex[p[0] >> 4];
3003 *to++ = hex[p[0] & 0x0f];
3004 }
3005 *to = '\0';
3006 }
3007
3008 // Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
mg_md5(char buf[33],...)3009 char *mg_md5(char buf[33], ...) {
3010 unsigned char hash[16];
3011 const char *p;
3012 va_list ap;
3013 MD5_CTX ctx;
3014
3015 MD5Init(&ctx);
3016
3017 va_start(ap, buf);
3018 while ((p = va_arg(ap, const char *)) != NULL) {
3019 MD5Update(&ctx, (const unsigned char *) p, (unsigned) strlen(p));
3020 }
3021 va_end(ap);
3022
3023 MD5Final(hash, &ctx);
3024 bin2str(buf, hash, sizeof(hash));
3025 return buf;
3026 }
3027
3028 // 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)3029 static int check_password(const char *method, const char *ha1, const char *uri,
3030 const char *nonce, const char *nc, const char *cnonce,
3031 const char *qop, const char *response) {
3032 char ha2[32 + 1], expected_response[32 + 1];
3033
3034 #if 0
3035 // Check for authentication timeout
3036 if ((unsigned long) time(NULL) - (unsigned long) to64(nonce) > 3600) {
3037 return 0;
3038 }
3039 #endif
3040
3041 mg_md5(ha2, method, ":", uri, NULL);
3042 mg_md5(expected_response, ha1, ":", nonce, ":", nc,
3043 ":", cnonce, ":", qop, ":", ha2, NULL);
3044
3045 return mg_strcasecmp(response, expected_response) == 0 ?
3046 MG_AUTH_OK : MG_AUTH_FAIL;
3047 }
3048
3049
3050 // Authorize against the opened passwords file. Return 1 if authorized.
mg_authorize_digest(struct mg_connection * c,FILE * fp)3051 int mg_authorize_digest(struct mg_connection *c, FILE *fp) {
3052 struct connection *conn = (struct connection *) c;
3053 const char *hdr;
3054 char line[256], f_user[256], ha1[256], f_domain[256], user[100], nonce[100],
3055 uri[MAX_REQUEST_SIZE], cnonce[100], resp[100], qop[100], nc[100];
3056
3057 if (c == NULL || fp == NULL) return 0;
3058 if ((hdr = mg_get_header(c, "Authorization")) == NULL ||
3059 mg_strncasecmp(hdr, "Digest ", 7) != 0) return 0;
3060 if (!mg_parse_header(hdr, "username", user, sizeof(user))) return 0;
3061 if (!mg_parse_header(hdr, "cnonce", cnonce, sizeof(cnonce))) return 0;
3062 if (!mg_parse_header(hdr, "response", resp, sizeof(resp))) return 0;
3063 if (!mg_parse_header(hdr, "uri", uri, sizeof(uri))) return 0;
3064 if (!mg_parse_header(hdr, "qop", qop, sizeof(qop))) return 0;
3065 if (!mg_parse_header(hdr, "nc", nc, sizeof(nc))) return 0;
3066 if (!mg_parse_header(hdr, "nonce", nonce, sizeof(nonce))) return 0;
3067
3068 while (fgets(line, sizeof(line), fp) != NULL) {
3069 if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) == 3 &&
3070 !strcmp(user, f_user) &&
3071 // NOTE(lsm): due to a bug in MSIE, we do not compare URIs
3072 !strcmp(conn->server->config_options[AUTH_DOMAIN], f_domain))
3073 return check_password(c->request_method, ha1, uri,
3074 nonce, nc, cnonce, qop, resp);
3075 }
3076 return MG_AUTH_FAIL;
3077 }
3078
3079
3080 // Return 1 if request is authorised, 0 otherwise.
is_authorized(struct connection * conn,const char * path)3081 static int is_authorized(struct connection *conn, const char *path) {
3082 FILE *fp;
3083 int authorized = MG_AUTH_OK;
3084
3085 if ((fp = open_auth_file(conn, path)) != NULL) {
3086 authorized = mg_authorize_digest(&conn->mg_conn, fp);
3087 fclose(fp);
3088 }
3089
3090 return authorized;
3091 }
3092
is_authorized_for_dav(struct connection * conn)3093 static int is_authorized_for_dav(struct connection *conn) {
3094 const char *auth_file = conn->server->config_options[DAV_AUTH_FILE];
3095 FILE *fp;
3096 int authorized = MG_AUTH_FAIL;
3097
3098 if (auth_file != NULL && (fp = fopen(auth_file, "r")) != NULL) {
3099 authorized = mg_authorize_digest(&conn->mg_conn, fp);
3100 fclose(fp);
3101 }
3102
3103 return authorized;
3104 }
3105
is_dav_mutation(const struct connection * conn)3106 static int is_dav_mutation(const struct connection *conn) {
3107 const char *s = conn->mg_conn.request_method;
3108 return s && (!strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
3109 !strcmp(s, "MKCOL"));
3110 }
3111 #endif // MONGOOSE_NO_AUTH
3112
parse_header(const char * str,int str_len,const char * var_name,char * buf,size_t buf_size)3113 int parse_header(const char *str, int str_len, const char *var_name, char *buf,
3114 size_t buf_size) {
3115 int ch = ' ', len = 0, n = strlen(var_name);
3116 const char *p, *end = str + str_len, *s = NULL;
3117
3118 if (buf != NULL && buf_size > 0) buf[0] = '\0';
3119
3120 // Find where variable starts
3121 for (s = str; s != NULL && s + n < end; s++) {
3122 if ((s == str || s[-1] == ' ' || s[-1] == ',') && s[n] == '=' &&
3123 !memcmp(s, var_name, n)) break;
3124 }
3125
3126 if (s != NULL && &s[n + 1] < end) {
3127 s += n + 1;
3128 if (*s == '"' || *s == '\'') ch = *s++;
3129 p = s;
3130 while (p < end && p[0] != ch && p[0] != ',' && len < (int) buf_size) {
3131 if (p[0] == '\\' && p[1] == ch) p++;
3132 buf[len++] = *p++;
3133 }
3134 if (len >= (int) buf_size || (ch != ' ' && *p != ch)) {
3135 len = 0;
3136 } else {
3137 if (len > 0 && s[len - 1] == ',') len--;
3138 if (len > 0 && s[len - 1] == ';') len--;
3139 buf[len] = '\0';
3140 }
3141 }
3142
3143 return len;
3144 }
3145
mg_parse_header(const char * s,const char * var_name,char * buf,size_t buf_size)3146 int mg_parse_header(const char *s, const char *var_name, char *buf,
3147 size_t buf_size) {
3148 return parse_header(s, s == NULL ? 0 : strlen(s), var_name, buf, buf_size);
3149 }
3150
3151 #ifdef MONGOOSE_USE_LUA
3152 #include "lua_5.2.1.h"
3153
3154 #ifdef _WIN32
mmap(void * addr,int64_t len,int prot,int flags,int fd,int offset)3155 static void *mmap(void *addr, int64_t len, int prot, int flags, int fd,
3156 int offset) {
3157 HANDLE fh = (HANDLE) _get_osfhandle(fd);
3158 HANDLE mh = CreateFileMapping(fh, 0, PAGE_READONLY, 0, 0, 0);
3159 void *p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, (size_t) len);
3160 CloseHandle(mh);
3161 return p;
3162 }
3163 #define munmap(x, y) UnmapViewOfFile(x)
3164 #define MAP_FAILED NULL
3165 #define MAP_PRIVATE 0
3166 #define PROT_READ 0
3167 #else
3168 #include <sys/mman.h>
3169 #endif
3170
reg_string(struct lua_State * L,const char * name,const char * val)3171 static void reg_string(struct lua_State *L, const char *name, const char *val) {
3172 lua_pushstring(L, name);
3173 lua_pushstring(L, val);
3174 lua_rawset(L, -3);
3175 }
3176
reg_int(struct lua_State * L,const char * name,int val)3177 static void reg_int(struct lua_State *L, const char *name, int val) {
3178 lua_pushstring(L, name);
3179 lua_pushinteger(L, val);
3180 lua_rawset(L, -3);
3181 }
3182
reg_function(struct lua_State * L,const char * name,lua_CFunction func,struct mg_connection * conn)3183 static void reg_function(struct lua_State *L, const char *name,
3184 lua_CFunction func, struct mg_connection *conn) {
3185 lua_pushstring(L, name);
3186 lua_pushlightuserdata(L, conn);
3187 lua_pushcclosure(L, func, 1);
3188 lua_rawset(L, -3);
3189 }
3190
lua_write(lua_State * L)3191 static int lua_write(lua_State *L) {
3192 int i, num_args;
3193 const char *str;
3194 size_t size;
3195 struct mg_connection *conn = (struct mg_connection *)
3196 lua_touserdata(L, lua_upvalueindex(1));
3197
3198 num_args = lua_gettop(L);
3199 for (i = 1; i <= num_args; i++) {
3200 if (lua_isstring(L, i)) {
3201 str = lua_tolstring(L, i, &size);
3202 mg_write(conn, str, size);
3203 }
3204 }
3205
3206 return 0;
3207 }
3208
lsp_sock_close(lua_State * L)3209 static int lsp_sock_close(lua_State *L) {
3210 if (lua_gettop(L) > 0 && lua_istable(L, -1)) {
3211 lua_getfield(L, -1, "sock");
3212 closesocket((sock_t) lua_tonumber(L, -1));
3213 } else {
3214 return luaL_error(L, "invalid :close() call");
3215 }
3216 return 1;
3217 }
3218
lsp_sock_recv(lua_State * L)3219 static int lsp_sock_recv(lua_State *L) {
3220 char buf[2000];
3221 int n;
3222
3223 if (lua_gettop(L) > 0 && lua_istable(L, -1)) {
3224 lua_getfield(L, -1, "sock");
3225 n = recv((sock_t) lua_tonumber(L, -1), buf, sizeof(buf), 0);
3226 if (n <= 0) {
3227 lua_pushnil(L);
3228 } else {
3229 lua_pushlstring(L, buf, n);
3230 }
3231 } else {
3232 return luaL_error(L, "invalid :close() call");
3233 }
3234 return 1;
3235 }
3236
lsp_sock_send(lua_State * L)3237 static int lsp_sock_send(lua_State *L) {
3238 const char *buf;
3239 size_t len, sent = 0;
3240 int n, sock;
3241
3242 if (lua_gettop(L) > 1 && lua_istable(L, -2) && lua_isstring(L, -1)) {
3243 buf = lua_tolstring(L, -1, &len);
3244 lua_getfield(L, -2, "sock");
3245 sock = (int) lua_tonumber(L, -1);
3246 while (sent < len) {
3247 if ((n = send(sock, buf + sent, len - sent, 0)) <= 0) break;
3248 sent += n;
3249 }
3250 lua_pushnumber(L, sent);
3251 } else {
3252 return luaL_error(L, "invalid :close() call");
3253 }
3254 return 1;
3255 }
3256
3257 static const struct luaL_Reg luasocket_methods[] = {
3258 {"close", lsp_sock_close},
3259 {"send", lsp_sock_send},
3260 {"recv", lsp_sock_recv},
3261 {NULL, NULL}
3262 };
3263
conn2(const char * host,int port)3264 static sock_t conn2(const char *host, int port) {
3265 struct sockaddr_in sin;
3266 struct hostent *he = NULL;
3267 sock_t sock = INVALID_SOCKET;
3268
3269 if (host != NULL &&
3270 (he = gethostbyname(host)) != NULL &&
3271 (sock = socket(PF_INET, SOCK_STREAM, 0)) != INVALID_SOCKET) {
3272 set_close_on_exec(sock);
3273 sin.sin_family = AF_INET;
3274 sin.sin_port = htons((uint16_t) port);
3275 sin.sin_addr = * (struct in_addr *) he->h_addr_list[0];
3276 if (connect(sock, (struct sockaddr *) &sin, sizeof(sin)) != 0) {
3277 closesocket(sock);
3278 sock = INVALID_SOCKET;
3279 }
3280 }
3281 return sock;
3282 }
3283
lsp_connect(lua_State * L)3284 static int lsp_connect(lua_State *L) {
3285 sock_t sock;
3286
3287 if (lua_isstring(L, -2) && lua_isnumber(L, -1)) {
3288 sock = conn2(lua_tostring(L, -2), (int) lua_tonumber(L, -1));
3289 if (sock == INVALID_SOCKET) {
3290 lua_pushnil(L);
3291 } else {
3292 lua_newtable(L);
3293 reg_int(L, "sock", sock);
3294 reg_string(L, "host", lua_tostring(L, -4));
3295 luaL_getmetatable(L, "luasocket");
3296 lua_setmetatable(L, -2);
3297 }
3298 } else {
3299 return luaL_error(L, "connect(host,port): invalid parameter given.");
3300 }
3301 return 1;
3302 }
3303
prepare_lua_environment(struct mg_connection * ri,lua_State * L)3304 static void prepare_lua_environment(struct mg_connection *ri, lua_State *L) {
3305 extern void luaL_openlibs(lua_State *);
3306 int i;
3307
3308 luaL_openlibs(L);
3309 #ifdef MONGOOSE_USE_LUA_SQLITE3
3310 { extern int luaopen_lsqlite3(lua_State *); luaopen_lsqlite3(L); }
3311 #endif
3312
3313 luaL_newmetatable(L, "luasocket");
3314 lua_pushliteral(L, "__index");
3315 luaL_newlib(L, luasocket_methods);
3316 lua_rawset(L, -3);
3317 lua_pop(L, 1);
3318 lua_register(L, "connect", lsp_connect);
3319
3320 if (ri == NULL) return;
3321
3322 // Register mg module
3323 lua_newtable(L);
3324 reg_function(L, "write", lua_write, ri);
3325
3326 // Export request_info
3327 lua_pushstring(L, "request_info");
3328 lua_newtable(L);
3329 reg_string(L, "request_method", ri->request_method);
3330 reg_string(L, "uri", ri->uri);
3331 reg_string(L, "http_version", ri->http_version);
3332 reg_string(L, "query_string", ri->query_string);
3333 reg_string(L, "remote_ip", ri->remote_ip);
3334 reg_int(L, "remote_port", ri->remote_port);
3335 lua_pushstring(L, "content");
3336 lua_pushlstring(L, ri->content == NULL ? "" : ri->content, 0);
3337 lua_rawset(L, -3);
3338 reg_int(L, "content_len", ri->content_len);
3339 reg_int(L, "num_headers", ri->num_headers);
3340 lua_pushstring(L, "http_headers");
3341 lua_newtable(L);
3342 for (i = 0; i < ri->num_headers; i++) {
3343 reg_string(L, ri->http_headers[i].name, ri->http_headers[i].value);
3344 }
3345 lua_rawset(L, -3);
3346 lua_rawset(L, -3);
3347
3348 lua_setglobal(L, "mg");
3349
3350 // Register default mg.onerror function
3351 (void) luaL_dostring(L, "mg.onerror = function(e) mg.write('\\nLua "
3352 "error:\\n', debug.traceback(e, 1)) end");
3353 }
3354
lua_error_handler(lua_State * L)3355 static int lua_error_handler(lua_State *L) {
3356 const char *error_msg = lua_isstring(L, -1) ? lua_tostring(L, -1) : "?\n";
3357
3358 lua_getglobal(L, "mg");
3359 if (!lua_isnil(L, -1)) {
3360 lua_getfield(L, -1, "write"); // call mg.write()
3361 lua_pushstring(L, error_msg);
3362 lua_pushliteral(L, "\n");
3363 lua_call(L, 2, 0);
3364 (void) luaL_dostring(L, "mg.write(debug.traceback(), '\\n')");
3365 } else {
3366 printf("Lua error: [%s]\n", error_msg);
3367 (void) luaL_dostring(L, "print(debug.traceback(), '\\n')");
3368 }
3369 // TODO(lsm): leave the stack balanced
3370
3371 return 0;
3372 }
3373
lsp(struct connection * conn,const char * p,int len,lua_State * L)3374 static void lsp(struct connection *conn, const char *p, int len, lua_State *L) {
3375 int i, j, pos = 0;
3376
3377 for (i = 0; i < len; i++) {
3378 if (p[i] == '<' && p[i + 1] == '?') {
3379 for (j = i + 1; j < len ; j++) {
3380 if (p[j] == '?' && p[j + 1] == '>') {
3381 mg_write(&conn->mg_conn, p + pos, i - pos);
3382 if (luaL_loadbuffer(L, p + (i + 2), j - (i + 2), "") == LUA_OK) {
3383 lua_pcall(L, 0, LUA_MULTRET, 0);
3384 }
3385 pos = j + 2;
3386 i = pos - 1;
3387 break;
3388 }
3389 }
3390 }
3391 }
3392 if (i > pos) mg_write(&conn->mg_conn, p + pos, i - pos);
3393 }
3394
handle_lsp_request(struct connection * conn,const char * path,file_stat_t * st)3395 static void handle_lsp_request(struct connection *conn, const char *path,
3396 file_stat_t *st) {
3397 void *p = NULL;
3398 lua_State *L = NULL;
3399 FILE *fp = NULL;
3400
3401 if ((fp = fopen(path, "r")) == NULL ||
3402 (p = mmap(NULL, st->st_size, PROT_READ, MAP_PRIVATE,
3403 fileno(fp), 0)) == MAP_FAILED ||
3404 (L = luaL_newstate()) == NULL) {
3405 send_http_error(conn, 500, "mmap(%s): %s", path, strerror(errno));
3406 } else {
3407 // We're not sending HTTP headers here, Lua page must do it.
3408 prepare_lua_environment(&conn->mg_conn, L);
3409 lua_pushcclosure(L, &lua_error_handler, 0);
3410 lua_pushglobaltable(L);
3411 lsp(conn, p, (int) st->st_size, L);
3412 close_local_endpoint(conn);
3413 }
3414
3415 if (L != NULL) lua_close(L);
3416 if (p != NULL) munmap(p, st->st_size);
3417 if (fp != NULL) fclose(fp);
3418 }
3419 #endif // MONGOOSE_USE_LUA
3420
open_local_endpoint(struct connection * conn,int skip_user)3421 static void open_local_endpoint(struct connection *conn, int skip_user) {
3422 #ifndef MONGOOSE_NO_FILESYSTEM
3423 static const char lua_pat[] = LUA_SCRIPT_PATTERN;
3424 file_stat_t st;
3425 char path[MAX_PATH_SIZE];
3426 int exists = 0, is_directory = 0;
3427 #ifndef MONGOOSE_NO_CGI
3428 const char *cgi_pat = conn->server->config_options[CGI_PATTERN];
3429 #else
3430 const char *cgi_pat = DEFAULT_CGI_PATTERN;
3431 #endif
3432 #ifndef MONGOOSE_NO_DIRECTORY_LISTING
3433 const char *dir_lst = conn->server->config_options[ENABLE_DIRECTORY_LISTING];
3434 #else
3435 const char *dir_lst = "yes";
3436 #endif
3437 #endif
3438
3439 #ifndef MONGOOSE_NO_AUTH
3440 // Call auth handler
3441 if (conn->server->auth_handler != NULL &&
3442 conn->server->auth_handler(&conn->mg_conn) == MG_AUTH_FAIL) {
3443 mg_send_digest_auth_request(&conn->mg_conn);
3444 return;
3445 }
3446 #endif
3447
3448 // Call URI handler if one is registered for this URI
3449 if (skip_user == 0 && conn->server->request_handler != NULL) {
3450 conn->endpoint_type = EP_USER;
3451 #if MONGOOSE_USE_POST_SIZE_LIMIT > 1
3452 {
3453 const char *cl = mg_get_header(&conn->mg_conn, "Content-Length");
3454 if (!strcmp(conn->mg_conn.request_method, "POST") &&
3455 (cl == NULL || to64(cl) > MONGOOSE_USE_POST_SIZE_LIMIT)) {
3456 send_http_error(conn, 500, "POST size > %zu",
3457 (size_t) MONGOOSE_USE_POST_SIZE_LIMIT);
3458 }
3459 }
3460 #endif
3461 return;
3462 }
3463
3464 #ifdef MONGOOSE_NO_FILESYSTEM
3465 if (!strcmp(conn->mg_conn.request_method, "OPTIONS")) {
3466 send_options(conn);
3467 } else {
3468 send_http_error(conn, 404, NULL);
3469 }
3470 #else
3471 exists = convert_uri_to_file_name(conn, path, sizeof(path), &st);
3472 is_directory = S_ISDIR(st.st_mode);
3473
3474 if (!strcmp(conn->mg_conn.request_method, "OPTIONS")) {
3475 send_options(conn);
3476 } else if (conn->server->config_options[DOCUMENT_ROOT] == NULL) {
3477 send_http_error(conn, 404, NULL);
3478 #ifndef MONGOOSE_NO_AUTH
3479 } else if ((!is_dav_mutation(conn) && !is_authorized(conn, path)) ||
3480 (is_dav_mutation(conn) && !is_authorized_for_dav(conn))) {
3481 mg_send_digest_auth_request(&conn->mg_conn);
3482 close_local_endpoint(conn);
3483 #endif
3484 #ifndef MONGOOSE_NO_DAV
3485 } else if (!strcmp(conn->mg_conn.request_method, "PROPFIND")) {
3486 handle_propfind(conn, path, &st);
3487 } else if (!strcmp(conn->mg_conn.request_method, "MKCOL")) {
3488 handle_mkcol(conn, path);
3489 } else if (!strcmp(conn->mg_conn.request_method, "DELETE")) {
3490 handle_delete(conn, path);
3491 } else if (!strcmp(conn->mg_conn.request_method, "PUT")) {
3492 handle_put(conn, path);
3493 #endif
3494 } else if (!exists || must_hide_file(conn, path)) {
3495 send_http_error(conn, 404, NULL);
3496 } else if (is_directory &&
3497 conn->mg_conn.uri[strlen(conn->mg_conn.uri) - 1] != '/') {
3498 conn->mg_conn.status_code = 301;
3499 mg_printf(&conn->mg_conn, "HTTP/1.1 301 Moved Permanently\r\n"
3500 "Location: %s/\r\n\r\n", conn->mg_conn.uri);
3501 close_local_endpoint(conn);
3502 } else if (is_directory && !find_index_file(conn, path, sizeof(path), &st)) {
3503 if (!mg_strcasecmp(dir_lst, "yes")) {
3504 #ifndef MONGOOSE_NO_DIRECTORY_LISTING
3505 send_directory_listing(conn, path);
3506 #else
3507 send_http_error(conn, 501, NULL);
3508 #endif
3509 } else {
3510 send_http_error(conn, 403, NULL);
3511 }
3512 } else if (match_prefix(lua_pat, sizeof(lua_pat) - 1, path) > 0) {
3513 #ifdef MONGOOSE_USE_LUA
3514 handle_lsp_request(conn, path, &st);
3515 #else
3516 send_http_error(conn, 501, NULL);
3517 #endif
3518 } else if (match_prefix(cgi_pat, strlen(cgi_pat), path) > 0) {
3519 #if !defined(MONGOOSE_NO_CGI)
3520 open_cgi_endpoint(conn, path);
3521 #else
3522 send_http_error(conn, 501, NULL);
3523 #endif // !MONGOOSE_NO_CGI
3524 } else if (is_not_modified(conn, &st)) {
3525 send_http_error(conn, 304, NULL);
3526 } else if ((conn->endpoint.fd = open(path, O_RDONLY | O_BINARY)) != -1) {
3527 // O_BINARY is required for Windows, otherwise in default text mode
3528 // two bytes \r\n will be read as one.
3529 open_file_endpoint(conn, path, &st);
3530 } else {
3531 send_http_error(conn, 404, NULL);
3532 }
3533 #endif // MONGOOSE_NO_FILESYSTEM
3534 }
3535
send_continue_if_expected(struct connection * conn)3536 static void send_continue_if_expected(struct connection *conn) {
3537 static const char expect_response[] = "HTTP/1.1 100 Continue\r\n\r\n";
3538 const char *expect_hdr = mg_get_header(&conn->mg_conn, "Expect");
3539
3540 if (expect_hdr != NULL && !mg_strcasecmp(expect_hdr, "100-continue")) {
3541 spool(&conn->remote_iobuf, expect_response, sizeof(expect_response) - 1);
3542 }
3543 }
3544
is_valid_uri(const char * uri)3545 static int is_valid_uri(const char *uri) {
3546 // Conform to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
3547 // URI can be an asterisk (*) or should start with slash.
3548 return uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0');
3549 }
3550
try_http_parse_and_set_content_length(struct connection * conn)3551 static void try_http_parse_and_set_content_length(struct connection *conn) {
3552 struct iobuf *io = &conn->local_iobuf;
3553
3554 if (conn->request_len == 0 &&
3555 (conn->request_len = get_request_len(io->buf, io->len)) > 0) {
3556 // If request is buffered in, remove it from the iobuf. This is because
3557 // iobuf could be reallocated, and pointers in parsed request could
3558 // become invalid.
3559 conn->request = (char *) malloc(conn->request_len);
3560 memcpy(conn->request, io->buf, conn->request_len);
3561 DBG(("%p [%.*s]", conn, conn->request_len, conn->request));
3562 discard_leading_iobuf_bytes(io, conn->request_len);
3563 conn->request_len = parse_http_message(conn->request, conn->request_len,
3564 &conn->mg_conn);
3565 if (conn->request_len > 0) {
3566 const char *cl_hdr = mg_get_header(&conn->mg_conn, "Content-Length");
3567 conn->cl = cl_hdr == NULL ? 0 : to64(cl_hdr);
3568 conn->mg_conn.content_len = (long int) conn->cl;
3569 }
3570 }
3571 }
3572
process_request(struct connection * conn)3573 static void process_request(struct connection *conn) {
3574 struct iobuf *io = &conn->local_iobuf;
3575
3576 try_http_parse_and_set_content_length(conn);
3577 DBG(("%p %d %d %d [%.*s]", conn, conn->request_len, io->len, conn->flags,
3578 io->len, io->buf));
3579 if (conn->request_len < 0 ||
3580 (conn->request_len > 0 && !is_valid_uri(conn->mg_conn.uri))) {
3581 send_http_error(conn, 400, NULL);
3582 } else if (conn->request_len == 0 && io->len > MAX_REQUEST_SIZE) {
3583 send_http_error(conn, 413, NULL);
3584 } else if (conn->request_len > 0 &&
3585 strcmp(conn->mg_conn.http_version, "1.0") != 0 &&
3586 strcmp(conn->mg_conn.http_version, "1.1") != 0) {
3587 send_http_error(conn, 505, NULL);
3588 } else if (conn->request_len > 0 && conn->endpoint_type == EP_NONE) {
3589 #ifndef MONGOOSE_NO_WEBSOCKET
3590 send_websocket_handshake_if_requested(&conn->mg_conn);
3591 #endif
3592 send_continue_if_expected(conn);
3593 open_local_endpoint(conn, 0);
3594 }
3595
3596 #ifndef MONGOOSE_NO_CGI
3597 if (conn->endpoint_type == EP_CGI && io->len > 0) {
3598 forward_post_data(conn);
3599 }
3600 #endif
3601 if (conn->endpoint_type == EP_USER) {
3602 call_request_handler_if_data_is_buffered(conn);
3603 }
3604 #ifndef MONGOOSE_NO_DAV
3605 if (conn->endpoint_type == EP_PUT && io->len > 0) {
3606 forward_put_data(conn);
3607 }
3608 #endif
3609 }
3610
call_http_client_handler(struct connection * conn,int code)3611 static void call_http_client_handler(struct connection *conn, int code) {
3612 conn->mg_conn.status_code = code;
3613 // For responses without Content-Lengh, use the whole buffer
3614 if (conn->cl == 0 && code == MG_DOWNLOAD_SUCCESS) {
3615 conn->mg_conn.content_len = conn->local_iobuf.len;
3616 }
3617 conn->mg_conn.content = conn->local_iobuf.buf;
3618 if (conn->handler(&conn->mg_conn) || code == MG_CONNECT_FAILURE ||
3619 code == MG_DOWNLOAD_FAILURE) {
3620 conn->flags |= CONN_CLOSE;
3621 }
3622 discard_leading_iobuf_bytes(&conn->local_iobuf, conn->mg_conn.content_len);
3623 conn->flags = conn->mg_conn.status_code = 0;
3624 conn->cl = conn->num_bytes_sent = conn->request_len = 0;
3625 free(conn->request);
3626 conn->request = NULL;
3627 }
3628
process_response(struct connection * conn)3629 static void process_response(struct connection *conn) {
3630 struct iobuf *io = &conn->local_iobuf;
3631
3632 try_http_parse_and_set_content_length(conn);
3633 DBG(("%p %d %d [%.*s]", conn, conn->request_len, io->len,
3634 io->len > 40 ? 40 : io->len, io->buf));
3635 if (conn->request_len < 0 ||
3636 (conn->request_len == 0 && io->len > MAX_REQUEST_SIZE)) {
3637 call_http_client_handler(conn, MG_DOWNLOAD_FAILURE);
3638 }
3639 if (io->len >= conn->cl) {
3640 call_http_client_handler(conn, MG_DOWNLOAD_SUCCESS);
3641 }
3642 }
3643
read_from_socket(struct connection * conn)3644 static void read_from_socket(struct connection *conn) {
3645 char buf[IOBUF_SIZE];
3646 int n = 0;
3647
3648 if (conn->endpoint_type == EP_CLIENT && conn->flags & CONN_CONNECTING) {
3649 callback_http_client_on_connect(conn);
3650 return;
3651 }
3652
3653 #ifdef MONGOOSE_USE_SSL
3654 if (conn->ssl != NULL) {
3655 if (conn->flags & CONN_SSL_HANDS_SHAKEN) {
3656 n = SSL_read(conn->ssl, buf, sizeof(buf));
3657 } else {
3658 if (SSL_accept(conn->ssl) == 1) {
3659 conn->flags |= CONN_SSL_HANDS_SHAKEN;
3660 }
3661 return;
3662 }
3663 } else
3664 #endif
3665 {
3666 n = recv(conn->client_sock, buf, sizeof(buf), 0);
3667 }
3668
3669 DBG(("%p %d %d (1)", conn, n, conn->flags));
3670 if (is_error(n)) {
3671 if (conn->endpoint_type == EP_CLIENT && conn->local_iobuf.len > 0) {
3672 call_http_client_handler(conn, MG_DOWNLOAD_SUCCESS);
3673 }
3674 conn->flags |= CONN_CLOSE;
3675 } else if (n > 0) {
3676 spool(&conn->local_iobuf, buf, n);
3677 if (conn->endpoint_type == EP_CLIENT) {
3678 process_response(conn);
3679 } else {
3680 process_request(conn);
3681 }
3682 }
3683 DBG(("%p %d %d (2)", conn, n, conn->flags));
3684 }
3685
mg_connect(struct mg_server * server,const char * host,int port,int use_ssl,mg_handler_t handler,void * param)3686 int mg_connect(struct mg_server *server, const char *host, int port,
3687 int use_ssl, mg_handler_t handler, void *param) {
3688 sock_t sock = INVALID_SOCKET;
3689 struct sockaddr_in sin;
3690 struct hostent *he = NULL;
3691 struct connection *conn = NULL;
3692 int connect_ret_val;
3693
3694 if (host == NULL || (he = gethostbyname(host)) == NULL ||
3695 (sock = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) return 0;
3696 #ifndef MONGOOSE_USE_SSL
3697 if (use_ssl) return 0;
3698 #endif
3699
3700 sin.sin_family = AF_INET;
3701 sin.sin_port = htons((uint16_t) port);
3702 sin.sin_addr = * (struct in_addr *) he->h_addr_list[0];
3703 set_non_blocking_mode(sock);
3704
3705 connect_ret_val = connect(sock, (struct sockaddr *) &sin, sizeof(sin));
3706 if (is_error(connect_ret_val)) {
3707 return 0;
3708 } else if ((conn = (struct connection *) calloc(1, sizeof(*conn))) == NULL) {
3709 closesocket(sock);
3710 return 0;
3711 }
3712
3713 conn->server = server;
3714 conn->client_sock = sock;
3715 conn->endpoint_type = EP_CLIENT;
3716 conn->handler = handler;
3717 conn->mg_conn.server_param = server->server_data;
3718 conn->mg_conn.connection_param = param;
3719 conn->birth_time = conn->last_activity_time = time(NULL);
3720 conn->flags = CONN_CONNECTING;
3721 conn->mg_conn.status_code = MG_CONNECT_FAILURE;
3722 #ifdef MONGOOSE_USE_SSL
3723 if (use_ssl && (conn->ssl = SSL_new(server->client_ssl_ctx)) != NULL) {
3724 SSL_set_fd(conn->ssl, sock);
3725 }
3726 #endif
3727 LINKED_LIST_ADD_TO_FRONT(&server->active_connections, &conn->link);
3728 DBG(("%p %s:%d", conn, host, port));
3729
3730 return 1;
3731 }
3732
3733 #ifndef MONGOOSE_NO_LOGGING
log_header(const struct mg_connection * conn,const char * header,FILE * fp)3734 static void log_header(const struct mg_connection *conn, const char *header,
3735 FILE *fp) {
3736 const char *header_value;
3737
3738 if ((header_value = mg_get_header(conn, header)) == NULL) {
3739 (void) fprintf(fp, "%s", " -");
3740 } else {
3741 (void) fprintf(fp, " \"%s\"", header_value);
3742 }
3743 }
3744
log_access(const struct connection * conn,const char * path)3745 static void log_access(const struct connection *conn, const char *path) {
3746 const struct mg_connection *c = &conn->mg_conn;
3747 FILE *fp = (path == NULL) ? NULL : fopen(path, "a+");
3748 char date[64], user[100];
3749
3750 if (fp == NULL) return;
3751 strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z",
3752 localtime(&conn->birth_time));
3753
3754 flockfile(fp);
3755 mg_parse_header(mg_get_header(&conn->mg_conn, "Authorization"), "username",
3756 user, sizeof(user));
3757 fprintf(fp, "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT,
3758 c->remote_ip, user[0] == '\0' ? "-" : user, date,
3759 c->request_method ? c->request_method : "-",
3760 c->uri ? c->uri : "-", c->http_version,
3761 c->status_code, conn->num_bytes_sent);
3762 log_header(c, "Referer", fp);
3763 log_header(c, "User-Agent", fp);
3764 fputc('\n', fp);
3765 fflush(fp);
3766
3767 funlockfile(fp);
3768 fclose(fp);
3769 }
3770 #endif
3771
close_local_endpoint(struct connection * conn)3772 static void close_local_endpoint(struct connection *conn) {
3773 struct mg_connection *c = &conn->mg_conn;
3774 // Must be done before free()
3775 int keep_alive = should_keep_alive(&conn->mg_conn) &&
3776 (conn->endpoint_type == EP_FILE || conn->endpoint_type == EP_USER);
3777 DBG(("%p %d %d %d", conn, conn->endpoint_type, keep_alive, conn->flags));
3778
3779 switch (conn->endpoint_type) {
3780 case EP_PUT: close(conn->endpoint.fd); break;
3781 case EP_FILE: close(conn->endpoint.fd); break;
3782 case EP_CGI: closesocket(conn->endpoint.cgi_sock); break;
3783 default: break;
3784 }
3785
3786 #ifndef MONGOOSE_NO_LOGGING
3787 if (c->status_code > 0 && conn->endpoint_type != EP_CLIENT &&
3788 c->status_code != 400) {
3789 log_access(conn, conn->server->config_options[ACCESS_LOG_FILE]);
3790 }
3791 #endif
3792
3793 // Gobble possible POST data sent to the URI handler
3794 discard_leading_iobuf_bytes(&conn->local_iobuf, conn->mg_conn.content_len);
3795 conn->endpoint_type = EP_NONE;
3796 conn->cl = conn->num_bytes_sent = conn->request_len = conn->flags = 0;
3797 c->request_method = c->uri = c->http_version = c->query_string = NULL;
3798 c->num_headers = c->status_code = c->is_websocket = c->content_len = 0;
3799 free(conn->request);
3800 conn->request = NULL;
3801
3802 if (keep_alive) {
3803 process_request(conn); // Can call us recursively if pipelining is used
3804 } else {
3805 conn->flags |= conn->remote_iobuf.len == 0 ? CONN_CLOSE : CONN_SPOOL_DONE;
3806 }
3807 }
3808
transfer_file_data(struct connection * conn)3809 static void transfer_file_data(struct connection *conn) {
3810 char buf[IOBUF_SIZE];
3811 int n = read(conn->endpoint.fd, buf, conn->cl < (int64_t) sizeof(buf) ?
3812 (int) conn->cl : (int) sizeof(buf));
3813
3814 if (is_error(n)) {
3815 close_local_endpoint(conn);
3816 } else if (n > 0) {
3817 conn->cl -= n;
3818 spool(&conn->remote_iobuf, buf, n);
3819 if (conn->cl <= 0) {
3820 close_local_endpoint(conn);
3821 }
3822 }
3823 }
3824
execute_iteration(struct mg_server * server)3825 static void execute_iteration(struct mg_server *server) {
3826 struct ll *lp, *tmp;
3827 struct connection *conn;
3828 union { mg_handler_t f; void *p; } msg[2];
3829
3830 recv(server->ctl[1], (void *) msg, sizeof(msg), 0);
3831 LINKED_LIST_FOREACH(&server->active_connections, lp, tmp) {
3832 conn = LINKED_LIST_ENTRY(lp, struct connection, link);
3833 conn->mg_conn.connection_param = msg[1].p;
3834 msg[0].f(&conn->mg_conn);
3835 }
3836 }
3837
add_to_set(sock_t sock,fd_set * set,sock_t * max_fd)3838 void add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) {
3839 FD_SET(sock, set);
3840 if (sock > *max_fd) {
3841 *max_fd = sock;
3842 }
3843 }
3844
mg_poll_server(struct mg_server * server,int milliseconds)3845 unsigned int mg_poll_server(struct mg_server *server, int milliseconds) {
3846 struct ll *lp, *tmp;
3847 struct connection *conn;
3848 struct timeval tv;
3849 fd_set read_set, write_set;
3850 sock_t max_fd = -1;
3851 time_t current_time = time(NULL), expire_time = current_time -
3852 MONGOOSE_USE_IDLE_TIMEOUT_SECONDS;
3853
3854 if (server->listening_sock == INVALID_SOCKET) return 0;
3855
3856 FD_ZERO(&read_set);
3857 FD_ZERO(&write_set);
3858 add_to_set(server->listening_sock, &read_set, &max_fd);
3859 add_to_set(server->ctl[1], &read_set, &max_fd);
3860
3861 LINKED_LIST_FOREACH(&server->active_connections, lp, tmp) {
3862 conn = LINKED_LIST_ENTRY(lp, struct connection, link);
3863 add_to_set(conn->client_sock, &read_set, &max_fd);
3864 if (conn->endpoint_type == EP_CLIENT && (conn->flags & CONN_CONNECTING)) {
3865 add_to_set(conn->client_sock, &write_set, &max_fd);
3866 }
3867 if (conn->endpoint_type == EP_FILE) {
3868 transfer_file_data(conn);
3869 } else if (conn->endpoint_type == EP_CGI) {
3870 add_to_set(conn->endpoint.cgi_sock, &read_set, &max_fd);
3871 }
3872 if (conn->remote_iobuf.len > 0 && !(conn->flags & CONN_BUFFER)) {
3873 add_to_set(conn->client_sock, &write_set, &max_fd);
3874 } else if (conn->flags & CONN_CLOSE) {
3875 close_conn(conn);
3876 }
3877 }
3878
3879 tv.tv_sec = milliseconds / 1000;
3880 tv.tv_usec = (milliseconds % 1000) * 1000;
3881
3882 if (select(max_fd + 1, &read_set, &write_set, NULL, &tv) > 0) {
3883 if (FD_ISSET(server->ctl[1], &read_set)) {
3884 execute_iteration(server);
3885 }
3886
3887 // Accept new connections
3888 if (FD_ISSET(server->listening_sock, &read_set)) {
3889 while ((conn = accept_new_connection(server)) != NULL) {
3890 conn->birth_time = conn->last_activity_time = current_time;
3891 }
3892 }
3893
3894 // Read/write from clients
3895 LINKED_LIST_FOREACH(&server->active_connections, lp, tmp) {
3896 conn = LINKED_LIST_ENTRY(lp, struct connection, link);
3897 if (FD_ISSET(conn->client_sock, &read_set)) {
3898 conn->last_activity_time = current_time;
3899 read_from_socket(conn);
3900 }
3901 #ifndef MONGOOSE_NO_CGI
3902 if (conn->endpoint_type == EP_CGI &&
3903 FD_ISSET(conn->endpoint.cgi_sock, &read_set)) {
3904 read_from_cgi(conn);
3905 }
3906 #endif
3907 if (FD_ISSET(conn->client_sock, &write_set)) {
3908 if (conn->endpoint_type == EP_CLIENT &&
3909 (conn->flags & CONN_CONNECTING)) {
3910 read_from_socket(conn);
3911 } else if (!(conn->flags & CONN_BUFFER)) {
3912 conn->last_activity_time = current_time;
3913 write_to_socket(conn);
3914 }
3915 }
3916 }
3917 }
3918
3919 // Close expired connections and those that need to be closed
3920 LINKED_LIST_FOREACH(&server->active_connections, lp, tmp) {
3921 conn = LINKED_LIST_ENTRY(lp, struct connection, link);
3922 if (conn->mg_conn.is_websocket) {
3923 ping_idle_websocket_connection(conn, current_time);
3924 }
3925 if (conn->flags & CONN_LONG_RUNNING) {
3926 conn->mg_conn.wsbits = conn->flags & CONN_CLOSE ? 1 : 0;
3927 if (call_request_handler(conn) == MG_REQUEST_PROCESSED) {
3928 conn->flags |= CONN_CLOSE;
3929 }
3930 }
3931 if (conn->flags & CONN_CLOSE || conn->last_activity_time < expire_time) {
3932 close_conn(conn);
3933 }
3934 }
3935
3936 return (unsigned int) current_time;
3937 }
3938
mg_destroy_server(struct mg_server ** server)3939 void mg_destroy_server(struct mg_server **server) {
3940 int i;
3941 struct ll *lp, *tmp;
3942
3943 if (server != NULL && *server != NULL) {
3944 struct mg_server *s = *server;
3945 // Do one last poll, see https://github.com/cesanta/mongoose/issues/286
3946 mg_poll_server(s, 0);
3947 closesocket(s->listening_sock);
3948 closesocket(s->ctl[0]);
3949 closesocket(s->ctl[1]);
3950 LINKED_LIST_FOREACH(&s->active_connections, lp, tmp) {
3951 close_conn(LINKED_LIST_ENTRY(lp, struct connection, link));
3952 }
3953 for (i = 0; i < (int) ARRAY_SIZE(s->config_options); i++) {
3954 free(s->config_options[i]); // It is OK to free(NULL)
3955 }
3956 #ifdef MONGOOSE_USE_SSL
3957 if (s->ssl_ctx != NULL) SSL_CTX_free((*server)->ssl_ctx);
3958 if (s->client_ssl_ctx != NULL) SSL_CTX_free(s->client_ssl_ctx);
3959 #endif
3960 free(s);
3961 *server = NULL;
3962 }
3963 }
3964
3965 // Apply function to all active connections.
mg_iterate_over_connections(struct mg_server * server,mg_handler_t handler,void * param)3966 void mg_iterate_over_connections(struct mg_server *server, mg_handler_t handler,
3967 void *param) {
3968 // Send closure (function + parameter) to the IO thread to execute
3969 union { mg_handler_t f; void *p; } msg[2];
3970 msg[0].f = handler;
3971 msg[1].p = param;
3972 send(server->ctl[0], (void *) msg, sizeof(msg), 0);
3973 }
3974
get_var(const char * data,size_t data_len,const char * name,char * dst,size_t dst_len)3975 static int get_var(const char *data, size_t data_len, const char *name,
3976 char *dst, size_t dst_len) {
3977 const char *p, *e, *s;
3978 size_t name_len;
3979 int len;
3980
3981 if (dst == NULL || dst_len == 0) {
3982 len = -2;
3983 } else if (data == NULL || name == NULL || data_len == 0) {
3984 len = -1;
3985 dst[0] = '\0';
3986 } else {
3987 name_len = strlen(name);
3988 e = data + data_len;
3989 len = -1;
3990 dst[0] = '\0';
3991
3992 // data is "var1=val1&var2=val2...". Find variable first
3993 for (p = data; p + name_len < e; p++) {
3994 if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
3995 !mg_strncasecmp(name, p, name_len)) {
3996
3997 // Point p to variable value
3998 p += name_len + 1;
3999
4000 // Point s to the end of the value
4001 s = (const char *) memchr(p, '&', (size_t)(e - p));
4002 if (s == NULL) {
4003 s = e;
4004 }
4005 assert(s >= p);
4006
4007 // Decode variable into destination buffer
4008 len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
4009
4010 // Redirect error code from -1 to -2 (destination buffer too small).
4011 if (len == -1) {
4012 len = -2;
4013 }
4014 break;
4015 }
4016 }
4017 }
4018
4019 return len;
4020 }
4021
mg_get_var(const struct mg_connection * conn,const char * name,char * dst,size_t dst_len)4022 int mg_get_var(const struct mg_connection *conn, const char *name,
4023 char *dst, size_t dst_len) {
4024 int len = get_var(conn->query_string, conn->query_string == NULL ? 0 :
4025 strlen(conn->query_string), name, dst, dst_len);
4026 if (len < 0) {
4027 len = get_var(conn->content, conn->content_len, name, dst, dst_len);
4028 }
4029 return len;
4030 }
4031
mg_url_decode_len(const char * src,int src_len)4032 int mg_url_decode_len(const char *src, int src_len) {
4033 int i, j;
4034 for (i = j = 0; i < src_len; i++, j++) {
4035 if (src[i] == '%' && i < src_len - 2 &&
4036 isxdigit(* (const unsigned char *) (src + i + 1)) &&
4037 isxdigit(* (const unsigned char *) (src + i + 2))) {
4038 i += 2;
4039 }
4040 }
4041 return i >= src_len ? j : -1;
4042 }
4043
get_var_len(const char * data,size_t data_len,const char * name)4044 int get_var_len(const char *data, size_t data_len, const char *name)
4045 {
4046 const char *p, *e, *s;
4047 size_t name_len;
4048 int len;
4049
4050 if (data == NULL || name == NULL || data_len == 0)
4051 return -1;
4052
4053 name_len = strlen(name);
4054 e = data + data_len;
4055 len = -1;
4056
4057 // data is "var1=val1&var2=val2...". Find variable first
4058 for (p = data; p + name_len < e; p++) {
4059 if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
4060 !mg_strncasecmp(name, p, name_len)) {
4061
4062 // Point p to variable value
4063 p += name_len + 1;
4064
4065 // Point s to the end of the value
4066 s = (const char *) memchr(p, '&', (size_t)(e - p));
4067 if (s == NULL) {
4068 s = e;
4069 }
4070 assert(s >= p);
4071
4072 // Decode variable into destination buffer
4073 len = mg_url_decode_len(p, (size_t)(s - p));
4074
4075 // Redirect error code from -1 to -2 (destination buffer too small).
4076 if (len == -1) {
4077 len = -2;
4078 }
4079 break;
4080 }
4081 }
4082 return len;
4083 }
4084
mg_get_var_len(const struct mg_connection * conn,const char * name)4085 int mg_get_var_len(const struct mg_connection *conn, const char *name)
4086 {
4087 int len = get_var_len(
4088 conn->query_string,
4089 conn->query_string == NULL ? 0 : strlen(conn->query_string),
4090 name);
4091 if (len < 0)
4092 len = get_var_len(
4093 conn->content,
4094 conn->content_len,
4095 name);
4096 return len;
4097 }
4098
get_line_len(const char * buf,int buf_len)4099 static int get_line_len(const char *buf, int buf_len) {
4100 int len = 0;
4101 while (len < buf_len && buf[len] != '\n') len++;
4102 return buf[len] == '\n' ? len + 1: -1;
4103 }
4104
mg_parse_multipart(const char * buf,int buf_len,char * var_name,int var_name_len,char * file_name,int file_name_len,const char ** data,int * data_len)4105 int mg_parse_multipart(const char *buf, int buf_len,
4106 char *var_name, int var_name_len,
4107 char *file_name, int file_name_len,
4108 const char **data, int *data_len) {
4109 static const char cd[] = "Content-Disposition: ";
4110 //struct mg_connection c;
4111 int hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
4112 //char *p;
4113
4114 if (buf == NULL || buf_len <= 0) return 0;
4115 if ((hl = get_request_len(buf, buf_len)) <= 0) return 0;
4116 if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
4117
4118 // Get boundary length
4119 bl = get_line_len(buf, buf_len);
4120
4121 // Loop through headers, fetch variable name and file name
4122 var_name[0] = file_name[0] = '\0';
4123 for (n = bl; (ll = get_line_len(buf + n, hl - n)) > 0; n += ll) {
4124 if (mg_strncasecmp(cd, buf + n, cdl) == 0) {
4125 parse_header(buf + n + cdl, ll - (cdl + 2), "name",
4126 var_name, var_name_len);
4127 parse_header(buf + n + cdl, ll - (cdl + 2), "filename",
4128 file_name, file_name_len);
4129 }
4130 }
4131
4132 // Scan body, search for terminating boundary
4133 for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
4134 if (buf[pos] == '-' && !memcmp(buf, &buf[pos], bl - 2)) {
4135 if (data_len != NULL) *data_len = (pos - 2) - hl;
4136 if (data != NULL) *data = buf + hl;
4137 return pos;
4138 }
4139 }
4140
4141 return 0;
4142 }
4143
mg_get_valid_option_names(void)4144 const char **mg_get_valid_option_names(void) {
4145 return static_config_options;
4146 }
4147
get_option_index(const char * name)4148 static int get_option_index(const char *name) {
4149 int i;
4150
4151 for (i = 0; static_config_options[i * 2] != NULL; i++) {
4152 if (strcmp(static_config_options[i * 2], name) == 0) {
4153 return i;
4154 }
4155 }
4156 return -1;
4157 }
4158
set_default_option_values(char ** opts)4159 static void set_default_option_values(char **opts) {
4160 const char *value, **all_opts = mg_get_valid_option_names();
4161 int i;
4162
4163 for (i = 0; all_opts[i * 2] != NULL; i++) {
4164 value = all_opts[i * 2 + 1];
4165 if (opts[i] == NULL && value != NULL) {
4166 opts[i] = mg_strdup(value);
4167 }
4168 }
4169 }
4170
4171 // Valid listening port spec is: [ip_address:]port, e.g. "80", "127.0.0.1:3128"
parse_port_string(const char * str,union socket_address * sa)4172 static int parse_port_string(const char *str, union socket_address *sa) {
4173 unsigned int a, b, c, d, port;
4174 int len = 0;
4175 #ifdef MONGOOSE_USE_IPV6
4176 char buf[100];
4177 #endif
4178
4179 // MacOS needs that. If we do not zero it, subsequent bind() will fail.
4180 // Also, all-zeroes in the socket address means binding to all addresses
4181 // for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
4182 memset(sa, 0, sizeof(*sa));
4183 sa->sin.sin_family = AF_INET;
4184
4185 if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
4186 // Bind to a specific IPv4 address, e.g. 192.168.1.5:8080
4187 sa->sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
4188 sa->sin.sin_port = htons((uint16_t) port);
4189 #if defined(MONGOOSE_USE_IPV6)
4190 } else if (sscanf(str, "[%49[^]]]:%u%n", buf, &port, &len) == 2 &&
4191 inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
4192 // IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080
4193 sa->sin6.sin6_family = AF_INET6;
4194 sa->sin6.sin6_port = htons((uint16_t) port);
4195 #endif
4196 } else if (sscanf(str, "%u%n", &port, &len) == 1) {
4197 // If only port is specified, bind to IPv4, INADDR_ANY
4198 sa->sin.sin_port = htons((uint16_t) port);
4199 } else {
4200 port = 0; // Parsing failure. Make port invalid.
4201 }
4202
4203 return port <= 0xffff && str[len] == '\0';
4204 }
4205
4206 //const char *mg_set_option(struct mg_server *server, const char *name,
mg_set_option(struct mg_server * server,const char * name,const char * value,char * error_msg)4207 int mg_set_option(struct mg_server *server, const char *name,
4208 const char *value, char* error_msg) {
4209 int ind = get_option_index(name);
4210
4211 strcpy(error_msg,"No error");
4212 if (ind < 0) {
4213 strcpy(error_msg,"No such option");
4214 } else {
4215 if (server->config_options[ind] != NULL) {
4216 free(server->config_options[ind]);
4217 }
4218 server->config_options[ind] = mg_strdup(value);
4219 DBG(("%s [%s]", name, value));
4220
4221 if (ind == LISTENING_PORT) {
4222 if (server->listening_sock != INVALID_SOCKET) {
4223 closesocket(server->listening_sock);
4224 }
4225 parse_port_string(server->config_options[LISTENING_PORT], &server->lsa);
4226 server->listening_sock = open_listening_socket(&server->lsa);
4227 if (server->listening_sock == INVALID_SOCKET) {
4228 strcpy(error_msg, mg_open_msg);
4229 return INVALID_SOCKET;
4230 } else {
4231 sockaddr_to_string(server->local_ip, sizeof(server->local_ip),
4232 &server->lsa);
4233 if (!strcmp(value, "0")) {
4234 char buf[10];
4235 mg_snprintf(buf, sizeof(buf), "%d",
4236 (int) ntohs(server->lsa.sin.sin_port));
4237 free(server->config_options[ind]);
4238 server->config_options[ind] = mg_strdup(buf);
4239 }
4240 return 0;
4241 }
4242 #ifndef _WIN32
4243 } else if (ind == RUN_AS_USER) {
4244 struct passwd *pw;
4245 if ((pw = getpwnam(value)) == NULL) {
4246 strcpy(error_msg, "Unknown user");
4247 return INVALID_SOCKET;
4248 } else if (setgid(pw->pw_gid) != 0) {
4249 strcpy(error_msg, "setgid() failed");
4250 return INVALID_SOCKET;
4251 } else if (setuid(pw->pw_uid) != 0) {
4252 strcpy(error_msg, "setuid() failed");
4253 return INVALID_SOCKET;
4254 }
4255 return 0;
4256 #endif
4257 #ifdef MONGOOSE_USE_SSL
4258 } else if (ind == SSL_CERTIFICATE) {
4259 //SSL_library_init();
4260 if ((server->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
4261 strcpy(error_msg, "SSL_CTX_new() failed");
4262 return INVALID_SOCKET;
4263 } else if (SSL_CTX_use_certificate_file(server->ssl_ctx, value, 1) == 0 ||
4264 SSL_CTX_use_PrivateKey_file(server->ssl_ctx, value, 1) == 0) {
4265 strcpy(error_msg, "Cannot load PEM file");
4266 return INVALID_SOCKET;
4267 } else {
4268 SSL_CTX_use_certificate_chain_file(server->ssl_ctx, value);
4269 }
4270 return 0;
4271 #endif
4272 }
4273 }
4274 return 0;
4275 }
4276
mg_set_request_handler(struct mg_server * server,mg_handler_t handler)4277 void mg_set_request_handler(struct mg_server *server, mg_handler_t handler) {
4278 server->request_handler = handler;
4279 }
4280
mg_set_http_error_handler(struct mg_server * server,mg_handler_t handler)4281 void mg_set_http_error_handler(struct mg_server *server, mg_handler_t handler) {
4282 server->error_handler = handler;
4283 }
4284
mg_set_auth_handler(struct mg_server * server,mg_handler_t handler)4285 void mg_set_auth_handler(struct mg_server *server, mg_handler_t handler) {
4286 server->auth_handler = handler;
4287 }
4288
mg_set_listening_socket(struct mg_server * server,int sock)4289 void mg_set_listening_socket(struct mg_server *server, int sock) {
4290 if (server->listening_sock != INVALID_SOCKET) {
4291 closesocket(server->listening_sock);
4292 }
4293 server->listening_sock = (sock_t) sock;
4294 }
4295
mg_get_listening_socket(struct mg_server * server)4296 int mg_get_listening_socket(struct mg_server *server) {
4297 return server->listening_sock;
4298 }
4299
mg_get_option(const struct mg_server * server,const char * name)4300 const char *mg_get_option(const struct mg_server *server, const char *name) {
4301 const char **opts = (const char **) server->config_options;
4302 int i = get_option_index(name);
4303 return i == -1 ? NULL : opts[i] == NULL ? "" : opts[i];
4304 }
4305
mg_create_server(void * server_data)4306 struct mg_server *mg_create_server(void *server_data) {
4307 struct mg_server *server = (struct mg_server *) calloc(1, sizeof(*server));
4308
4309 #ifdef _WIN32
4310 WSADATA data;
4311 WSAStartup(MAKEWORD(2, 2), &data);
4312 #else
4313 // Ignore SIGPIPE signal, so if browser cancels the request, it
4314 // won't kill the whole process.
4315 signal(SIGPIPE, SIG_IGN);
4316 #endif
4317
4318 LINKED_LIST_INIT(&server->active_connections);
4319
4320 // Create control socket pair. Do it in a loop to protect from
4321 // interrupted syscalls in mg_socketpair().
4322 do {
4323 mg_socketpair(server->ctl);
4324 } while (server->ctl[0] == INVALID_SOCKET);
4325
4326 #ifdef MONGOOSE_USE_SSL
4327 SSL_library_init();
4328 server->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method());
4329 #endif
4330
4331 server->server_data = server_data;
4332 server->listening_sock = INVALID_SOCKET;
4333 set_default_option_values(server->config_options);
4334
4335 return server;
4336 }
4337