/[projects]/smsdaemon/embedded-http/mongoose.c
ViewVC logotype

Annotation of /smsdaemon/embedded-http/mongoose.c

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.20