source: rtems/cpukit/mghttpd/mongoose.c @ 56f9698

4.104.115
Last change on this file since 56f9698 was 56f9698, checked in by Ralf Corsepius <ralf.corsepius@…>, on 11/17/09 at 17:15:08

Add HAVE_CONFIG_H.

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