source: rtems/cpukit/mghttpd/mongoose.c @ 9b4422a2

4.115
Last change on this file since 9b4422a2 was 9b4422a2, checked in by Joel Sherrill <joel.sherrill@…>, on 05/03/12 at 15:09:24

Remove All CVS Id Strings Possible Using a Script

Script does what is expected and tries to do it as
smartly as possible.

+ remove occurrences of two blank comment lines

next to each other after Id string line removed.

+ remove entire comment blocks which only exited to

contain CVS Ids

+ If the processing left a blank line at the top of

a file, it was removed.

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