]> git.vomp.tv Git - jsonserver.git/commitdiff
Initial import
authorChris Tallon <chris@vomp.tv>
Sat, 16 Mar 2013 14:38:43 +0000 (14:38 +0000)
committerChris Tallon <chris@vomp.tv>
Sat, 16 Mar 2013 14:38:43 +0000 (14:38 +0000)
COPYING [new file with mode: 0644]
HISTORY [new file with mode: 0644]
Makefile [new file with mode: 0644]
README [new file with mode: 0644]
handler.c [new file with mode: 0644]
handler.h [new file with mode: 0644]
jsonserver.c [new file with mode: 0644]
log.c [new file with mode: 0644]
log.h [new file with mode: 0644]
mongoose.c [new file with mode: 0644]
mongoose.h [new file with mode: 0644]

diff --git a/COPYING b/COPYING
new file mode 100644 (file)
index 0000000..f90922e
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,340 @@
+                   GNU GENERAL PUBLIC LICENSE
+                      Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                           Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                   GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+                           NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+                    END OF TERMS AND CONDITIONS
+
+           How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
diff --git a/HISTORY b/HISTORY
new file mode 100644 (file)
index 0000000..24668f3
--- /dev/null
+++ b/HISTORY
@@ -0,0 +1,6 @@
+VDR Plugin 'jsonserver' Revision History
+----------------------------------------
+
+2013-03-16: Version 0.0.1
+
+- Initial revision.
diff --git a/Makefile b/Makefile
new file mode 100644 (file)
index 0000000..586985c
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,114 @@
+#
+# Makefile for a Video Disk Recorder plugin
+#
+# $Id$
+
+# The official name of this plugin.
+# This name will be used in the '-P...' option of VDR to load the plugin.
+# By default the main source file also carries this name.
+# IMPORTANT: the presence of this macro is important for the Make.config
+# file. So it must be defined, even if it is not used here!
+#
+PLUGIN = jsonserver
+
+### The version number of this plugin (taken from the main source file):
+
+VERSION = $(shell grep 'static const char \*VERSION *=' $(PLUGIN).c | awk '{ print $$6 }' | sed -e 's/[";]//g')
+
+### The C++ compiler and options:
+
+CXX      ?= g++
+CXXFLAGS ?= -g -O3 -Wall -Werror=overloaded-virtual -Wno-parentheses -fpermissive
+
+### The directory environment:
+
+VDRDIR ?= ../../..
+LIBDIR ?= ../../lib
+TMPDIR ?= /tmp
+
+### Make sure that necessary options are included:
+
+include $(VDRDIR)/Make.global
+
+### Allow user defined options to overwrite defaults:
+
+-include $(VDRDIR)/Make.config
+
+### The version number of VDR's plugin API (taken from VDR's "config.h"):
+
+APIVERSION = $(shell sed -ne '/define APIVERSION/s/^.*"\(.*\)".*$$/\1/p' $(VDRDIR)/config.h)
+
+### The name of the distribution archive:
+
+ARCHIVE = $(PLUGIN)-$(VERSION)
+PACKAGE = vdr-$(ARCHIVE)
+
+### Includes and Defines (add further entries here):
+
+INCLUDES += -I$(VDRDIR)/include
+
+DEFINES += -D_GNU_SOURCE -DPLUGIN_NAME_I18N='"$(PLUGIN)"'
+
+### The object files (add further files here):
+
+OBJS = $(PLUGIN).o mongoose.o handler.o log.o
+
+### The main target:
+
+all: libvdr-$(PLUGIN).so i18n
+
+### Implicit rules:
+
+%.o: %.c
+       $(CXX) $(CXXFLAGS) -c $(DEFINES) $(INCLUDES) $<
+
+### Dependencies:
+
+MAKEDEP = $(CXX) -MM -MG
+DEPFILE = .dependencies
+$(DEPFILE): Makefile
+       @$(MAKEDEP) $(DEFINES) $(INCLUDES) $(OBJS:%.o=%.c) > $@
+
+-include $(DEPFILE)
+
+### Internationalization (I18N):
+
+PODIR     = po
+LOCALEDIR = $(VDRDIR)/locale
+I18Npo    = $(wildcard $(PODIR)/*.po)
+I18Nmsgs  = $(addprefix $(LOCALEDIR)/, $(addsuffix /LC_MESSAGES/vdr-$(PLUGIN).mo, $(notdir $(foreach file, $(I18Npo), $(basename $(file))))))
+I18Npot   = $(PODIR)/$(PLUGIN).pot
+
+%.mo: %.po
+       msgfmt -c -o $@ $<
+
+$(I18Npot): $(wildcard *.c)
+       xgettext -C -cTRANSLATORS --no-wrap --no-location -k -ktr -ktrNOOP --package-name=vdr-$(PLUGIN) --package-version=$(VERSION) --msgid-bugs-address='<see README>' -o $@ $^
+
+%.po: $(I18Npot)
+       msgmerge -U --no-wrap --no-location --backup=none -q $@ $<
+       @touch $@
+
+$(I18Nmsgs): $(LOCALEDIR)/%/LC_MESSAGES/vdr-$(PLUGIN).mo: $(PODIR)/%.mo
+       @mkdir -p $(dir $@)
+       cp $< $@
+
+.PHONY: i18n
+i18n: $(I18Nmsgs) $(I18Npot)
+
+### Targets:
+
+libvdr-$(PLUGIN).so: $(OBJS)
+       $(CXX) $(CXXFLAGS) $(LDFLAGS) -shared $(OBJS) -ljsoncpp -o $@
+       @cp --remove-destination $@ $(LIBDIR)/$@.$(APIVERSION)
+
+dist: $(I18Npo) clean
+       @-rm -rf $(TMPDIR)/$(ARCHIVE)
+       @mkdir $(TMPDIR)/$(ARCHIVE)
+       @cp -a * $(TMPDIR)/$(ARCHIVE)
+       @tar czf $(PACKAGE).tgz -C $(TMPDIR) $(ARCHIVE)
+       @-rm -rf $(TMPDIR)/$(ARCHIVE)
+       @echo Distribution package created as $(PACKAGE).tgz
+
+clean:
+       @-rm -f $(OBJS) $(DEPFILE) *.so *.tgz core* *~ $(PODIR)/*.mo $(PODIR)/*.pot
diff --git a/README b/README
new file mode 100644 (file)
index 0000000..91cf4b6
--- /dev/null
+++ b/README
@@ -0,0 +1,19 @@
+This is a "plugin" for the Video Disk Recorder (VDR).
+
+Written by:                  Your Name <chris@vomp.tv>
+
+Project's homepage:          http://vomp.tv/jsonserver
+
+Latest version available at: http://vomp.tv/jsonserver
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+See the file COPYING for more information.
+
+Description:
+
+A JSON data server plugin for VDR.
+
+Uses embedded Mongoose 3.7, and depends on libjsoncpp (0.6) from system.
diff --git a/handler.c b/handler.c
new file mode 100644 (file)
index 0000000..9976be8
--- /dev/null
+++ b/handler.c
@@ -0,0 +1,646 @@
+#include "handler.h"
+
+#include <string.h>
+#include <stdlib.h>
+#include <jsoncpp/json/json.h>
+#include <string>
+
+#include <vdr/videodir.h>
+#include <vdr/recording.h>
+#include <vdr/menu.h>
+#include <vdr/timers.h>
+
+#include "log.h"
+
+int jsonserver_request_handler(struct mg_connection *conn)
+{
+  Log* log = Log::getInstance();
+  const struct mg_request_info *request_info = mg_get_request_info(conn);
+  
+  if (strcmp(request_info->uri, "/jsonserver")) return 0; // not for us
+
+  char wvrequest[20];
+  int wvrl = mg_get_var(request_info->query_string, strlen(request_info->query_string), "req", wvrequest, 20);
+  if (wvrl == -1)
+  {
+    log->log("JSONServer", Log::ERR, "Could not decode req");
+    return 0;
+  }
+
+/*
+  if (!strcmp(request_info->request_method, "OPTIONS"))
+  {
+    mg_printf(conn, "%s", "HTTP/1.0 200 OK\r\n");
+    mg_printf(conn, "%s", "Access-Control-Allow-Origin: *\r\n");
+    mg_printf(conn, "%s", "Content-Type: text/plain\r\n\r\n");
+    return (void*)1;
+  }
+*/
+
+  // Get POST data
+  char postData[10000];
+  postData[0] = '\0';
+  if (!strcmp(request_info->request_method, "POST"))
+  {
+    const char* contentLength = mg_get_header(conn, "Content-Length");
+    int contentLengthI = atoi(contentLength);
+    log->log("JSONServer", Log::DEBUG, "POST data content length: %i", contentLengthI);
+    if (contentLengthI > 10000)
+    {
+      log->log("JSONServer", Log::DEBUG, "Length > 10000, rejecting");
+      return 0;
+    }
+
+    if (contentLengthI > 0)
+    {
+      // FIXME - assume for now that all post data will be small enough to have arrived immediately
+      int bytesRead = mg_read(conn, postData, contentLengthI);
+      if (bytesRead != contentLengthI)
+      {
+        log->log("JSONServer", Log::DEBUG, "Could not read up to contentLength");
+        return 0;
+      }
+    }
+  }
+
+  Json::Value js;
+  bool success = false;
+
+  if      (!strcmp(wvrequest, "reclist")) success = jsonserver_reclist(js);
+  else if (!strcmp(wvrequest, "recinfo")) success = jsonserver_recinfo(js, postData);
+  else if (!strcmp(wvrequest, "recdel")) success = jsonserver_recdel(js, postData);
+  else if (!strcmp(wvrequest, "recmove")) success = jsonserver_recmove(js, postData);
+  else if (!strcmp(wvrequest, "channellist")) success = jsonserver_channellist(js);
+  else if (!strcmp(wvrequest, "channelschedule")) success = jsonserver_channelschedule(js, postData);
+  else if (!strcmp(wvrequest, "timerlist")) success = jsonserver_timerlist(js);
+  else if (!strcmp(wvrequest, "timerdel")) success = jsonserver_timerdel(js, postData);
+  else if (!strcmp(wvrequest, "timerset")) success = jsonserver_timerset(js, postData);
+
+  if (!success) return 0; // the specific handler failed badly
+
+  // Now js will be filled
+
+  Json::StyledWriter sw;
+  std::string jsonout = sw.write(js);
+  mg_printf(conn, "%s", "HTTP/1.0 200 OK\r\n");
+  mg_printf(conn, "%s", "Content-Type: text/plain\r\n\r\n");
+  mg_write(conn, jsonout.c_str(), jsonout.length());
+  return 1;
+
+  
+/*
+  else if (event == MG_EVENT_LOG)
+  {
+    if (request_info->status_code == 400) // bad request
+    {
+      log->log("Mongoose", Log::DEBUG, "400 BAD REQUEST:");
+      log->log("Mongoose", Log::DEBUG, request_info->request_method);
+      log->log("Mongoose", Log::DEBUG, request_info->uri);
+      log->log("Mongoose", Log::DEBUG, request_info->http_version);
+      log->log("Mongoose", Log::DEBUG, request_info->query_string);
+      log->log("Mongoose", Log::DEBUG, request_info->log_message);
+      for (int i = 0; i < request_info->num_headers; i++)
+      {
+        log->log("Mongoose", Log::DEBUG, "%s: %s", request_info->http_headers[i].name, request_info->http_headers[i].value);
+      }
+    }
+    else
+    {
+      log->log("Mongoose", Log::DEBUG, request_info->log_message);
+      log->log("Mongoose", Log::DEBUG, request_info->uri);
+    }
+    return (void*)1;
+  }
+  
+  // other events not handled:
+  // MG_HTTP_ERROR, MG_INIT_SSL
+  // Let mongoose do something with those
+
+  return NULL;
+
+*/
+  
+}
+
+bool jsonserver_reclist(Json::Value& js)
+{
+  Log* log = Log::getInstance();
+  log->log("JSONServer", Log::DEBUG, "reclist");
+
+  int FreeMB;
+  int Percent = VideoDiskSpace(&FreeMB);
+  int Total = (FreeMB / (100 - Percent)) * 100;
+        
+  js["MBFree"] = FreeMB;
+  js["Percent"] = Percent;
+  js["Total"] = Total;
+  
+  Json::Value jsrecordings;
+  cRecordings Recordings;
+  Recordings.Load();
+  for (cRecording *recording = Recordings.First(); recording; recording = Recordings.Next(recording))
+  {
+    Json::Value oneRec;
+    oneRec["StartTime"] = (Json::UInt)recording->Start();
+    oneRec["Name"] = recording->Name();
+    oneRec["Filename"] = recording->FileName();
+    jsrecordings.append(oneRec);
+  }
+  js["Recordings"] = jsrecordings;
+  
+  return true;
+}
+
+bool jsonserver_recinfo(Json::Value& js, const char* postData)
+{
+  // For now this returns just the string summary of the recording
+
+  Log* log = Log::getInstance();
+  log->log("JSONServer", Log::DEBUG, "recinfo");
+
+  char reqfilename[1000];
+  int mgv1 = mg_get_var(postData, strlen(postData), "filename", reqfilename, 1000);
+  if (mgv1 == -1)
+  {
+    log->log("JSONServer", Log::ERR, "Could not decode filename");
+    js["Result"] = false;
+    js["Error"] = "Could not decode filename";
+    return true;
+  }
+
+  log->log("JSONServer", Log::DEBUG, "%s", reqfilename);
+  
+  cRecordings Recordings;
+  Recordings.Load(); // probably have to do this
+  cRecording *recording = Recordings.GetByName(reqfilename);
+
+  if (recording)
+  {
+    const cRecordingInfo *Info = recording->Info();
+    char* summary = (char*)Info->ShortText();
+    if (isempty(summary)) summary = (char*)Info->Description();
+    js["Result"] = true;
+    js["Summary"] = summary;
+  }
+  else
+  {
+    log->log("JSONServer", Log::ERR, "recinfo found no recording");
+    js["Result"] = false;
+    js["Summary"] = "";
+  }  
+
+  return true;
+}
+
+bool jsonserver_recdel(Json::Value& js, const char* postData)
+{
+  Log* log = Log::getInstance();
+  log->log("JSONServer", Log::DEBUG, "recdel");
+
+  char reqfilename[1000];
+  int mgv1 = mg_get_var(postData, strlen(postData), "filename", reqfilename, 1000);
+  if (mgv1 == -1)
+  {
+    log->log("JSONServer", Log::ERR, "Could not decode filename");
+    js["Result"] = false;
+    js["Error"] = "Could not decode filename";
+    return true;
+  }
+
+  log->log("JSONServer", Log::DEBUG, "%s", reqfilename);
+  
+  cRecordings Recordings;
+  Recordings.Load(); // probably have to do this
+  cRecording *recording = Recordings.GetByName(reqfilename);
+
+  if (!recording)
+  {
+    js["Result"] = false;
+    js["Error"] = "Could not find recording to delete";
+    return true;
+  }
+
+  log->log("JSONServer", Log::DEBUG, "Deleting recording: %s", recording->Name());
+  cRecordControl *rc = cRecordControls::GetRecordControl(recording->FileName());
+  if (rc)
+  {
+    js["Result"] = false;
+    js["Error"] = "This recording is still recording.. ho ho";
+    return true;
+  }
+
+  if (recording->Delete())
+  {
+    ::Recordings.DelByName(recording->FileName());
+    js["Result"] = true;
+  }
+  else
+  {
+    js["Result"] = false;
+    js["Error"] = "Failed to delete recording";
+  }
+
+  return true;
+}
+
+bool jsonserver_recmove(Json::Value& js, const char* postData)
+{
+  Log* log = Log::getInstance();
+  log->log("JSONServer", Log::DEBUG, "recmove");
+
+  char sFileName[1000]; int mgv1 = mg_get_var(postData, strlen(postData), "filename", sFileName, 1000);  
+  char sNewPath[1000];  int mgv2 = mg_get_var(postData, strlen(postData), "newpath", sNewPath, 1000);  
+
+  if ( (mgv1 == -1) || (mgv2 == -1) || !strlen(sFileName) || !strlen(sNewPath) )
+  {
+    log->log("JSONServer", Log::ERR, "request mgvs: %i %i", mgv1, mgv2);
+    js["Result"] = false;
+    js["Error"] = "Bad request parameters";
+    return true;
+  }
+
+  cRecordings Recordings;
+  Recordings.Load(); // probably have to do this
+  cRecording* recording = Recordings.GetByName(sFileName);
+
+  if (!recording)
+  {
+    log->log("JSONServer", Log::ERR, "Could not find recording to move");
+    js["Result"] = false;
+    js["Error"] = "Bad filename";
+    return true;
+  }
+
+  cRecordControl *rc = cRecordControls::GetRecordControl(recording->FileName());
+  if (rc)
+  {
+    log->log("JSONServer", Log::ERR, "Could not move recording, it is still recording");
+    js["Result"] = false;
+    js["Error"] = "Cannot move recording in progress";
+    return true;
+  }
+  
+  log->log("JSONServer", Log::DEBUG, "moving recording: %s", recording->Name());
+  log->log("JSONServer", Log::DEBUG, "moving recording: %s", recording->FileName());
+  log->log("JSONServer", Log::DEBUG, "to: %s", sNewPath);
+
+  const char* t = recording->FileName();
+
+  char* dateDirName = NULL;   int k;
+  char* titleDirName = NULL;  int j;
+  char* newContainer = NULL;
+
+  // Find the datedirname
+  for(k = strlen(t) - 1; k >= 0; k--)
+  {
+    if (t[k] == '/')
+    {
+      log->log("JSONServer", Log::DEBUG, "l1: %i", strlen(&t[k+1]) + 1);
+      dateDirName = new char[strlen(&t[k+1]) + 1];
+      strcpy(dateDirName, &t[k+1]);
+      break;
+    }
+  }
+
+  // Find the titledirname
+
+  for(j = k-1; j >= 0; j--)
+  {
+    if (t[j] == '/')
+    {
+      log->log("JSONServer", Log::DEBUG, "l2: %i", (k - j - 1) + 1);
+      titleDirName = new char[(k - j - 1) + 1];
+      memcpy(titleDirName, &t[j+1], k - j - 1);
+      titleDirName[k - j - 1] = '\0';
+      break;
+    }
+  }
+
+  log->log("JSONServer", Log::DEBUG, "datedirname: %s", dateDirName);
+  log->log("JSONServer", Log::DEBUG, "titledirname: %s", titleDirName);
+  log->log("JSONServer", Log::DEBUG, "viddir: %s", VideoDirectory);
+
+  ExchangeChars(sNewPath, true);
+  log->log("JSONServer", Log::DEBUG, "EC: %s", sNewPath);
+
+  newContainer = new char[strlen(VideoDirectory) + strlen(sNewPath) + strlen(titleDirName) + 1];
+  log->log("JSONServer", Log::DEBUG, "l10: %i", strlen(VideoDirectory) + strlen(sNewPath) + strlen(titleDirName) + 1);
+  sprintf(newContainer, "%s%s%s", VideoDirectory, sNewPath, titleDirName);
+  log->log("JSONServer", Log::DEBUG, "%s", newContainer);
+
+  struct stat dstat;
+  int statret = stat(newContainer, &dstat);
+  if ((statret == -1) && (errno == ENOENT)) // Dir does not exist
+  {
+    log->log("JSONServer", Log::DEBUG, "new dir does not exist");
+    int mkdirret = mkdir(newContainer, 0755);
+    if (mkdirret != 0)
+    {
+      delete[] dateDirName;
+      delete[] titleDirName;
+      delete[] newContainer;
+
+      log->log("JSONServer", Log::ERR, "Failed to make new dir");
+      js["Result"] = false;
+      js["Error"] = "Failed to create new directory";
+      return true;
+    }
+  }
+  else if ((statret == 0) && (! (dstat.st_mode && S_IFDIR))) // Something exists but it's not a dir
+  {
+    delete[] dateDirName;
+    delete[] titleDirName;
+    delete[] newContainer;
+
+    log->log("JSONServer", Log::ERR, "Something already exists?");
+    js["Result"] = false;
+    js["Error"] = "Something already exists at the new path";
+    return true;
+  }
+
+  // Ok, the directory container has been made, or it pre-existed.
+
+  char* newDir = new char[strlen(newContainer) + 1 + strlen(dateDirName) + 1];
+  sprintf(newDir, "%s/%s", newContainer, dateDirName);
+
+  log->log("JSONServer", Log::DEBUG, "doing rename '%s' '%s'", t, newDir);
+  int renameret = rename(t, newDir);
+  if (renameret == 0)
+  {
+    // Success. Test for remove old dir containter
+    char* oldTitleDir = new char[k+1];
+    memcpy(oldTitleDir, t, k);
+    oldTitleDir[k] = '\0';
+    log->log("JSONServer", Log::DEBUG, "len: %i, cp: %i, strlen: %i, oldtitledir: %s", k+1, k, strlen(oldTitleDir), oldTitleDir);
+    rmdir(oldTitleDir); // can't do anything about a fail result at this point.
+    delete[] oldTitleDir;
+
+    ::Recordings.Update();
+    js["Result"] = true;
+  }
+  else
+  {
+    log->log("JSONServer", Log::ERR, "Rename failed");
+    js["Result"] = false;
+    js["Error"] = "Move failed";
+  }
+
+  delete[] dateDirName;
+  delete[] titleDirName;
+  delete[] newContainer;
+  delete[] newDir;
+
+  return true;
+}
+
+bool jsonserver_channellist(Json::Value& js)
+{
+  Log* log = Log::getInstance();
+  log->log("JSONServer", Log::DEBUG, "channellist");
+
+  Json::Value jschannels;
+  
+  int type;
+  for (cChannel *channel = Channels.First(); channel; channel = Channels.Next(channel))
+  {
+    if (!channel->GroupSep())
+    {
+      log->log("JSONServer", Log::DEBUG, "name: '%s'", channel->Name());
+
+      if (channel->Vpid()) type = 1;
+      else if (channel->Apid(0)) type = 2;
+      else continue;
+
+      Json::Value oneChannel;
+      oneChannel["Number"] = channel->Number();
+      oneChannel["Type"] = type;
+      oneChannel["Name"] = channel->Name();
+#if VDRVERSNUM < 10703
+      oneChannel["VType"] = 2;
+#else
+      oneChannel["VType"] = channel->Vtype();
+#endif
+      jschannels.append(oneChannel);    
+    }
+  }
+  js["Channels"] = jschannels;
+  
+  return true;
+}
+
+bool jsonserver_channelschedule(Json::Value& js, const char* postData)
+{
+  Log* log = Log::getInstance();
+  log->log("JSONServer", Log::DEBUG, "channelschedule '%s'", postData);
+
+  char sChannelNumber[15];  int mgv1 = mg_get_var(postData, strlen(postData), "channelnumber", sChannelNumber, 15);  
+  char sStartTime[15];      int mgv2 = mg_get_var(postData, strlen(postData), "starttime", sStartTime, 15);  
+  char sDuration[15];       int mgv3 = mg_get_var(postData, strlen(postData), "duration", sDuration, 15);  
+
+  if ( (mgv1 == -1) || (mgv2 == -1) || (mgv3 == -1) )
+  {
+    log->log("JSONServer", Log::ERR, "request mgvs: %i %i %i", mgv1, mgv2, mgv3);
+    js["Result"] = false;
+    js["Error"] = "Bad request parameters";
+    return true;
+  }
+
+  int channelNumber = atoi(sChannelNumber);
+  int startTime = atoi(sStartTime); 
+  int duration = atoi(sDuration); 
+
+  cChannel* channel = NULL;
+  for (channel = Channels.First(); channel; channel = Channels.Next(channel))
+  {
+    if (channel->GroupSep()) continue;
+    if (channel->Number() == channelNumber) break;
+  }
+
+  if (!channel)
+  {
+    log->log("JSONServer", Log::ERR, "Could not find requested channel: %i", channelNumber);
+    js["Result"] = false;
+    js["Error"] = "Could not find channel";
+    return true;
+  }
+
+  cSchedulesLock MutexLock;
+  const cSchedules *Schedules = cSchedules::Schedules(MutexLock);
+  if (!Schedules)
+  {
+    log->log("JSONServer", Log::ERR, "Could not find requested channel: %i", channelNumber);
+    js["Result"] = false;
+    js["Error"] = "Internal schedules error (1)";
+    return true;
+  }
+  const cSchedule *Schedule = Schedules->GetSchedule(channel->GetChannelID());
+  if (!Schedule)     
+  {
+    log->log("JSONServer", Log::ERR, "Could not find requested channel: %i", channelNumber);
+    js["Result"] = false;
+    js["Error"] = "Internal schedules error (2)";
+    return true;
+  }
+    
+  Json::Value jsevents;
+
+  for (const cEvent* event = Schedule->Events()->First(); event; event = Schedule->Events()->Next(event))
+  {
+    //in the past filter
+    if ((event->StartTime() + event->Duration()) < time(NULL)) continue;
+   //start time filter
+    if ((event->StartTime() + event->Duration()) <= startTime) continue;
+    //duration filter
+    if (event->StartTime() >= (startTime + duration)) continue;
+
+    Json::Value oneEvent;
+    oneEvent["ID"] = event->EventID();
+    oneEvent["Time"] = (Json::UInt)event->StartTime();
+    oneEvent["Duration"] = event->Duration();
+    oneEvent["Title"] = event->Title() ? event->Title() : "";
+    oneEvent["Description"] = event->Description() ? event->Description() : "";
+    jsevents.append(oneEvent);
+  }
+
+  js["Events"] = jsevents;
+  return true;
+}
+
+bool jsonserver_timerlist(Json::Value& js)
+{
+  Log* log = Log::getInstance();
+  log->log("JSONServer", Log::DEBUG, "timerlist");
+
+  Json::Value jstimers;
+  
+  cTimer *timer;
+  int numTimers = Timers.Count();
+
+  for (int i = 0; i < numTimers; i++)
+  {
+    timer = Timers.Get(i);
+    Json::Value oneTimer;
+    oneTimer["Active"] = timer->HasFlags(tfActive);
+    oneTimer["Recording"] = timer->Recording();
+    oneTimer["Pending"] = timer->Pending();
+    oneTimer["Priority"] = timer->Priority();
+    oneTimer["Lifetime"] = timer->Lifetime();
+    oneTimer["ChannelNumber"] = timer->Channel()->Number();
+    oneTimer["StartTime"] = (int)timer->StartTime();
+    oneTimer["StopTime"] = (int)timer->StopTime();
+    oneTimer["Day"] = (int)timer->Day();
+    oneTimer["WeekDays"] = timer->WeekDays();
+    oneTimer["Name"] = timer->File();
+    jstimers.append(oneTimer);
+  }
+  
+  js["Timers"] = jstimers;
+  return true;
+}
+
+bool jsonserver_timerdel(Json::Value& js, const char* postData)
+{
+  Log* log = Log::getInstance();
+  log->log("JSONServer", Log::DEBUG, "timerdel");
+
+  char sdelChannel[15];   int mgv1 = mg_get_var(postData, strlen(postData), "delchannel", sdelChannel, 15);  
+  char sdelWeekdays[15];  int mgv2 = mg_get_var(postData, strlen(postData), "delweekdays", sdelWeekdays, 15);  
+  char sdelDay[15];       int mgv3 = mg_get_var(postData, strlen(postData), "delday", sdelDay, 15);  
+  char sdelStart[15];     int mgv4 = mg_get_var(postData, strlen(postData), "delstart", sdelStart, 15);  
+  char sdelStop[15];      int mgv5 = mg_get_var(postData, strlen(postData), "delstop", sdelStop, 15);  
+
+  if ( (mgv1 == -1) || (mgv2 == -1) || (mgv3 == -1) || (mgv4 == -1) || (mgv5 == -1) )
+  {
+    log->log("JSONServer", Log::ERR, "request mgvs: %i %i %i %i %i", mgv1, mgv2, mgv3, mgv4, mgv5);
+    js["Result"] = false;
+    js["Error"] = "Bad request parameters";
+    return true;
+  }
+
+  int delChannel = atoi(sdelChannel); 
+  int delWeekdays = atoi(sdelWeekdays); 
+  int delDay = atoi(sdelDay); 
+  int delStart = atoi(sdelStart); 
+  int delStop = atoi(sdelStop); 
+
+  cTimer* ti = NULL;
+  for (ti = Timers.First(); ti; ti = Timers.Next(ti))
+  {
+    if  ( (ti->Channel()->Number() == delChannel)
+     &&   ((ti->WeekDays() && (ti->WeekDays() == delWeekdays)) || (!ti->WeekDays() && (ti->Day() == delDay)))
+     &&   (ti->StartTime() == delStart)
+     &&   (ti->StopTime() == delStop) )
+       break;
+  }
+  
+  if (!ti)
+  {
+    log->log("JSONServer", Log::ERR, "Could not find timer");
+    js["Result"] = false;
+    js["Error"] = "Could not find timer";
+    return true;
+  }
+
+  if (Timers.BeingEdited())
+  {
+    log->log("JSONServer", Log::ERR, "Unable to delete timer - timers being edited at VDR");
+    js["Result"] = false;
+    js["Error"] = "Timers being edited at VDR";
+    return true; 
+  }
+  
+  if (ti->Recording())
+  {
+    log->log("JSONServer", Log::ERR, "Unable to delete timer - timer is running");
+    js["Result"] = false;
+    js["Error"] = "Timer is running";
+    return true;
+  }
+  
+  Timers.Del(ti);
+  Timers.SetModified();
+  js["Result"] = true;
+    
+  return true;
+}
+
+bool jsonserver_timerset(Json::Value& js, const char* postData)
+{
+  Log* log = Log::getInstance();
+  log->log("JSONServer", Log::DEBUG, "timerset");
+
+  char sTimerString[1024];   int mgv1 = mg_get_var(postData, strlen(postData), "timerstring", sTimerString, 1024);  
+
+  if (mgv1 == -1)
+  {
+    log->log("JSONServer", Log::ERR, "Could not get timerstring");
+    js["Result"] = false;
+    js["Error"] = "Bad request parameters";
+    return true;
+  }
+
+  log->log("JSONServer", Log::DEBUG, "'%s'", sTimerString);
+  cTimer *timer = new cTimer;
+  if (!timer->Parse(sTimerString))
+  {
+    delete timer;
+    js["Result"] = false;
+    js["Error"] = "Failed to parse timer request details";
+    return true;
+  }
+
+  cTimer *t = Timers.GetTimer(timer);
+  if (t)
+  {
+    delete timer;
+    js["Result"] = false;
+    js["Error"] = "Timer already exists";
+    return true;
+  }
+
+  Timers.Add(timer);
+  Timers.SetModified();
+  js["Result"] = true;
+  return true;
+}
+
diff --git a/handler.h b/handler.h
new file mode 100644 (file)
index 0000000..e58993a
--- /dev/null
+++ b/handler.h
@@ -0,0 +1,20 @@
+#ifndef JSONSERVERHANDLER_H
+#define JSONSERVERHANDLER_H
+
+#include <jsoncpp/json/json.h>
+#include "mongoose.h"
+
+int jsonserver_request_handler(struct mg_connection* conn);
+
+bool jsonserver_reclist(Json::Value& js);
+bool jsonserver_recinfo(Json::Value& js, const char* postData);
+bool jsonserver_recdel(Json::Value& js, const char* postData);
+bool jsonserver_recmove(Json::Value& js, const char* postData);
+bool jsonserver_channellist(Json::Value& js);
+bool jsonserver_channelschedule(Json::Value& js, const char* postData);
+bool jsonserver_timerlist(Json::Value& js);
+bool jsonserver_timerdel(Json::Value& js, const char* postData);
+bool jsonserver_timerset(Json::Value& js, const char* postData);
+
+#endif
+
diff --git a/jsonserver.c b/jsonserver.c
new file mode 100644 (file)
index 0000000..2e4ede0
--- /dev/null
@@ -0,0 +1,169 @@
+/*
+ * jsonserver.c: A plugin for the Video Disk Recorder
+ *
+ * See the README file for copyright information and how to reach the author.
+ *
+ */
+
+#include <vdr/plugin.h>
+
+#include "mongoose.h"
+#include "handler.h"
+#include "log.h"
+
+static const char *VERSION        = "0.0.1";
+static const char *DESCRIPTION    = "JSON data server plugin for VDR";
+static const char *MAINMENUENTRY  = "Jsonserver";
+
+class cPluginJsonserver : public cPlugin {
+private:
+  // Add any member variables or functions you may need here.
+  struct mg_context *mg;
+  Log* log;  
+public:
+  cPluginJsonserver(void);
+  virtual ~cPluginJsonserver();
+  virtual const char *Version(void) { return VERSION; }
+  virtual const char *Description(void) { return DESCRIPTION; }
+  virtual const char *CommandLineHelp(void);
+  virtual bool ProcessArgs(int argc, char *argv[]);
+  virtual bool Initialize(void);
+  virtual bool Start(void);
+  virtual void Stop(void);
+  virtual void Housekeeping(void);
+  virtual void MainThreadHook(void);
+  virtual cString Active(void);
+  virtual time_t WakeupTime(void);
+  virtual const char *MainMenuEntry(void) { return MAINMENUENTRY; }
+  virtual cOsdObject *MainMenuAction(void);
+  virtual cMenuSetupPage *SetupMenu(void);
+  virtual bool SetupParse(const char *Name, const char *Value);
+  virtual bool Service(const char *Id, void *Data = NULL);
+  virtual const char **SVDRPHelpPages(void);
+  virtual cString SVDRPCommand(const char *Command, const char *Option, int &ReplyCode);
+  };
+
+cPluginJsonserver::cPluginJsonserver(void)
+{
+  // Initialize any member variables here.
+  // DON'T DO ANYTHING ELSE THAT MAY HAVE SIDE EFFECTS, REQUIRE GLOBAL
+  // VDR OBJECTS TO EXIST OR PRODUCE ANY OUTPUT!
+
+  log = new Log();
+  if (log) log->init(Log::DEBUG, "/tmp/jsonserver.log");
+}
+
+cPluginJsonserver::~cPluginJsonserver()
+{
+  // Clean up after yourself!
+  delete log;
+  log = NULL;
+}
+
+const char *cPluginJsonserver::CommandLineHelp(void)
+{
+  // Return a string that describes all known command line options.
+  return NULL;
+}
+
+bool cPluginJsonserver::ProcessArgs(int argc, char *argv[])
+{
+  // Implement command line argument processing here if applicable.
+  return true;
+}
+
+bool cPluginJsonserver::Initialize(void)
+{
+  // Initialize any background activities the plugin shall perform.
+  return true;
+}
+
+bool cPluginJsonserver::Start(void)
+{
+  // Start any background activities the plugin shall perform.
+
+  // Make Mongoose options
+  const char *options[] =
+  {
+    "document_root", "/home/chris/dvb/vdr-1.7.32/PLUGINS/src/jsonserver/docroot",
+    "listening_ports", "8005",
+    "num_threads", "5",
+    NULL
+  };
+
+  // Prepare callbacks structure. We have only one callback, the rest are NULL.
+  struct mg_callbacks callbacks;
+  memset(&callbacks, 0, sizeof(callbacks));
+  callbacks.begin_request = jsonserver_request_handler;
+  
+  mg = mg_start(&callbacks, NULL, options);
+  log->log("JSONServer", Log::INFO, "Mongoose started");
+  return true;
+}
+
+void cPluginJsonserver::Stop(void)
+{
+  // Stop any background activities the plugin is performing.
+  mg_stop(mg);
+}
+
+void cPluginJsonserver::Housekeeping(void)
+{
+  // Perform any cleanup or other regular tasks.
+}
+
+void cPluginJsonserver::MainThreadHook(void)
+{
+  // Perform actions in the context of the main program thread.
+  // WARNING: Use with great care - see PLUGINS.html!
+}
+
+cString cPluginJsonserver::Active(void)
+{
+  // Return a message string if shutdown should be postponed
+  return NULL;
+}
+
+time_t cPluginJsonserver::WakeupTime(void)
+{
+  // Return custom wakeup time for shutdown script
+  return 0;
+}
+
+cOsdObject *cPluginJsonserver::MainMenuAction(void)
+{
+  // Perform the action when selected from the main VDR menu.
+  return NULL;
+}
+
+cMenuSetupPage *cPluginJsonserver::SetupMenu(void)
+{
+  // Return a setup menu in case the plugin supports one.
+  return NULL;
+}
+
+bool cPluginJsonserver::SetupParse(const char *Name, const char *Value)
+{
+  // Parse your own setup parameters and store their values.
+  return false;
+}
+
+bool cPluginJsonserver::Service(const char *Id, void *Data)
+{
+  // Handle custom service requests from other plugins
+  return false;
+}
+
+const char **cPluginJsonserver::SVDRPHelpPages(void)
+{
+  // Return help text for SVDRP commands this plugin implements
+  return NULL;
+}
+
+cString cPluginJsonserver::SVDRPCommand(const char *Command, const char *Option, int &ReplyCode)
+{
+  // Process SVDRP commands this plugin implements
+  return NULL;
+}
+
+VDRPLUGINCREATOR(cPluginJsonserver); // Don't touch this!
diff --git a/log.c b/log.c
new file mode 100644 (file)
index 0000000..49a9add
--- /dev/null
+++ b/log.c
@@ -0,0 +1,158 @@
+/*
+    Copyright 2004-2013 Chris Tallon
+    Copyright 2003-2004 University Of Bradford
+
+    This file is part of VOMP.
+
+    VOMP is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    VOMP is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with VOMP; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+*/
+
+#include <time.h>
+#include <sys/time.h>
+#include <string.h>
+#include <stdarg.h>
+
+#include "log.h"
+
+Log* Log::instance = NULL;
+
+Log::Log()
+{
+  if (instance) return;
+  instance = this;
+  logfile = NULL;
+  initted = 0;
+  logLevel = 0;
+}
+
+Log::~Log()
+{
+  instance = NULL;
+}
+
+Log* Log::getInstance()
+{
+  return instance;
+}
+
+void Log::upLogLevel()
+{
+  if (!initted) return;
+
+  if (logLevel == Log::DEBUG)
+  {
+    log("Log", logLevel, "Log level is at its highest already");
+    return;
+  }
+
+  logLevel++;
+  log("Log", logLevel, "Log level is now %i", logLevel);
+}
+
+void Log::downLogLevel()
+{
+  if (!initted) return;
+
+  if (logLevel == Log::CRAZY)
+  {
+    log("Log", logLevel, "Log level is at its lowest already");
+    return;
+  }
+
+  logLevel--;
+  log("Log", logLevel, "Log level is now %i", logLevel);
+}
+
+int Log::init(int startLogLevel, const char* fileName)
+{
+  logLevel = startLogLevel;
+
+  logfile = fopen(fileName, "a");
+  if (logfile)
+  {
+    initted = 1;
+    return 1;
+  }
+  else
+  {
+    return 0;
+  }
+}
+
+int Log::shutdown()
+{
+  if (!initted) return 1;
+  initted = 0;
+  if (logfile) fclose(logfile);
+  return 1;
+}
+
+int Log::log(const char *fromModule, int level, const char* message, ...)
+{
+  if (!initted) return 0;
+
+  if (level > logLevel) return 1;
+
+  int lineLength = 250;
+
+  char buffer[lineLength + 1];
+  int spaceLeft = lineLength;
+
+  struct timeval tv;
+  gettimeofday(&tv, NULL);
+  struct tm* tm = localtime(&tv.tv_sec);
+  spaceLeft -= strftime(buffer, spaceLeft, "%H:%M:%S.", tm);
+  spaceLeft -= snprintf(&buffer[lineLength-spaceLeft], spaceLeft, "%06lu ", (unsigned long)tv.tv_usec);
+
+
+  char levelString[10];
+  if (level == CRAZY)   strcpy(levelString, "[CRAZY] ");
+  if (level == EMERG)   strcpy(levelString, "[EMERG] ");
+  if (level == ALERT)   strcpy(levelString, "[ALERT] ");
+  if (level == CRIT)    strcpy(levelString, "[CRIT]  ");
+  if (level == ERR)     strcpy(levelString, "[ERR]   ");
+  if (level == WARN)    strcpy(levelString, "[WARN]  ");
+  if (level == NOTICE)  strcpy(levelString, "[notice]");
+  if (level == INFO)    strcpy(levelString, "[info]  ");
+  if (level == DEBUG)   strcpy(levelString, "[debug] ");
+
+  spaceLeft -= snprintf(&buffer[lineLength-spaceLeft], spaceLeft, "%s %s - ", levelString, fromModule);
+
+  va_list ap;
+  va_start(ap, message);
+  spaceLeft = vsnprintf(&buffer[lineLength-spaceLeft], spaceLeft, message, ap);
+  va_end(ap);
+
+  int messageLength = strlen(buffer);
+  if (messageLength < lineLength)
+  {
+    buffer[messageLength] = '\n';
+    buffer[messageLength+1] = '\0';
+  }
+  else
+  {
+    buffer[lineLength-1] = '\n';
+    buffer[lineLength] = '\0';
+  }
+
+  int success = fputs(buffer, logfile);
+  fflush(NULL);
+
+  if (success != EOF)
+    return 1;
+  else
+    return 0;
+
+}
diff --git a/log.h b/log.h
new file mode 100644 (file)
index 0000000..50741d2
--- /dev/null
+++ b/log.h
@@ -0,0 +1,84 @@
+/*
+    Copyright 2004-2013 Chris Tallon
+    Copyright 2003-2004 University Of Bradford
+
+    This file is part of VOMP.
+
+    VOMP is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    VOMP is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with VOMP; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+*/
+
+#ifndef LOG_H
+#define LOG_H
+
+#include <stdio.h>
+
+class Log
+{
+  public:
+    Log();
+    ~Log();
+    static Log* getInstance();
+
+    int init(int defaultLevel, const char* fileName);
+    int shutdown();
+    int log(const char *fromModule, int level, const char *message, ...);
+    void upLogLevel();
+    void downLogLevel();
+
+    const static int CRAZY  = 0; // mad crazy things that should never happen
+    const static int EMERG  = 1; // human assist required NOW
+    const static int ALERT  = 2; // system unusable, but happy to sit there
+    const static int CRIT   = 3; // still working, but maybe about to die
+    const static int ERR    = 4; // that response is not even listed...
+    const static int WARN   = 5; // this could be a bad thing. still running tho
+    const static int NOTICE = 6; // significant good thing
+    const static int INFO   = 7; // verbose good thing
+    const static int DEBUG  = 8; // debug-level messages
+
+  private:
+    static Log* instance;
+    int initted;
+    int logLevel;
+    int enabled;
+
+    FILE *logfile;
+};
+
+#endif
+
+/*
+
+Documentation
+-------------
+
+This class is intended to be instatiated once by the core.
+For a one off use:
+
+Log::getInstance()->log("<module-name>", Log::<levelname>, "<message>");
+
+Or, a pointer can be stored and used:
+
+Log *myptr = Log::getInstance();
+
+myptr->log("<module-name>", Log::<levelname>, "<message>");
+myptr->log("<module-name>", Log::<levelname>, "<message>");
+
+Level usages are above.
+
+The message parameter in the log function can be used in the same way as printf, eg.
+
+myptr->log("<module-name>", Log::<levelname>, "Success: %s %i", stringpointer, integer);
+
+*/
diff --git a/mongoose.c b/mongoose.c
new file mode 100644 (file)
index 0000000..6fc3d17
--- /dev/null
@@ -0,0 +1,5180 @@
+// Copyright (c) 2004-2013 Sergey Lyubka\r
+//\r
+// Permission is hereby granted, free of charge, to any person obtaining a copy\r
+// of this software and associated documentation files (the "Software"), to deal\r
+// in the Software without restriction, including without limitation the rights\r
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r
+// copies of the Software, and to permit persons to whom the Software is\r
+// furnished to do so, subject to the following conditions:\r
+//\r
+// The above copyright notice and this permission notice shall be included in\r
+// all copies or substantial portions of the Software.\r
+//\r
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r
+// THE SOFTWARE.\r
+\r
+#if defined(_WIN32)\r
+#define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005\r
+#else\r
+#ifdef __linux__\r
+#define _XOPEN_SOURCE 600     // For flockfile() on Linux\r
+#endif\r
+//#define _LARGEFILE_SOURCE     // Enable 64-bit file offsets\r
+#define __STDC_FORMAT_MACROS  // <inttypes.h> wants this for C++\r
+#define __STDC_LIMIT_MACROS   // C++ wants that for INT64_MAX\r
+#endif\r
+\r
+#if defined (_MSC_VER)\r
+// conditional expression is constant: introduced by FD_SET(..)\r
+#pragma warning (disable : 4127)\r
+// non-constant aggregate initializer: issued due to missing C99 support\r
+#pragma warning (disable : 4204)\r
+#endif\r
+\r
+// Disable WIN32_LEAN_AND_MEAN.\r
+// This makes windows.h always include winsock2.h\r
+#ifdef WIN32_LEAN_AND_MEAN\r
+#undef WIN32_LEAN_AND_MEAN\r
+#endif\r
+\r
+#if defined(__SYMBIAN32__)\r
+#define NO_SSL // SSL is not supported\r
+#define NO_CGI // CGI is not supported\r
+#define PATH_MAX FILENAME_MAX\r
+#endif // __SYMBIAN32__\r
+\r
+#ifndef _WIN32_WCE // Some ANSI #includes are not available on Windows CE\r
+#include <sys/types.h>\r
+#include <sys/stat.h>\r
+#include <errno.h>\r
+#include <signal.h>\r
+#include <fcntl.h>\r
+#endif // !_WIN32_WCE\r
+\r
+#include <time.h>\r
+#include <stdlib.h>\r
+#include <stdarg.h>\r
+#include <assert.h>\r
+#include <string.h>\r
+#include <ctype.h>\r
+#include <limits.h>\r
+#include <stddef.h>\r
+#include <stdio.h>\r
+\r
+#if defined(_WIN32) && !defined(__SYMBIAN32__) // Windows specific\r
+#define _WIN32_WINNT 0x0400 // To make it link in VS2005\r
+#include <windows.h>\r
+\r
+#ifndef PATH_MAX\r
+#define PATH_MAX MAX_PATH\r
+#endif\r
+\r
+#ifndef _WIN32_WCE\r
+#include <process.h>\r
+#include <direct.h>\r
+#include <io.h>\r
+#else // _WIN32_WCE\r
+#define NO_CGI // WinCE has no pipes\r
+\r
+typedef long off_t;\r
+\r
+#define errno   GetLastError()\r
+#define strerror(x)  _ultoa(x, (char *) _alloca(sizeof(x) *3 ), 10)\r
+#endif // _WIN32_WCE\r
+\r
+#define MAKEUQUAD(lo, hi) ((uint64_t)(((uint32_t)(lo)) | \\r
+      ((uint64_t)((uint32_t)(hi))) << 32))\r
+#define RATE_DIFF 10000000 // 100 nsecs\r
+#define EPOCH_DIFF MAKEUQUAD(0xd53e8000, 0x019db1de)\r
+#define SYS2UNIX_TIME(lo, hi) \\r
+  (time_t) ((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF)\r
+\r
+// Visual Studio 6 does not know __func__ or __FUNCTION__\r
+// The rest of MS compilers use __FUNCTION__, not C99 __func__\r
+// Also use _strtoui64 on modern M$ compilers\r
+#if defined(_MSC_VER) && _MSC_VER < 1300\r
+#define STRX(x) #x\r
+#define STR(x) STRX(x)\r
+#define __func__ __FILE__ ":" STR(__LINE__)\r
+#define strtoull(x, y, z) strtoul(x, y, z)\r
+#define strtoll(x, y, z) strtol(x, y, z)\r
+#else\r
+#define __func__  __FUNCTION__\r
+#define strtoull(x, y, z) _strtoui64(x, y, z)\r
+#define strtoll(x, y, z) _strtoi64(x, y, z)\r
+#endif // _MSC_VER\r
+\r
+#define ERRNO   GetLastError()\r
+#define NO_SOCKLEN_T\r
+#define SSL_LIB   "ssleay32.dll"\r
+#define CRYPTO_LIB  "libeay32.dll"\r
+#define O_NONBLOCK  0\r
+#if !defined(EWOULDBLOCK)\r
+#define EWOULDBLOCK  WSAEWOULDBLOCK\r
+#endif // !EWOULDBLOCK\r
+#define _POSIX_\r
+#define INT64_FMT  "I64d"\r
+\r
+#define WINCDECL __cdecl\r
+#define SHUT_WR 1\r
+#define snprintf _snprintf\r
+#define vsnprintf _vsnprintf\r
+#define mg_sleep(x) Sleep(x)\r
+\r
+#define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)\r
+#define popen(x, y) _popen(x, y)\r
+#define pclose(x) _pclose(x)\r
+#define close(x) _close(x)\r
+#define dlsym(x,y) GetProcAddress((HINSTANCE) (x), (y))\r
+#define RTLD_LAZY  0\r
+#define fseeko(x, y, z) _lseeki64(_fileno(x), (y), (z))\r
+#define fdopen(x, y) _fdopen((x), (y))\r
+#define write(x, y, z) _write((x), (y), (unsigned) z)\r
+#define read(x, y, z) _read((x), (y), (unsigned) z)\r
+#define flockfile(x) EnterCriticalSection(&global_log_file_lock)\r
+#define funlockfile(x) LeaveCriticalSection(&global_log_file_lock)\r
+#define sleep(x) Sleep((x) * 1000)\r
+#define va_copy(x, y) x = y\r
+\r
+#if !defined(fileno)\r
+#define fileno(x) _fileno(x)\r
+#endif // !fileno MINGW #defines fileno\r
+\r
+typedef HANDLE pthread_mutex_t;\r
+typedef struct {HANDLE signal, broadcast;} pthread_cond_t;\r
+typedef DWORD pthread_t;\r
+#define pid_t HANDLE // MINGW typedefs pid_t to int. Using #define here.\r
+\r
+static int pthread_mutex_lock(pthread_mutex_t *);\r
+static int pthread_mutex_unlock(pthread_mutex_t *);\r
+static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);\r
+struct file;\r
+static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);\r
+\r
+#if defined(HAVE_STDINT)\r
+#include <stdint.h>\r
+#else\r
+typedef unsigned int  uint32_t;\r
+typedef unsigned short  uint16_t;\r
+typedef unsigned __int64 uint64_t;\r
+typedef __int64   int64_t;\r
+#define INT64_MAX  9223372036854775807\r
+#endif // HAVE_STDINT\r
+\r
+// POSIX dirent interface\r
+struct dirent {\r
+  char d_name[PATH_MAX];\r
+};\r
+\r
+typedef struct DIR {\r
+  HANDLE   handle;\r
+  WIN32_FIND_DATAW info;\r
+  struct dirent  result;\r
+} DIR;\r
+\r
+#ifndef HAS_POLL\r
+struct pollfd {\r
+  int fd;\r
+  short events;\r
+  short revents;\r
+};\r
+#define POLLIN 1\r
+#endif\r
+\r
+\r
+// Mark required libraries\r
+#pragma comment(lib, "Ws2_32.lib")\r
+\r
+#else    // UNIX  specific\r
+#include <sys/wait.h>\r
+#include <sys/socket.h>\r
+#include <sys/poll.h>\r
+#include <netinet/in.h>\r
+#include <arpa/inet.h>\r
+#include <sys/time.h>\r
+#include <stdint.h>\r
+#include <inttypes.h>\r
+#include <netdb.h>\r
+\r
+#include <pwd.h>\r
+#include <unistd.h>\r
+#include <dirent.h>\r
+#if !defined(NO_SSL_DL) && !defined(NO_SSL)\r
+#include <dlfcn.h>\r
+#endif\r
+#include <pthread.h>\r
+#if defined(__MACH__)\r
+#define SSL_LIB   "libssl.dylib"\r
+#define CRYPTO_LIB  "libcrypto.dylib"\r
+#else\r
+#if !defined(SSL_LIB)\r
+#define SSL_LIB   "libssl.so"\r
+#endif\r
+#if !defined(CRYPTO_LIB)\r
+#define CRYPTO_LIB  "libcrypto.so"\r
+#endif\r
+#endif\r
+#ifndef O_BINARY\r
+#define O_BINARY  0\r
+#endif // O_BINARY\r
+#define closesocket(a) close(a)\r
+#define mg_mkdir(x, y) mkdir(x, y)\r
+#define mg_remove(x) remove(x)\r
+#define mg_rename(x, y) rename(x, y)\r
+#define mg_sleep(x) usleep((x) * 1000)\r
+#define ERRNO errno\r
+#define INVALID_SOCKET (-1)\r
+#define INT64_FMT PRId64\r
+typedef int SOCKET;\r
+#define WINCDECL\r
+\r
+#endif // End of Windows and UNIX specific includes\r
+\r
+#include "mongoose.h"\r
+\r
+#ifdef USE_LUA\r
+#include <lua.h>\r
+#include <lauxlib.h>\r
+#endif\r
+\r
+#define MONGOOSE_VERSION "3.7"\r
+#define PASSWORDS_FILE_NAME ".htpasswd"\r
+#define CGI_ENVIRONMENT_SIZE 4096\r
+#define MAX_CGI_ENVIR_VARS 64\r
+#define MG_BUF_LEN 8192\r
+#define MAX_REQUEST_SIZE 16384\r
+#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))\r
+\r
+#ifdef _WIN32\r
+static CRITICAL_SECTION global_log_file_lock;\r
+static pthread_t pthread_self(void) {\r
+  return GetCurrentThreadId();\r
+}\r
+#endif // _WIN32\r
+\r
+#ifdef DEBUG_TRACE\r
+#undef DEBUG_TRACE\r
+#define DEBUG_TRACE(x)\r
+#else\r
+#if defined(DEBUG)\r
+#define DEBUG_TRACE(x) do { \\r
+  flockfile(stdout); \\r
+  printf("*** %lu.%p.%s.%d: ", \\r
+         (unsigned long) time(NULL), (void *) pthread_self(), \\r
+         __func__, __LINE__); \\r
+  printf x; \\r
+  putchar('\n'); \\r
+  fflush(stdout); \\r
+  funlockfile(stdout); \\r
+} while (0)\r
+#else\r
+#define DEBUG_TRACE(x)\r
+#endif // DEBUG\r
+#endif // DEBUG_TRACE\r
+\r
+// Darwin prior to 7.0 and Win32 do not have socklen_t\r
+#ifdef NO_SOCKLEN_T\r
+typedef int socklen_t;\r
+#endif // NO_SOCKLEN_T\r
+#define _DARWIN_UNLIMITED_SELECT\r
+\r
+#if !defined(MSG_NOSIGNAL)\r
+#define MSG_NOSIGNAL 0\r
+#endif\r
+\r
+#if !defined(SOMAXCONN)\r
+#define SOMAXCONN 100\r
+#endif\r
+\r
+#if !defined(PATH_MAX)\r
+#define PATH_MAX 4096\r
+#endif\r
+\r
+static const char *http_500_error = "Internal Server Error";\r
+\r
+#if defined(NO_SSL_DL)\r
+#include <openssl/ssl.h>\r
+#else\r
+// SSL loaded dynamically from DLL.\r
+// I put the prototypes here to be independent from OpenSSL source installation.\r
+typedef struct ssl_st SSL;\r
+typedef struct ssl_method_st SSL_METHOD;\r
+typedef struct ssl_ctx_st SSL_CTX;\r
+\r
+struct ssl_func {\r
+  const char *name;   // SSL function name\r
+  void  (*ptr)(void); // Function pointer\r
+};\r
+\r
+#define SSL_free (* (void (*)(SSL *)) ssl_sw[0].ptr)\r
+#define SSL_accept (* (int (*)(SSL *)) ssl_sw[1].ptr)\r
+#define SSL_connect (* (int (*)(SSL *)) ssl_sw[2].ptr)\r
+#define SSL_read (* (int (*)(SSL *, void *, int)) ssl_sw[3].ptr)\r
+#define SSL_write (* (int (*)(SSL *, const void *,int)) ssl_sw[4].ptr)\r
+#define SSL_get_error (* (int (*)(SSL *, int)) ssl_sw[5].ptr)\r
+#define SSL_set_fd (* (int (*)(SSL *, SOCKET)) ssl_sw[6].ptr)\r
+#define SSL_new (* (SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)\r
+#define SSL_CTX_new (* (SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)\r
+#define SSLv23_server_method (* (SSL_METHOD * (*)(void)) ssl_sw[9].ptr)\r
+#define SSL_library_init (* (int (*)(void)) ssl_sw[10].ptr)\r
+#define SSL_CTX_use_PrivateKey_file (* (int (*)(SSL_CTX *, \\r
+        const char *, int)) ssl_sw[11].ptr)\r
+#define SSL_CTX_use_certificate_file (* (int (*)(SSL_CTX *, \\r
+        const char *, int)) ssl_sw[12].ptr)\r
+#define SSL_CTX_set_default_passwd_cb \\r
+  (* (void (*)(SSL_CTX *, mg_callback_t)) ssl_sw[13].ptr)\r
+#define SSL_CTX_free (* (void (*)(SSL_CTX *)) ssl_sw[14].ptr)\r
+#define SSL_load_error_strings (* (void (*)(void)) ssl_sw[15].ptr)\r
+#define SSL_CTX_use_certificate_chain_file \\r
+  (* (int (*)(SSL_CTX *, const char *)) ssl_sw[16].ptr)\r
+#define SSLv23_client_method (* (SSL_METHOD * (*)(void)) ssl_sw[17].ptr)\r
+#define SSL_pending (* (int (*)(SSL *)) ssl_sw[18].ptr)\r
+#define SSL_CTX_set_verify (* (void (*)(SSL_CTX *, int, int)) ssl_sw[19].ptr)\r
+\r
+#define CRYPTO_num_locks (* (int (*)(void)) crypto_sw[0].ptr)\r
+#define CRYPTO_set_locking_callback \\r
+  (* (void (*)(void (*)(int, int, const char *, int))) crypto_sw[1].ptr)\r
+#define CRYPTO_set_id_callback \\r
+  (* (void (*)(unsigned long (*)(void))) crypto_sw[2].ptr)\r
+#define ERR_get_error (* (unsigned long (*)(void)) crypto_sw[3].ptr)\r
+#define ERR_error_string (* (char * (*)(unsigned long,char *)) crypto_sw[4].ptr)\r
+\r
+// set_ssl_option() function updates this array.\r
+// It loads SSL library dynamically and changes NULLs to the actual addresses\r
+// of respective functions. The macros above (like SSL_connect()) are really\r
+// just calling these functions indirectly via the pointer.\r
+static struct ssl_func ssl_sw[] = {\r
+  {"SSL_free",   NULL},\r
+  {"SSL_accept",   NULL},\r
+  {"SSL_connect",   NULL},\r
+  {"SSL_read",   NULL},\r
+  {"SSL_write",   NULL},\r
+  {"SSL_get_error",  NULL},\r
+  {"SSL_set_fd",   NULL},\r
+  {"SSL_new",   NULL},\r
+  {"SSL_CTX_new",   NULL},\r
+  {"SSLv23_server_method", NULL},\r
+  {"SSL_library_init",  NULL},\r
+  {"SSL_CTX_use_PrivateKey_file", NULL},\r
+  {"SSL_CTX_use_certificate_file",NULL},\r
+  {"SSL_CTX_set_default_passwd_cb",NULL},\r
+  {"SSL_CTX_free",  NULL},\r
+  {"SSL_load_error_strings", NULL},\r
+  {"SSL_CTX_use_certificate_chain_file", NULL},\r
+  {"SSLv23_client_method", NULL},\r
+  {"SSL_pending", NULL},\r
+  {"SSL_CTX_set_verify", NULL},\r
+  {NULL,    NULL}\r
+};\r
+\r
+// Similar array as ssl_sw. These functions could be located in different lib.\r
+#if !defined(NO_SSL)\r
+static struct ssl_func crypto_sw[] = {\r
+  {"CRYPTO_num_locks",  NULL},\r
+  {"CRYPTO_set_locking_callback", NULL},\r
+  {"CRYPTO_set_id_callback", NULL},\r
+  {"ERR_get_error",  NULL},\r
+  {"ERR_error_string", NULL},\r
+  {NULL,    NULL}\r
+};\r
+#endif // NO_SSL\r
+#endif // NO_SSL_DL\r
+\r
+static const char *month_names[] = {\r
+  "Jan", "Feb", "Mar", "Apr", "May", "Jun",\r
+  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"\r
+};\r
+\r
+// Unified socket address. For IPv6 support, add IPv6 address structure\r
+// in the union u.\r
+union usa {\r
+  struct sockaddr sa;\r
+  struct sockaddr_in sin;\r
+#if defined(USE_IPV6)\r
+  struct sockaddr_in6 sin6;\r
+#endif\r
+};\r
+\r
+// Describes a string (chunk of memory).\r
+struct vec {\r
+  const char *ptr;\r
+  size_t len;\r
+};\r
+\r
+struct file {\r
+  int is_directory;\r
+  time_t modification_time;\r
+  int64_t size;\r
+  FILE *fp;\r
+  const char *membuf;   // Non-NULL if file data is in memory\r
+};\r
+#define STRUCT_FILE_INITIALIZER {0, 0, 0, NULL, NULL}\r
+\r
+// Describes listening socket, or socket which was accept()-ed by the master\r
+// thread and queued for future handling by the worker thread.\r
+struct socket {\r
+  SOCKET sock;          // Listening socket\r
+  union usa lsa;        // Local socket address\r
+  union usa rsa;        // Remote socket address\r
+  unsigned is_ssl:1;    // Is port SSL-ed\r
+  unsigned ssl_redir:1; // Is port supposed to redirect everything to SSL port\r
+};\r
+\r
+// NOTE(lsm): this enum shoulds be in sync with the config_options below.\r
+enum {\r
+  CGI_EXTENSIONS, CGI_ENVIRONMENT, PUT_DELETE_PASSWORDS_FILE, CGI_INTERPRETER,\r
+  PROTECT_URI, AUTHENTICATION_DOMAIN, SSI_EXTENSIONS, THROTTLE,\r
+  ACCESS_LOG_FILE, ENABLE_DIRECTORY_LISTING, ERROR_LOG_FILE,\r
+  GLOBAL_PASSWORDS_FILE, INDEX_FILES, ENABLE_KEEP_ALIVE, ACCESS_CONTROL_LIST,\r
+  EXTRA_MIME_TYPES, LISTENING_PORTS, DOCUMENT_ROOT, SSL_CERTIFICATE,\r
+  NUM_THREADS, RUN_AS_USER, REWRITE, HIDE_FILES, REQUEST_TIMEOUT,\r
+  NUM_OPTIONS\r
+};\r
+\r
+static const char *config_options[] = {\r
+  "C", "cgi_pattern", "**.cgi$|**.pl$|**.php$",\r
+  "E", "cgi_environment", NULL,\r
+  "G", "put_delete_auth_file", NULL,\r
+  "I", "cgi_interpreter", NULL,\r
+  "P", "protect_uri", NULL,\r
+  "R", "authentication_domain", "mydomain.com",\r
+  "S", "ssi_pattern", "**.shtml$|**.shtm$",\r
+  "T", "throttle", NULL,\r
+  "a", "access_log_file", NULL,\r
+  "d", "enable_directory_listing", "yes",\r
+  "e", "error_log_file", NULL,\r
+  "g", "global_auth_file", NULL,\r
+  "i", "index_files", "index.html,index.htm,index.cgi,index.shtml,index.php",\r
+  "k", "enable_keep_alive", "no",\r
+  "l", "access_control_list", NULL,\r
+  "m", "extra_mime_types", NULL,\r
+  "p", "listening_ports", "8080",\r
+  "r", "document_root",  ".",\r
+  "s", "ssl_certificate", NULL,\r
+  "t", "num_threads", "20",\r
+  "u", "run_as_user", NULL,\r
+  "w", "url_rewrite_patterns", NULL,\r
+  "x", "hide_files_patterns", NULL,\r
+  "z", "request_timeout_ms", "30000",\r
+  NULL\r
+};\r
+#define ENTRIES_PER_CONFIG_OPTION 3\r
+\r
+struct mg_context {\r
+  volatile int stop_flag;         // Should we stop event loop\r
+  SSL_CTX *ssl_ctx;               // SSL context\r
+  char *config[NUM_OPTIONS];      // Mongoose configuration parameters\r
+  struct mg_callbacks callbacks;  // User-defined callback function\r
+  void *user_data;                // User-defined data\r
+\r
+  struct socket *listening_sockets;\r
+  int num_listening_sockets;\r
+\r
+  volatile int num_threads;  // Number of threads\r
+  pthread_mutex_t mutex;     // Protects (max|num)_threads\r
+  pthread_cond_t  cond;      // Condvar for tracking workers terminations\r
+\r
+  struct socket queue[20];   // Accepted sockets\r
+  volatile int sq_head;      // Head of the socket queue\r
+  volatile int sq_tail;      // Tail of the socket queue\r
+  pthread_cond_t sq_full;    // Signaled when socket is produced\r
+  pthread_cond_t sq_empty;   // Signaled when socket is consumed\r
+};\r
+\r
+struct mg_connection {\r
+  struct mg_request_info request_info;\r
+  struct mg_context *ctx;\r
+  SSL *ssl;                   // SSL descriptor\r
+  SSL_CTX *client_ssl_ctx;    // SSL context for client connections\r
+  struct socket client;       // Connected client\r
+  time_t birth_time;          // Time when request was received\r
+  int64_t num_bytes_sent;     // Total bytes sent to client\r
+  int64_t content_len;        // Content-Length header value\r
+  int64_t consumed_content;   // How many bytes of content have been read\r
+  char *buf;                  // Buffer for received data\r
+  char *path_info;            // PATH_INFO part of the URL\r
+  int must_close;             // 1 if connection must be closed\r
+  int buf_size;               // Buffer size\r
+  int request_len;            // Size of the request + headers in a buffer\r
+  int data_len;               // Total size of data in a buffer\r
+  int status_code;            // HTTP reply status code, e.g. 200\r
+  int throttle;               // Throttling, bytes/sec. <= 0 means no throttle\r
+  time_t last_throttle_time;  // Last time throttled data was sent\r
+  int64_t last_throttle_bytes;// Bytes sent this second\r
+};\r
+\r
+const char **mg_get_valid_option_names(void) {\r
+  return config_options;\r
+}\r
+\r
+static int is_file_in_memory(struct mg_connection *conn, const char *path,\r
+                             struct file *filep) {\r
+  size_t size = 0;\r
+  if ((filep->membuf = conn->ctx->callbacks.open_file == NULL ? NULL :\r
+       conn->ctx->callbacks.open_file(conn, path, &size)) != NULL) {\r
+    // NOTE: override filep->size only on success. Otherwise, it might break\r
+    // constructs like if (!mg_stat() || !mg_fopen()) ...\r
+    filep->size = size;\r
+  }\r
+  return filep->membuf != NULL;\r
+}\r
+\r
+static int is_file_opened(const struct file *filep) {\r
+  return filep->membuf != NULL || filep->fp != NULL;\r
+}\r
+\r
+static int mg_fopen(struct mg_connection *conn, const char *path,\r
+                    const char *mode, struct file *filep) {\r
+  if (!is_file_in_memory(conn, path, filep)) {\r
+#ifdef _WIN32\r
+    wchar_t wbuf[PATH_MAX], wmode[20];\r
+    to_unicode(path, wbuf, ARRAY_SIZE(wbuf));\r
+    MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));\r
+    filep->fp = _wfopen(wbuf, wmode);\r
+#else\r
+    filep->fp = fopen(path, mode);\r
+#endif\r
+  }\r
+\r
+  return is_file_opened(filep);\r
+}\r
+\r
+static void mg_fclose(struct file *filep) {\r
+  if (filep != NULL && filep->fp != NULL) {\r
+    fclose(filep->fp);\r
+  }\r
+}\r
+\r
+static int get_option_index(const char *name) {\r
+  int i;\r
+\r
+  for (i = 0; config_options[i] != NULL; i += ENTRIES_PER_CONFIG_OPTION) {\r
+    if (strcmp(config_options[i], name) == 0 ||\r
+        strcmp(config_options[i + 1], name) == 0) {\r
+      return i / ENTRIES_PER_CONFIG_OPTION;\r
+    }\r
+  }\r
+  return -1;\r
+}\r
+\r
+const char *mg_get_option(const struct mg_context *ctx, const char *name) {\r
+  int i;\r
+  if ((i = get_option_index(name)) == -1) {\r
+    return NULL;\r
+  } else if (ctx->config[i] == NULL) {\r
+    return "";\r
+  } else {\r
+    return ctx->config[i];\r
+  }\r
+}\r
+\r
+static void sockaddr_to_string(char *buf, size_t len,\r
+                                     const union usa *usa) {\r
+  buf[0] = '\0';\r
+#if defined(USE_IPV6)\r
+  inet_ntop(usa->sa.sa_family, usa->sa.sa_family == AF_INET ?\r
+            (void *) &usa->sin.sin_addr :\r
+            (void *) &usa->sin6.sin6_addr, buf, len);\r
+#elif defined(_WIN32)\r
+  // Only Windoze Vista (and newer) have inet_ntop()\r
+  strncpy(buf, inet_ntoa(usa->sin.sin_addr), len);\r
+#else\r
+  inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, len);\r
+#endif\r
+}\r
+\r
+static void cry(struct mg_connection *conn,\r
+                PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3);\r
+\r
+// Print error message to the opened error log stream.\r
+static void cry(struct mg_connection *conn, const char *fmt, ...) {\r
+  char buf[MG_BUF_LEN], src_addr[20];\r
+  va_list ap;\r
+  FILE *fp;\r
+  time_t timestamp;\r
+\r
+  va_start(ap, fmt);\r
+  (void) vsnprintf(buf, sizeof(buf), fmt, ap);\r
+  va_end(ap);\r
+\r
+  // Do not lock when getting the callback value, here and below.\r
+  // I suppose this is fine, since function cannot disappear in the\r
+  // same way string option can.\r
+  if (conn->ctx->callbacks.log_message == NULL ||\r
+      conn->ctx->callbacks.log_message(conn, buf) == 0) {\r
+    fp = conn->ctx == NULL || conn->ctx->config[ERROR_LOG_FILE] == NULL ? NULL :\r
+      fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");\r
+\r
+    if (fp != NULL) {\r
+      flockfile(fp);\r
+      timestamp = time(NULL);\r
+\r
+      sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);\r
+      fprintf(fp, "[%010lu] [error] [client %s] ", (unsigned long) timestamp,\r
+              src_addr);\r
+\r
+      if (conn->request_info.request_method != NULL) {\r
+        fprintf(fp, "%s %s: ", conn->request_info.request_method,\r
+                conn->request_info.uri);\r
+      }\r
+\r
+      fprintf(fp, "%s", buf);\r
+      fputc('\n', fp);\r
+      funlockfile(fp);\r
+      fclose(fp);\r
+    }\r
+  }\r
+}\r
+\r
+// Return fake connection structure. Used for logging, if connection\r
+// is not applicable at the moment of logging.\r
+static struct mg_connection *fc(struct mg_context *ctx) {\r
+  static struct mg_connection fake_connection;\r
+  fake_connection.ctx = ctx;\r
+  return &fake_connection;\r
+}\r
+\r
+const char *mg_version(void) {\r
+  return MONGOOSE_VERSION;\r
+}\r
+\r
+struct mg_request_info *mg_get_request_info(struct mg_connection *conn) {\r
+  return &conn->request_info;\r
+}\r
+\r
+static void mg_strlcpy(register char *dst, register const char *src, size_t n) {\r
+  for (; *src != '\0' && n > 1; n--) {\r
+    *dst++ = *src++;\r
+  }\r
+  *dst = '\0';\r
+}\r
+\r
+static int lowercase(const char *s) {\r
+  return tolower(* (const unsigned char *) s);\r
+}\r
+\r
+static int mg_strncasecmp(const char *s1, const char *s2, size_t len) {\r
+  int diff = 0;\r
+\r
+  if (len > 0)\r
+    do {\r
+      diff = lowercase(s1++) - lowercase(s2++);\r
+    } while (diff == 0 && s1[-1] != '\0' && --len > 0);\r
+\r
+  return diff;\r
+}\r
+\r
+static int mg_strcasecmp(const char *s1, const char *s2) {\r
+  int diff;\r
+\r
+  do {\r
+    diff = lowercase(s1++) - lowercase(s2++);\r
+  } while (diff == 0 && s1[-1] != '\0');\r
+\r
+  return diff;\r
+}\r
+\r
+static char * mg_strndup(const char *ptr, size_t len) {\r
+  char *p;\r
+\r
+  if ((p = (char *) malloc(len + 1)) != NULL) {\r
+    mg_strlcpy(p, ptr, len + 1);\r
+  }\r
+\r
+  return p;\r
+}\r
+\r
+static char * mg_strdup(const char *str) {\r
+  return mg_strndup(str, strlen(str));\r
+}\r
+\r
+// Like snprintf(), but never returns negative value, or a value\r
+// that is larger than a supplied buffer.\r
+// Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability\r
+// in his audit report.\r
+static int mg_vsnprintf(struct mg_connection *conn, char *buf, size_t buflen,\r
+                        const char *fmt, va_list ap) {\r
+  int n;\r
+\r
+  if (buflen == 0)\r
+    return 0;\r
+\r
+  n = vsnprintf(buf, buflen, fmt, ap);\r
+\r
+  if (n < 0) {\r
+    cry(conn, "vsnprintf error");\r
+    n = 0;\r
+  } else if (n >= (int) buflen) {\r
+    cry(conn, "truncating vsnprintf buffer: [%.*s]",\r
+        n > 200 ? 200 : n, buf);\r
+    n = (int) buflen - 1;\r
+  }\r
+  buf[n] = '\0';\r
+\r
+  return n;\r
+}\r
+\r
+static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,\r
+                       PRINTF_FORMAT_STRING(const char *fmt), ...)\r
+  PRINTF_ARGS(4, 5);\r
+\r
+static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,\r
+                       const char *fmt, ...) {\r
+  va_list ap;\r
+  int n;\r
+\r
+  va_start(ap, fmt);\r
+  n = mg_vsnprintf(conn, buf, buflen, fmt, ap);\r
+  va_end(ap);\r
+\r
+  return n;\r
+}\r
+\r
+// Skip the characters until one of the delimiters characters found.\r
+// 0-terminate resulting word. Skip the delimiter and following whitespaces.\r
+// Advance pointer to buffer to the next word. Return found 0-terminated word.\r
+// Delimiters can be quoted with quotechar.\r
+static char *skip_quoted(char **buf, const char *delimiters,\r
+                         const char *whitespace, char quotechar) {\r
+  char *p, *begin_word, *end_word, *end_whitespace;\r
+\r
+  begin_word = *buf;\r
+  end_word = begin_word + strcspn(begin_word, delimiters);\r
+\r
+  // Check for quotechar\r
+  if (end_word > begin_word) {\r
+    p = end_word - 1;\r
+    while (*p == quotechar) {\r
+      // If there is anything beyond end_word, copy it\r
+      if (*end_word == '\0') {\r
+        *p = '\0';\r
+        break;\r
+      } else {\r
+        size_t end_off = strcspn(end_word + 1, delimiters);\r
+        memmove (p, end_word, end_off + 1);\r
+        p += end_off; // p must correspond to end_word - 1\r
+        end_word += end_off + 1;\r
+      }\r
+    }\r
+    for (p++; p < end_word; p++) {\r
+      *p = '\0';\r
+    }\r
+  }\r
+\r
+  if (*end_word == '\0') {\r
+    *buf = end_word;\r
+  } else {\r
+    end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);\r
+\r
+    for (p = end_word; p < end_whitespace; p++) {\r
+      *p = '\0';\r
+    }\r
+\r
+    *buf = end_whitespace;\r
+  }\r
+\r
+  return begin_word;\r
+}\r
+\r
+// Simplified version of skip_quoted without quote char\r
+// and whitespace == delimiters\r
+static char *skip(char **buf, const char *delimiters) {\r
+  return skip_quoted(buf, delimiters, delimiters, 0);\r
+}\r
+\r
+\r
+// Return HTTP header value, or NULL if not found.\r
+static const char *get_header(const struct mg_request_info *ri,\r
+                              const char *name) {\r
+  int i;\r
+\r
+  for (i = 0; i < ri->num_headers; i++)\r
+    if (!mg_strcasecmp(name, ri->http_headers[i].name))\r
+      return ri->http_headers[i].value;\r
+\r
+  return NULL;\r
+}\r
+\r
+const char *mg_get_header(const struct mg_connection *conn, const char *name) {\r
+  return get_header(&conn->request_info, name);\r
+}\r
+\r
+// A helper function for traversing a comma separated list of values.\r
+// It returns a list pointer shifted to the next value, or NULL if the end\r
+// of the list found.\r
+// Value is stored in val vector. If value has form "x=y", then eq_val\r
+// vector is initialized to point to the "y" part, and val vector length\r
+// is adjusted to point only to "x".\r
+static const char *next_option(const char *list, struct vec *val,\r
+                               struct vec *eq_val) {\r
+  if (list == NULL || *list == '\0') {\r
+    // End of the list\r
+    list = NULL;\r
+  } else {\r
+    val->ptr = list;\r
+    if ((list = strchr(val->ptr, ',')) != NULL) {\r
+      // Comma found. Store length and shift the list ptr\r
+      val->len = list - val->ptr;\r
+      list++;\r
+    } else {\r
+      // This value is the last one\r
+      list = val->ptr + strlen(val->ptr);\r
+      val->len = list - val->ptr;\r
+    }\r
+\r
+    if (eq_val != NULL) {\r
+      // Value has form "x=y", adjust pointers and lengths\r
+      // so that val points to "x", and eq_val points to "y".\r
+      eq_val->len = 0;\r
+      eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);\r
+      if (eq_val->ptr != NULL) {\r
+        eq_val->ptr++;  // Skip over '=' character\r
+        eq_val->len = val->ptr + val->len - eq_val->ptr;\r
+        val->len = (eq_val->ptr - val->ptr) - 1;\r
+      }\r
+    }\r
+  }\r
+\r
+  return list;\r
+}\r
+\r
+static int match_prefix(const char *pattern, int pattern_len, const char *str) {\r
+  const char *or_str;\r
+  int i, j, len, res;\r
+\r
+  if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {\r
+    res = match_prefix(pattern, or_str - pattern, str);\r
+    return res > 0 ? res :\r
+        match_prefix(or_str + 1, (pattern + pattern_len) - (or_str + 1), str);\r
+  }\r
+\r
+  i = j = 0;\r
+  res = -1;\r
+  for (; i < pattern_len; i++, j++) {\r
+    if (pattern[i] == '?' && str[j] != '\0') {\r
+      continue;\r
+    } else if (pattern[i] == '$') {\r
+      return str[j] == '\0' ? j : -1;\r
+    } else if (pattern[i] == '*') {\r
+      i++;\r
+      if (pattern[i] == '*') {\r
+        i++;\r
+        len = (int) strlen(str + j);\r
+      } else {\r
+        len = (int) strcspn(str + j, "/");\r
+      }\r
+      if (i == pattern_len) {\r
+        return j + len;\r
+      }\r
+      do {\r
+        res = match_prefix(pattern + i, pattern_len - i, str + j + len);\r
+      } while (res == -1 && len-- > 0);\r
+      return res == -1 ? -1 : j + res + len;\r
+    } else if (pattern[i] != str[j]) {\r
+      return -1;\r
+    }\r
+  }\r
+  return j;\r
+}\r
+\r
+// HTTP 1.1 assumes keep alive if "Connection:" header is not set\r
+// This function must tolerate situations when connection info is not\r
+// set up, for example if request parsing failed.\r
+static int should_keep_alive(const struct mg_connection *conn) {\r
+  const char *http_version = conn->request_info.http_version;\r
+  const char *header = mg_get_header(conn, "Connection");\r
+  if (conn->must_close ||\r
+      conn->status_code == 401 ||\r
+      mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0 ||\r
+      (header != NULL && mg_strcasecmp(header, "keep-alive") != 0) ||\r
+      (header == NULL && http_version && strcmp(http_version, "1.1"))) {\r
+    return 0;\r
+  }\r
+  return 1;\r
+}\r
+\r
+static const char *suggest_connection_header(const struct mg_connection *conn) {\r
+  return should_keep_alive(conn) ? "keep-alive" : "close";\r
+}\r
+\r
+static void send_http_error(struct mg_connection *, int, const char *,\r
+                            PRINTF_FORMAT_STRING(const char *fmt), ...)\r
+  PRINTF_ARGS(4, 5);\r
+\r
+\r
+static void send_http_error(struct mg_connection *conn, int status,\r
+                            const char *reason, const char *fmt, ...) {\r
+  char buf[MG_BUF_LEN];\r
+  va_list ap;\r
+  int len = 0;\r
+\r
+  conn->status_code = status;\r
+  buf[0] = '\0';\r
+\r
+  // Errors 1xx, 204 and 304 MUST NOT send a body\r
+  if (status > 199 && status != 204 && status != 304) {\r
+    len = mg_snprintf(conn, buf, sizeof(buf), "Error %d: %s", status, reason);\r
+    buf[len++] = '\n';\r
+\r
+    va_start(ap, fmt);\r
+    len += mg_vsnprintf(conn, buf + len, sizeof(buf) - len, fmt, ap);\r
+    va_end(ap);\r
+  }\r
+  DEBUG_TRACE(("[%s]", buf));\r
+\r
+  mg_printf(conn, "HTTP/1.1 %d %s\r\n"\r
+            "Content-Length: %d\r\n"\r
+            "Connection: %s\r\n\r\n", status, reason, len,\r
+            suggest_connection_header(conn));\r
+  conn->num_bytes_sent += mg_printf(conn, "%s", buf);\r
+}\r
+\r
+#if defined(_WIN32) && !defined(__SYMBIAN32__)\r
+static int pthread_mutex_init(pthread_mutex_t *mutex, void *unused) {\r
+  unused = NULL;\r
+  *mutex = CreateMutex(NULL, FALSE, NULL);\r
+  return *mutex == NULL ? -1 : 0;\r
+}\r
+\r
+static int pthread_mutex_destroy(pthread_mutex_t *mutex) {\r
+  return CloseHandle(*mutex) == 0 ? -1 : 0;\r
+}\r
+\r
+static int pthread_mutex_lock(pthread_mutex_t *mutex) {\r
+  return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;\r
+}\r
+\r
+static int pthread_mutex_unlock(pthread_mutex_t *mutex) {\r
+  return ReleaseMutex(*mutex) == 0 ? -1 : 0;\r
+}\r
+\r
+static int pthread_cond_init(pthread_cond_t *cv, const void *unused) {\r
+  unused = NULL;\r
+  cv->signal = CreateEvent(NULL, FALSE, FALSE, NULL);\r
+  cv->broadcast = CreateEvent(NULL, TRUE, FALSE, NULL);\r
+  return cv->signal != NULL && cv->broadcast != NULL ? 0 : -1;\r
+}\r
+\r
+static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex) {\r
+  HANDLE handles[] = {cv->signal, cv->broadcast};\r
+  ReleaseMutex(*mutex);\r
+  WaitForMultipleObjects(2, handles, FALSE, INFINITE);\r
+  return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;\r
+}\r
+\r
+static int pthread_cond_signal(pthread_cond_t *cv) {\r
+  return SetEvent(cv->signal) == 0 ? -1 : 0;\r
+}\r
+\r
+static int pthread_cond_broadcast(pthread_cond_t *cv) {\r
+  // Implementation with PulseEvent() has race condition, see\r
+  // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html\r
+  return PulseEvent(cv->broadcast) == 0 ? -1 : 0;\r
+}\r
+\r
+static int pthread_cond_destroy(pthread_cond_t *cv) {\r
+  return CloseHandle(cv->signal) && CloseHandle(cv->broadcast) ? 0 : -1;\r
+}\r
+\r
+// For Windows, change all slashes to backslashes in path names.\r
+static void change_slashes_to_backslashes(char *path) {\r
+  int i;\r
+\r
+  for (i = 0; path[i] != '\0'; i++) {\r
+    if (path[i] == '/')\r
+      path[i] = '\\';\r
+    // i > 0 check is to preserve UNC paths, like \\server\file.txt\r
+    if (path[i] == '\\' && i > 0)\r
+      while (path[i + 1] == '\\' || path[i + 1] == '/')\r
+        (void) memmove(path + i + 1,\r
+            path + i + 2, strlen(path + i + 1));\r
+  }\r
+}\r
+\r
+// Encode 'path' which is assumed UTF-8 string, into UNICODE string.\r
+// wbuf and wbuf_len is a target buffer and its length.\r
+static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len) {\r
+  char buf[PATH_MAX], buf2[PATH_MAX], *p;\r
+\r
+  mg_strlcpy(buf, path, sizeof(buf));\r
+  change_slashes_to_backslashes(buf);\r
+\r
+  // Point p to the end of the file name\r
+  p = buf + strlen(buf) - 1;\r
+\r
+  // Convert to Unicode and back. If doubly-converted string does not\r
+  // match the original, something is fishy, reject.\r
+  memset(wbuf, 0, wbuf_len * sizeof(wchar_t));\r
+  MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);\r
+  WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),\r
+                      NULL, NULL);\r
+  if (strcmp(buf, buf2) != 0) {\r
+    wbuf[0] = L'\0';\r
+  }\r
+}\r
+\r
+#if defined(_WIN32_WCE)\r
+static time_t time(time_t *ptime) {\r
+  time_t t;\r
+  SYSTEMTIME st;\r
+  FILETIME ft;\r
+\r
+  GetSystemTime(&st);\r
+  SystemTimeToFileTime(&st, &ft);\r
+  t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);\r
+\r
+  if (ptime != NULL) {\r
+    *ptime = t;\r
+  }\r
+\r
+  return t;\r
+}\r
+\r
+static struct tm *localtime(const time_t *ptime, struct tm *ptm) {\r
+  int64_t t = ((int64_t) *ptime) * RATE_DIFF + EPOCH_DIFF;\r
+  FILETIME ft, lft;\r
+  SYSTEMTIME st;\r
+  TIME_ZONE_INFORMATION tzinfo;\r
+\r
+  if (ptm == NULL) {\r
+    return NULL;\r
+  }\r
+\r
+  * (int64_t *) &ft = t;\r
+  FileTimeToLocalFileTime(&ft, &lft);\r
+  FileTimeToSystemTime(&lft, &st);\r
+  ptm->tm_year = st.wYear - 1900;\r
+  ptm->tm_mon = st.wMonth - 1;\r
+  ptm->tm_wday = st.wDayOfWeek;\r
+  ptm->tm_mday = st.wDay;\r
+  ptm->tm_hour = st.wHour;\r
+  ptm->tm_min = st.wMinute;\r
+  ptm->tm_sec = st.wSecond;\r
+  ptm->tm_yday = 0; // hope nobody uses this\r
+  ptm->tm_isdst =\r
+    GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;\r
+\r
+  return ptm;\r
+}\r
+\r
+static struct tm *gmtime(const time_t *ptime, struct tm *ptm) {\r
+  // FIXME(lsm): fix this.\r
+  return localtime(ptime, ptm);\r
+}\r
+\r
+static size_t strftime(char *dst, size_t dst_size, const char *fmt,\r
+                       const struct tm *tm) {\r
+  (void) snprintf(dst, dst_size, "implement strftime() for WinCE");\r
+  return 0;\r
+}\r
+#endif\r
+\r
+static int mg_rename(const char* oldname, const char* newname) {\r
+  wchar_t woldbuf[PATH_MAX];\r
+  wchar_t wnewbuf[PATH_MAX];\r
+\r
+  to_unicode(oldname, woldbuf, ARRAY_SIZE(woldbuf));\r
+  to_unicode(newname, wnewbuf, ARRAY_SIZE(wnewbuf));\r
+\r
+  return MoveFileW(woldbuf, wnewbuf) ? 0 : -1;\r
+}\r
+\r
+// Windows happily opens files with some garbage at the end of file name.\r
+// For example, fopen("a.cgi    ", "r") on Windows successfully opens\r
+// "a.cgi", despite one would expect an error back.\r
+// This function returns non-0 if path ends with some garbage.\r
+static int path_cannot_disclose_cgi(const char *path) {\r
+  static const char *allowed_last_characters = "_-";\r
+  int last = path[strlen(path) - 1];\r
+  return isalnum(last) || strchr(allowed_last_characters, last) != NULL;\r
+}\r
+\r
+static int mg_stat(struct mg_connection *conn, const char *path,\r
+                   struct file *filep) {\r
+  wchar_t wbuf[PATH_MAX];\r
+  WIN32_FILE_ATTRIBUTE_DATA info;\r
+\r
+  if (!is_file_in_memory(conn, path, filep)) {\r
+    to_unicode(path, wbuf, ARRAY_SIZE(wbuf));\r
+    if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {\r
+      filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);\r
+      filep->modification_time = SYS2UNIX_TIME(\r
+          info.ftLastWriteTime.dwLowDateTime,\r
+          info.ftLastWriteTime.dwHighDateTime);\r
+      filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;\r
+      // If file name is fishy, reset the file structure and return error.\r
+      // Note it is important to reset, not just return the error, cause\r
+      // functions like is_file_opened() check the struct.\r
+      if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {\r
+        memset(filep, 0, sizeof(*filep));\r
+      }\r
+    }\r
+  }\r
+\r
+  return filep->membuf != NULL || filep->modification_time != 0;\r
+}\r
+\r
+static int mg_remove(const char *path) {\r
+  wchar_t wbuf[PATH_MAX];\r
+  to_unicode(path, wbuf, ARRAY_SIZE(wbuf));\r
+  return DeleteFileW(wbuf) ? 0 : -1;\r
+}\r
+\r
+static int mg_mkdir(const char *path, int mode) {\r
+  char buf[PATH_MAX];\r
+  wchar_t wbuf[PATH_MAX];\r
+\r
+  mode = 0; // Unused\r
+  mg_strlcpy(buf, path, sizeof(buf));\r
+  change_slashes_to_backslashes(buf);\r
+\r
+  (void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));\r
+\r
+  return CreateDirectoryW(wbuf, NULL) ? 0 : -1;\r
+}\r
+\r
+// Implementation of POSIX opendir/closedir/readdir for Windows.\r
+static DIR * opendir(const char *name) {\r
+  DIR *dir = NULL;\r
+  wchar_t wpath[PATH_MAX];\r
+  DWORD attrs;\r
+\r
+  if (name == NULL) {\r
+    SetLastError(ERROR_BAD_ARGUMENTS);\r
+  } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) {\r
+    SetLastError(ERROR_NOT_ENOUGH_MEMORY);\r
+  } else {\r
+    to_unicode(name, wpath, ARRAY_SIZE(wpath));\r
+    attrs = GetFileAttributesW(wpath);\r
+    if (attrs != 0xFFFFFFFF &&\r
+        ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {\r
+      (void) wcscat(wpath, L"\\*");\r
+      dir->handle = FindFirstFileW(wpath, &dir->info);\r
+      dir->result.d_name[0] = '\0';\r
+    } else {\r
+      free(dir);\r
+      dir = NULL;\r
+    }\r
+  }\r
+\r
+  return dir;\r
+}\r
+\r
+static int closedir(DIR *dir) {\r
+  int result = 0;\r
+\r
+  if (dir != NULL) {\r
+    if (dir->handle != INVALID_HANDLE_VALUE)\r
+      result = FindClose(dir->handle) ? 0 : -1;\r
+\r
+    free(dir);\r
+  } else {\r
+    result = -1;\r
+    SetLastError(ERROR_BAD_ARGUMENTS);\r
+  }\r
+\r
+  return result;\r
+}\r
+\r
+static struct dirent *readdir(DIR *dir) {\r
+  struct dirent *result = 0;\r
+\r
+  if (dir) {\r
+    if (dir->handle != INVALID_HANDLE_VALUE) {\r
+      result = &dir->result;\r
+      (void) WideCharToMultiByte(CP_UTF8, 0,\r
+          dir->info.cFileName, -1, result->d_name,\r
+          sizeof(result->d_name), NULL, NULL);\r
+\r
+      if (!FindNextFileW(dir->handle, &dir->info)) {\r
+        (void) FindClose(dir->handle);\r
+        dir->handle = INVALID_HANDLE_VALUE;\r
+      }\r
+\r
+    } else {\r
+      SetLastError(ERROR_FILE_NOT_FOUND);\r
+    }\r
+  } else {\r
+    SetLastError(ERROR_BAD_ARGUMENTS);\r
+  }\r
+\r
+  return result;\r
+}\r
+\r
+#ifndef HAVE_POLL\r
+static int poll(struct pollfd *pfd, int n, int milliseconds) {\r
+  struct timeval tv;\r
+  fd_set set;\r
+  int i, result;\r
+\r
+  tv.tv_sec = milliseconds / 1000;\r
+  tv.tv_usec = (milliseconds % 1000) * 1000;\r
+  FD_ZERO(&set);\r
+\r
+  for (i = 0; i < n; i++) {\r
+    FD_SET((SOCKET) pfd[i].fd, &set);\r
+    pfd[i].revents = 0;\r
+  }\r
+\r
+  if ((result = select(0, &set, NULL, NULL, &tv)) > 0) {\r
+    for (i = 0; i < n; i++) {\r
+      if (FD_ISSET(pfd[i].fd, &set)) {\r
+        pfd[i].revents = POLLIN;\r
+      }\r
+    }\r
+  }\r
+\r
+  return result;\r
+}\r
+#endif // HAVE_POLL\r
+\r
+#define set_close_on_exec(x) // No FD_CLOEXEC on Windows\r
+\r
+int mg_start_thread(mg_thread_func_t f, void *p) {\r
+  return _beginthread((void (__cdecl *)(void *)) f, 0, p) == -1L ? -1 : 0;\r
+}\r
+\r
+static HANDLE dlopen(const char *dll_name, int flags) {\r
+  wchar_t wbuf[PATH_MAX];\r
+  flags = 0; // Unused\r
+  to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));\r
+  return LoadLibraryW(wbuf);\r
+}\r
+\r
+#if !defined(NO_CGI)\r
+#define SIGKILL 0\r
+static int kill(pid_t pid, int sig_num) {\r
+  (void) TerminateProcess(pid, sig_num);\r
+  (void) CloseHandle(pid);\r
+  return 0;\r
+}\r
+\r
+static void trim_trailing_whitespaces(char *s) {\r
+  char *e = s + strlen(s) - 1;\r
+  while (e > s && isspace(* (unsigned char *) e)) {\r
+    *e-- = '\0';\r
+  }\r
+}\r
+\r
+static pid_t spawn_process(struct mg_connection *conn, const char *prog,\r
+                           char *envblk, char *envp[], int fd_stdin,\r
+                           int fd_stdout, const char *dir) {\r
+  HANDLE me;\r
+  char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],\r
+       cmdline[PATH_MAX], buf[PATH_MAX];\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+  STARTUPINFOA si = { sizeof(si) };\r
+  PROCESS_INFORMATION pi = { 0 };\r
+\r
+  envp = NULL; // Unused\r
+\r
+  // TODO(lsm): redirect CGI errors to the error log file\r
+  si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;\r
+  si.wShowWindow = SW_HIDE;\r
+\r
+  me = GetCurrentProcess();\r
+  DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdin), me,\r
+                  &si.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS);\r
+  DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdout), me,\r
+                  &si.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS);\r
+\r
+  // If CGI file is a script, try to read the interpreter line\r
+  interp = conn->ctx->config[CGI_INTERPRETER];\r
+  if (interp == NULL) {\r
+    buf[0] = buf[1] = '\0';\r
+\r
+    // Read the first line of the script into the buffer\r
+    snprintf(cmdline, sizeof(cmdline), "%s%c%s", dir, '/', prog);\r
+    if (mg_fopen(conn, cmdline, "r", &file)) {\r
+      p = (char *) file.membuf;\r
+      mg_fgets(buf, sizeof(buf), &file, &p);\r
+      mg_fclose(&file);\r
+      buf[sizeof(buf) - 1] = '\0';\r
+    }\r
+\r
+    if (buf[0] == '#' && buf[1] == '!') {\r
+      trim_trailing_whitespaces(buf + 2);\r
+    } else {\r
+      buf[2] = '\0';\r
+    }\r
+    interp = buf + 2;\r
+  }\r
+\r
+  if (interp[0] != '\0') {\r
+    GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);\r
+    interp = full_interp;\r
+  }\r
+  GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);\r
+\r
+  mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%s%s\\%s",\r
+              interp, interp[0] == '\0' ? "" : " ", full_dir, prog);\r
+\r
+  DEBUG_TRACE(("Running [%s]", cmdline));\r
+  if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE,\r
+        CREATE_NEW_PROCESS_GROUP, envblk, NULL, &si, &pi) == 0) {\r
+    cry(conn, "%s: CreateProcess(%s): %d",\r
+        __func__, cmdline, ERRNO);\r
+    pi.hProcess = (pid_t) -1;\r
+  }\r
+\r
+  // Always close these to prevent handle leakage.\r
+  (void) close(fd_stdin);\r
+  (void) close(fd_stdout);\r
+\r
+  (void) CloseHandle(si.hStdOutput);\r
+  (void) CloseHandle(si.hStdInput);\r
+  (void) CloseHandle(pi.hThread);\r
+\r
+  return (pid_t) pi.hProcess;\r
+}\r
+#endif // !NO_CGI\r
+\r
+static int set_non_blocking_mode(SOCKET sock) {\r
+  unsigned long on = 1;\r
+  return ioctlsocket(sock, FIONBIO, &on);\r
+}\r
+\r
+#else\r
+static int mg_stat(struct mg_connection *conn, const char *path,\r
+                   struct file *filep) {\r
+  struct stat st;\r
+\r
+  if (!is_file_in_memory(conn, path, filep) && !stat(path, &st)) {\r
+    filep->size = st.st_size;\r
+    filep->modification_time = st.st_mtime;\r
+    filep->is_directory = S_ISDIR(st.st_mode);\r
+  } else {\r
+    filep->modification_time = (time_t) 0;\r
+  }\r
+\r
+  return filep->membuf != NULL || filep->modification_time != (time_t) 0;\r
+}\r
+\r
+static void set_close_on_exec(int fd) {\r
+  fcntl(fd, F_SETFD, FD_CLOEXEC);\r
+}\r
+\r
+int mg_start_thread(mg_thread_func_t func, void *param) {\r
+  pthread_t thread_id;\r
+  pthread_attr_t attr;\r
+\r
+  (void) pthread_attr_init(&attr);\r
+  (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);\r
+  // TODO(lsm): figure out why mongoose dies on Linux if next line is enabled\r
+  // (void) pthread_attr_setstacksize(&attr, sizeof(struct mg_connection) * 5);\r
+\r
+  return pthread_create(&thread_id, &attr, func, param);\r
+}\r
+\r
+#ifndef NO_CGI\r
+static pid_t spawn_process(struct mg_connection *conn, const char *prog,\r
+                           char *envblk, char *envp[], int fd_stdin,\r
+                           int fd_stdout, const char *dir) {\r
+  pid_t pid;\r
+  const char *interp;\r
+\r
+  (void) envblk;\r
+\r
+  if ((pid = fork()) == -1) {\r
+    // Parent\r
+    send_http_error(conn, 500, http_500_error, "fork(): %s", strerror(ERRNO));\r
+  } else if (pid == 0) {\r
+    // Child\r
+    if (chdir(dir) != 0) {\r
+      cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));\r
+    } else if (dup2(fd_stdin, 0) == -1) {\r
+      cry(conn, "%s: dup2(%d, 0): %s", __func__, fd_stdin, strerror(ERRNO));\r
+    } else if (dup2(fd_stdout, 1) == -1) {\r
+      cry(conn, "%s: dup2(%d, 1): %s", __func__, fd_stdout, strerror(ERRNO));\r
+    } else {\r
+      (void) dup2(fd_stdout, 2);\r
+      (void) close(fd_stdin);\r
+      (void) close(fd_stdout);\r
+\r
+      // After exec, all signal handlers are restored to their default values,\r
+      // with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's\r
+      // implementation, SIGCHLD's handler will leave unchanged after exec\r
+      // if it was set to be ignored. Restore it to default action.\r
+      signal(SIGCHLD, SIG_DFL);\r
+\r
+      interp = conn->ctx->config[CGI_INTERPRETER];\r
+      if (interp == NULL) {\r
+        (void) execle(prog, prog, NULL, envp);\r
+        cry(conn, "%s: execle(%s): %s", __func__, prog, strerror(ERRNO));\r
+      } else {\r
+        (void) execle(interp, interp, prog, NULL, envp);\r
+        cry(conn, "%s: execle(%s %s): %s", __func__, interp, prog,\r
+            strerror(ERRNO));\r
+      }\r
+    }\r
+    exit(EXIT_FAILURE);\r
+  }\r
+\r
+  // Parent. Close stdio descriptors\r
+  (void) close(fd_stdin);\r
+  (void) close(fd_stdout);\r
+\r
+  return pid;\r
+}\r
+#endif // !NO_CGI\r
+\r
+static int set_non_blocking_mode(SOCKET sock) {\r
+  int flags;\r
+\r
+  flags = fcntl(sock, F_GETFL, 0);\r
+  (void) fcntl(sock, F_SETFL, flags | O_NONBLOCK);\r
+\r
+  return 0;\r
+}\r
+#endif // _WIN32\r
+\r
+// Write data to the IO channel - opened file descriptor, socket or SSL\r
+// descriptor. Return number of bytes written.\r
+static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf,\r
+                    int64_t len) {\r
+  int64_t sent;\r
+  int n, k;\r
+\r
+  sent = 0;\r
+  while (sent < len) {\r
+\r
+    // How many bytes we send in this iteration\r
+    k = len - sent > INT_MAX ? INT_MAX : (int) (len - sent);\r
+\r
+#ifndef NO_SSL\r
+    if (ssl != NULL) {\r
+      n = SSL_write(ssl, buf + sent, k);\r
+    } else\r
+#endif\r
+      if (fp != NULL) {\r
+      n = (int) fwrite(buf + sent, 1, (size_t) k, fp);\r
+      if (ferror(fp))\r
+        n = -1;\r
+    } else {\r
+      n = send(sock, buf + sent, (size_t) k, MSG_NOSIGNAL);\r
+    }\r
+\r
+    if (n <= 0)\r
+      break;\r
+\r
+    sent += n;\r
+  }\r
+\r
+  return sent;\r
+}\r
+\r
+// Read from IO channel - opened file descriptor, socket, or SSL descriptor.\r
+// Return negative value on error, or number of bytes read on success.\r
+static int pull(FILE *fp, struct mg_connection *conn, char *buf, int len) {\r
+  int nread;\r
+\r
+  if (fp != NULL) {\r
+    // Use read() instead of fread(), because if we're reading from the CGI\r
+    // pipe, fread() may block until IO buffer is filled up. We cannot afford\r
+    // to block and must pass all read bytes immediately to the client.\r
+    nread = read(fileno(fp), buf, (size_t) len);\r
+#ifndef NO_SSL\r
+  } else if (conn->ssl != NULL) {\r
+    nread = SSL_read(conn->ssl, buf, len);\r
+#endif\r
+  } else {\r
+    nread = recv(conn->client.sock, buf, (size_t) len, 0);\r
+  }\r
+\r
+  return conn->ctx->stop_flag ? -1 : nread;\r
+}\r
+\r
+int mg_read(struct mg_connection *conn, void *buf, size_t len) {\r
+  int n, buffered_len, nread;\r
+  const char *body;\r
+\r
+  nread = 0;\r
+  if (conn->consumed_content < conn->content_len) {\r
+    // Adjust number of bytes to read.\r
+    int64_t to_read = conn->content_len - conn->consumed_content;\r
+    if (to_read < (int64_t) len) {\r
+      len = (size_t) to_read;\r
+    }\r
+\r
+    // Return buffered data\r
+    body = conn->buf + conn->request_len + conn->consumed_content;\r
+    buffered_len = &conn->buf[conn->data_len] - body;\r
+    if (buffered_len > 0) {\r
+      if (len < (size_t) buffered_len) {\r
+        buffered_len = (int) len;\r
+      }\r
+      memcpy(buf, body, (size_t) buffered_len);\r
+      len -= buffered_len;\r
+      conn->consumed_content += buffered_len;\r
+      nread += buffered_len;\r
+      buf = (char *) buf + buffered_len;\r
+    }\r
+\r
+    // We have returned all buffered data. Read new data from the remote socket.\r
+    while (len > 0) {\r
+      n = pull(NULL, conn, (char *) buf, (int) len);\r
+      if (n < 0) {\r
+        nread = n;  // Propagate the error\r
+        break;\r
+      } else if (n == 0) {\r
+        break;  // No more data to read\r
+      } else {\r
+        buf = (char *) buf + n;\r
+        conn->consumed_content += n;\r
+        nread += n;\r
+        len -= n;\r
+      }\r
+    }\r
+  }\r
+  return nread;\r
+}\r
+\r
+int mg_write(struct mg_connection *conn, const void *buf, size_t len) {\r
+  time_t now;\r
+  int64_t n, total, allowed;\r
+\r
+  if (conn->throttle > 0) {\r
+    if ((now = time(NULL)) != conn->last_throttle_time) {\r
+      conn->last_throttle_time = now;\r
+      conn->last_throttle_bytes = 0;\r
+    }\r
+    allowed = conn->throttle - conn->last_throttle_bytes;\r
+    if (allowed > (int64_t) len) {\r
+      allowed = len;\r
+    }\r
+    if ((total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,\r
+                      (int64_t) allowed)) == allowed) {\r
+      buf = (char *) buf + total;\r
+      conn->last_throttle_bytes += total;\r
+      while (total < (int64_t) len && conn->ctx->stop_flag == 0) {\r
+        allowed = conn->throttle > (int64_t) len - total ?\r
+          (int64_t) len - total : conn->throttle;\r
+        if ((n = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,\r
+                      (int64_t) allowed)) != allowed) {\r
+          break;\r
+        }\r
+        sleep(1);\r
+        conn->last_throttle_bytes = allowed;\r
+        conn->last_throttle_time = time(NULL);\r
+        buf = (char *) buf + n;\r
+        total += n;\r
+      }\r
+    }\r
+  } else {\r
+    total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,\r
+                 (int64_t) len);\r
+  }\r
+  return (int) total;\r
+}\r
+\r
+// Print message to buffer. If buffer is large enough to hold the message,\r
+// return buffer. If buffer is to small, allocate large enough buffer on heap,\r
+// and return allocated buffer.\r
+static int alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap) {\r
+  va_list ap_copy;\r
+  int len;\r
+\r
+  // Windows is not standard-compliant, and vsnprintf() returns -1 if\r
+  // buffer is too small. Also, older versions of msvcrt.dll do not have\r
+  // _vscprintf().  However, if size is 0, vsnprintf() behaves correctly.\r
+  // Therefore, we make two passes: on first pass, get required message length.\r
+  // On second pass, actually print the message.\r
+  va_copy(ap_copy, ap);\r
+  len = vsnprintf(NULL, 0, fmt, ap_copy);\r
+\r
+  if (len > (int) size &&\r
+      (size = len + 1) > 0 &&\r
+      (*buf = (char *) malloc(size)) == NULL) {\r
+    len = -1;  // Allocation failed, mark failure\r
+  } else {\r
+    va_copy(ap_copy, ap);\r
+    vsnprintf(*buf, size, fmt, ap_copy);\r
+  }\r
+\r
+  return len;\r
+}\r
+\r
+int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap) {\r
+  char mem[MG_BUF_LEN], *buf = mem;\r
+  int len;\r
+\r
+  if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) {\r
+    len = mg_write(conn, buf, (size_t) len);\r
+  }\r
+  if (buf != mem && buf != NULL) {\r
+    free(buf);\r
+  }\r
+\r
+  return len;\r
+}\r
+\r
+int mg_printf(struct mg_connection *conn, const char *fmt, ...) {\r
+  va_list ap;\r
+  va_start(ap, fmt);\r
+  return mg_vprintf(conn, fmt, ap);\r
+}\r
+\r
+// URL-decode input buffer into destination buffer.\r
+// 0-terminate the destination buffer. Return the length of decoded data.\r
+// form-url-encoded data differs from URI encoding in a way that it\r
+// uses '+' as character for space, see RFC 1866 section 8.2.1\r
+// http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt\r
+static int url_decode(const char *src, int src_len, char *dst,\r
+                      int dst_len, int is_form_url_encoded) {\r
+  int i, j, a, b;\r
+#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')\r
+\r
+  for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {\r
+    if (src[i] == '%' &&\r
+        isxdigit(* (const unsigned char *) (src + i + 1)) &&\r
+        isxdigit(* (const unsigned char *) (src + i + 2))) {\r
+      a = tolower(* (const unsigned char *) (src + i + 1));\r
+      b = tolower(* (const unsigned char *) (src + i + 2));\r
+      dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));\r
+      i += 2;\r
+    } else if (is_form_url_encoded && src[i] == '+') {\r
+      dst[j] = ' ';\r
+    } else {\r
+      dst[j] = src[i];\r
+    }\r
+  }\r
+\r
+  dst[j] = '\0'; // Null-terminate the destination\r
+\r
+  return i >= src_len ? j : -1;\r
+}\r
+\r
+int mg_get_var(const char *data, size_t data_len, const char *name,\r
+               char *dst, size_t dst_len) {\r
+  const char *p, *e, *s;\r
+  size_t name_len;\r
+  int len;\r
+\r
+  if (dst == NULL || dst_len == 0) {\r
+    len = -2;\r
+  } else if (data == NULL || name == NULL || data_len == 0) {\r
+    len = -1;\r
+    dst[0] = '\0';\r
+  } else {\r
+    name_len = strlen(name);\r
+    e = data + data_len;\r
+    len = -1;\r
+    dst[0] = '\0';\r
+\r
+    // data is "var1=val1&var2=val2...". Find variable first\r
+    for (p = data; p + name_len < e; p++) {\r
+      if ((p == data || p[-1] == '&') && p[name_len] == '=' &&\r
+          !mg_strncasecmp(name, p, name_len)) {\r
+\r
+        // Point p to variable value\r
+        p += name_len + 1;\r
+\r
+        // Point s to the end of the value\r
+        s = (const char *) memchr(p, '&', (size_t)(e - p));\r
+        if (s == NULL) {\r
+          s = e;\r
+        }\r
+        assert(s >= p);\r
+\r
+        // Decode variable into destination buffer\r
+        len = url_decode(p, (size_t)(s - p), dst, dst_len, 1);\r
+\r
+        // Redirect error code from -1 to -2 (destination buffer too small).\r
+        if (len == -1) {\r
+          len = -2;\r
+        }\r
+        break;\r
+      }\r
+    }\r
+  }\r
+\r
+  return len;\r
+}\r
+\r
+int mg_get_cookie(const struct mg_connection *conn, const char *cookie_name,\r
+                  char *dst, size_t dst_size) {\r
+  const char *s, *p, *end;\r
+  int name_len, len = -1;\r
+\r
+  if (dst == NULL || dst_size == 0) {\r
+      len = -2;\r
+  } else if (cookie_name == NULL || (s = mg_get_header(conn, "Cookie")) == NULL) {\r
+      len = -1;\r
+      dst[0] = '\0';\r
+  } else {\r
+    name_len = (int) strlen(cookie_name);\r
+    end = s + strlen(s);\r
+    dst[0] = '\0';\r
+\r
+    for (; (s = strstr(s, cookie_name)) != NULL; s += name_len) {\r
+      if (s[name_len] == '=') {\r
+        s += name_len + 1;\r
+        if ((p = strchr(s, ' ')) == NULL)\r
+          p = end;\r
+        if (p[-1] == ';')\r
+          p--;\r
+        if (*s == '"' && p[-1] == '"' && p > s + 1) {\r
+          s++;\r
+          p--;\r
+        }\r
+        if ((size_t) (p - s) < dst_size) {\r
+          len = p - s;\r
+          mg_strlcpy(dst, s, (size_t) len + 1);\r
+        } else {\r
+          len = -2;\r
+        }\r
+        break;\r
+      }\r
+    }\r
+  }\r
+  return len;\r
+}\r
+\r
+static void convert_uri_to_file_name(struct mg_connection *conn, char *buf,\r
+                                     size_t buf_len, struct file *filep) {\r
+  struct vec a, b;\r
+  const char *rewrite, *uri = conn->request_info.uri;\r
+  char *p;\r
+  int match_len;\r
+\r
+  // Using buf_len - 1 because memmove() for PATH_INFO may shift part\r
+  // of the path one byte on the right.\r
+  mg_snprintf(conn, buf, buf_len - 1, "%s%s", conn->ctx->config[DOCUMENT_ROOT],\r
+              uri);\r
+\r
+  rewrite = conn->ctx->config[REWRITE];\r
+  while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {\r
+    if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {\r
+      mg_snprintf(conn, buf, buf_len - 1, "%.*s%s", (int) b.len, b.ptr,\r
+                  uri + match_len);\r
+      break;\r
+    }\r
+  }\r
+\r
+  if (!mg_stat(conn, buf, filep)) {\r
+    // Support PATH_INFO for CGI scripts.\r
+    for (p = buf + strlen(buf); p > buf + 1; p--) {\r
+      if (*p == '/') {\r
+        *p = '\0';\r
+        if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],\r
+                         strlen(conn->ctx->config[CGI_EXTENSIONS]), buf) > 0 &&\r
+            mg_stat(conn, buf, filep)) {\r
+          // Shift PATH_INFO block one character right, e.g.\r
+          //  "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"\r
+          // conn->path_info is pointing to the local variable "path" declared\r
+          // in handle_request(), so PATH_INFO is not valid after\r
+          // handle_request returns.\r
+          conn->path_info = p + 1;\r
+          memmove(p + 2, p + 1, strlen(p + 1) + 1);  // +1 is for trailing \0\r
+          p[1] = '/';\r
+          break;\r
+        } else {\r
+          *p = '/';\r
+        }\r
+      }\r
+    }\r
+  }\r
+}\r
+\r
+// Check whether full request is buffered. Return:\r
+//   -1  if request is malformed\r
+//    0  if request is not yet fully buffered\r
+//   >0  actual request length, including last \r\n\r\n\r
+static int get_request_len(const char *buf, int buflen) {\r
+  const char *s, *e;\r
+  int len = 0;\r
+\r
+  for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)\r
+    // Control characters are not allowed but >=128 is.\r
+    if (!isprint(* (const unsigned char *) s) && *s != '\r' &&\r
+        *s != '\n' && * (const unsigned char *) s < 128) {\r
+      len = -1;\r
+      break;  // [i_a] abort scan as soon as one malformed character is found;\r
+              // don't let subsequent \r\n\r\n win us over anyhow\r
+    } else if (s[0] == '\n' && s[1] == '\n') {\r
+      len = (int) (s - buf) + 2;\r
+    } else if (s[0] == '\n' && &s[1] < e &&\r
+        s[1] == '\r' && s[2] == '\n') {\r
+      len = (int) (s - buf) + 3;\r
+    }\r
+\r
+  return len;\r
+}\r
+\r
+// Convert month to the month number. Return -1 on error, or month number\r
+static int get_month_index(const char *s) {\r
+  size_t i;\r
+\r
+  for (i = 0; i < ARRAY_SIZE(month_names); i++)\r
+    if (!strcmp(s, month_names[i]))\r
+      return (int) i;\r
+\r
+  return -1;\r
+}\r
+\r
+static int num_leap_years(int year) {\r
+  return year / 4 - year / 100 + year / 400;\r
+}\r
+\r
+// Parse UTC date-time string, and return the corresponding time_t value.\r
+static time_t parse_date_string(const char *datetime) {\r
+  static const unsigned short days_before_month[] = {\r
+    0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334\r
+  };\r
+  char month_str[32];\r
+  int second, minute, hour, day, month, year, leap_days, days;\r
+  time_t result = (time_t) 0;\r
+\r
+  if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d",\r
+               &day, month_str, &year, &hour, &minute, &second) == 6) ||\r
+       (sscanf(datetime, "%d %3s %d %d:%d:%d",\r
+               &day, month_str, &year, &hour, &minute, &second) == 6) ||\r
+       (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",\r
+               &day, month_str, &year, &hour, &minute, &second) == 6) ||\r
+       (sscanf(datetime, "%d-%3s-%d %d:%d:%d",\r
+               &day, month_str, &year, &hour, &minute, &second) == 6)) &&\r
+      year > 1970 &&\r
+      (month = get_month_index(month_str)) != -1) {\r
+    leap_days = num_leap_years(year) - num_leap_years(1970);\r
+    year -= 1970;\r
+    days = year * 365 + days_before_month[month] + (day - 1) + leap_days;\r
+    result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;\r
+  }\r
+\r
+  return result;\r
+}\r
+\r
+// Protect against directory disclosure attack by removing '..',\r
+// excessive '/' and '\' characters\r
+static void remove_double_dots_and_double_slashes(char *s) {\r
+  char *p = s;\r
+\r
+  while (*s != '\0') {\r
+    *p++ = *s++;\r
+    if (s[-1] == '/' || s[-1] == '\\') {\r
+      // Skip all following slashes, backslashes and double-dots\r
+      while (s[0] != '\0') {\r
+        if (s[0] == '/' || s[0] == '\\') {\r
+          s++;\r
+        } else if (s[0] == '.' && s[1] == '.') {\r
+          s += 2;\r
+        } else {\r
+          break;\r
+        }\r
+      }\r
+    }\r
+  }\r
+  *p = '\0';\r
+}\r
+\r
+static const struct {\r
+  const char *extension;\r
+  size_t ext_len;\r
+  const char *mime_type;\r
+} builtin_mime_types[] = {\r
+  {".html", 5, "text/html"},\r
+  {".htm", 4, "text/html"},\r
+  {".shtm", 5, "text/html"},\r
+  {".shtml", 6, "text/html"},\r
+  {".css", 4, "text/css"},\r
+  {".js",  3, "application/x-javascript"},\r
+  {".ico", 4, "image/x-icon"},\r
+  {".gif", 4, "image/gif"},\r
+  {".jpg", 4, "image/jpeg"},\r
+  {".jpeg", 5, "image/jpeg"},\r
+  {".png", 4, "image/png"},\r
+  {".svg", 4, "image/svg+xml"},\r
+  {".txt", 4, "text/plain"},\r
+  {".torrent", 8, "application/x-bittorrent"},\r
+  {".wav", 4, "audio/x-wav"},\r
+  {".mp3", 4, "audio/x-mp3"},\r
+  {".mid", 4, "audio/mid"},\r
+  {".m3u", 4, "audio/x-mpegurl"},\r
+  {".ogg", 4, "audio/ogg"},\r
+  {".ram", 4, "audio/x-pn-realaudio"},\r
+  {".xml", 4, "text/xml"},\r
+  {".json",  5, "text/json"},\r
+  {".xslt", 5, "application/xml"},\r
+  {".xsl", 4, "application/xml"},\r
+  {".ra",  3, "audio/x-pn-realaudio"},\r
+  {".doc", 4, "application/msword"},\r
+  {".exe", 4, "application/octet-stream"},\r
+  {".zip", 4, "application/x-zip-compressed"},\r
+  {".xls", 4, "application/excel"},\r
+  {".tgz", 4, "application/x-tar-gz"},\r
+  {".tar", 4, "application/x-tar"},\r
+  {".gz",  3, "application/x-gunzip"},\r
+  {".arj", 4, "application/x-arj-compressed"},\r
+  {".rar", 4, "application/x-arj-compressed"},\r
+  {".rtf", 4, "application/rtf"},\r
+  {".pdf", 4, "application/pdf"},\r
+  {".swf", 4, "application/x-shockwave-flash"},\r
+  {".mpg", 4, "video/mpeg"},\r
+  {".webm", 5, "video/webm"},\r
+  {".mpeg", 5, "video/mpeg"},\r
+  {".mp4", 4, "video/mp4"},\r
+  {".m4v", 4, "video/x-m4v"},\r
+  {".asf", 4, "video/x-ms-asf"},\r
+  {".avi", 4, "video/x-msvideo"},\r
+  {".bmp", 4, "image/bmp"},\r
+  {NULL,  0, NULL}\r
+};\r
+\r
+const char *mg_get_builtin_mime_type(const char *path) {\r
+  const char *ext;\r
+  size_t i, path_len;\r
+\r
+  path_len = strlen(path);\r
+\r
+  for (i = 0; builtin_mime_types[i].extension != NULL; i++) {\r
+    ext = path + (path_len - builtin_mime_types[i].ext_len);\r
+    if (path_len > builtin_mime_types[i].ext_len &&\r
+        mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {\r
+      return builtin_mime_types[i].mime_type;\r
+    }\r
+  }\r
+\r
+  return "text/plain";\r
+}\r
+\r
+// Look at the "path" extension and figure what mime type it has.\r
+// Store mime type in the vector.\r
+static void get_mime_type(struct mg_context *ctx, const char *path,\r
+                          struct vec *vec) {\r
+  struct vec ext_vec, mime_vec;\r
+  const char *list, *ext;\r
+  size_t path_len;\r
+\r
+  path_len = strlen(path);\r
+\r
+  // Scan user-defined mime types first, in case user wants to\r
+  // override default mime types.\r
+  list = ctx->config[EXTRA_MIME_TYPES];\r
+  while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {\r
+    // ext now points to the path suffix\r
+    ext = path + path_len - ext_vec.len;\r
+    if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {\r
+      *vec = mime_vec;\r
+      return;\r
+    }\r
+  }\r
+\r
+  vec->ptr = mg_get_builtin_mime_type(path);\r
+  vec->len = strlen(vec->ptr);\r
+}\r
+\r
+static int is_big_endian(void) {\r
+  static const int n = 1;\r
+  return ((char *) &n)[0] == 0;\r
+}\r
+\r
+#ifndef HAVE_MD5\r
+typedef struct MD5Context {\r
+  uint32_t buf[4];\r
+  uint32_t bits[2];\r
+  unsigned char in[64];\r
+} MD5_CTX;\r
+\r
+static void byteReverse(unsigned char *buf, unsigned longs) {\r
+  uint32_t t;\r
+\r
+  // Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN\r
+  if (is_big_endian()) {\r
+    do {\r
+      t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |\r
+        ((unsigned) buf[1] << 8 | buf[0]);\r
+      * (uint32_t *) buf = t;\r
+      buf += 4;\r
+    } while (--longs);\r
+  }\r
+}\r
+\r
+#define F1(x, y, z) (z ^ (x & (y ^ z)))\r
+#define F2(x, y, z) F1(z, x, y)\r
+#define F3(x, y, z) (x ^ y ^ z)\r
+#define F4(x, y, z) (y ^ (x | ~z))\r
+\r
+#define MD5STEP(f, w, x, y, z, data, s) \\r
+  ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )\r
+\r
+// Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious\r
+// initialization constants.\r
+static void MD5Init(MD5_CTX *ctx) {\r
+  ctx->buf[0] = 0x67452301;\r
+  ctx->buf[1] = 0xefcdab89;\r
+  ctx->buf[2] = 0x98badcfe;\r
+  ctx->buf[3] = 0x10325476;\r
+\r
+  ctx->bits[0] = 0;\r
+  ctx->bits[1] = 0;\r
+}\r
+\r
+static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {\r
+  register uint32_t a, b, c, d;\r
+\r
+  a = buf[0];\r
+  b = buf[1];\r
+  c = buf[2];\r
+  d = buf[3];\r
+\r
+  MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);\r
+  MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);\r
+  MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);\r
+  MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);\r
+  MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);\r
+  MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);\r
+  MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);\r
+  MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);\r
+  MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);\r
+  MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);\r
+  MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);\r
+  MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);\r
+  MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);\r
+  MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);\r
+  MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);\r
+  MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);\r
+\r
+  MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);\r
+  MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);\r
+  MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);\r
+  MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);\r
+  MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);\r
+  MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);\r
+  MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);\r
+  MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);\r
+  MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);\r
+  MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);\r
+  MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);\r
+  MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);\r
+  MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);\r
+  MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);\r
+  MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);\r
+  MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);\r
+\r
+  MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);\r
+  MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);\r
+  MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);\r
+  MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);\r
+  MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);\r
+  MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);\r
+  MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);\r
+  MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);\r
+  MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);\r
+  MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);\r
+  MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);\r
+  MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);\r
+  MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);\r
+  MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);\r
+  MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);\r
+  MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);\r
+\r
+  MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);\r
+  MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);\r
+  MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);\r
+  MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);\r
+  MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);\r
+  MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);\r
+  MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);\r
+  MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);\r
+  MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);\r
+  MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);\r
+  MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);\r
+  MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);\r
+  MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);\r
+  MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);\r
+  MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);\r
+  MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);\r
+\r
+  buf[0] += a;\r
+  buf[1] += b;\r
+  buf[2] += c;\r
+  buf[3] += d;\r
+}\r
+\r
+static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) {\r
+  uint32_t t;\r
+\r
+  t = ctx->bits[0];\r
+  if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)\r
+    ctx->bits[1]++;\r
+  ctx->bits[1] += len >> 29;\r
+\r
+  t = (t >> 3) & 0x3f;\r
+\r
+  if (t) {\r
+    unsigned char *p = (unsigned char *) ctx->in + t;\r
+\r
+    t = 64 - t;\r
+    if (len < t) {\r
+      memcpy(p, buf, len);\r
+      return;\r
+    }\r
+    memcpy(p, buf, t);\r
+    byteReverse(ctx->in, 16);\r
+    MD5Transform(ctx->buf, (uint32_t *) ctx->in);\r
+    buf += t;\r
+    len -= t;\r
+  }\r
+\r
+  while (len >= 64) {\r
+    memcpy(ctx->in, buf, 64);\r
+    byteReverse(ctx->in, 16);\r
+    MD5Transform(ctx->buf, (uint32_t *) ctx->in);\r
+    buf += 64;\r
+    len -= 64;\r
+  }\r
+\r
+  memcpy(ctx->in, buf, len);\r
+}\r
+\r
+static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) {\r
+  unsigned count;\r
+  unsigned char *p;\r
+\r
+  count = (ctx->bits[0] >> 3) & 0x3F;\r
+\r
+  p = ctx->in + count;\r
+  *p++ = 0x80;\r
+  count = 64 - 1 - count;\r
+  if (count < 8) {\r
+    memset(p, 0, count);\r
+    byteReverse(ctx->in, 16);\r
+    MD5Transform(ctx->buf, (uint32_t *) ctx->in);\r
+    memset(ctx->in, 0, 56);\r
+  } else {\r
+    memset(p, 0, count - 8);\r
+  }\r
+  byteReverse(ctx->in, 14);\r
+\r
+  ((uint32_t *) ctx->in)[14] = ctx->bits[0];\r
+  ((uint32_t *) ctx->in)[15] = ctx->bits[1];\r
+\r
+  MD5Transform(ctx->buf, (uint32_t *) ctx->in);\r
+  byteReverse((unsigned char *) ctx->buf, 4);\r
+  memcpy(digest, ctx->buf, 16);\r
+  memset((char *) ctx, 0, sizeof(*ctx));\r
+}\r
+#endif // !HAVE_MD5\r
+\r
+// Stringify binary data. Output buffer must be twice as big as input,\r
+// because each byte takes 2 bytes in string representation\r
+static void bin2str(char *to, const unsigned char *p, size_t len) {\r
+  static const char *hex = "0123456789abcdef";\r
+\r
+  for (; len--; p++) {\r
+    *to++ = hex[p[0] >> 4];\r
+    *to++ = hex[p[0] & 0x0f];\r
+  }\r
+  *to = '\0';\r
+}\r
+\r
+// Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.\r
+void mg_md5(char buf[33], ...) {\r
+  unsigned char hash[16];\r
+  const char *p;\r
+  va_list ap;\r
+  MD5_CTX ctx;\r
+\r
+  MD5Init(&ctx);\r
+\r
+  va_start(ap, buf);\r
+  while ((p = va_arg(ap, const char *)) != NULL) {\r
+    MD5Update(&ctx, (const unsigned char *) p, (unsigned) strlen(p));\r
+  }\r
+  va_end(ap);\r
+\r
+  MD5Final(hash, &ctx);\r
+  bin2str(buf, hash, sizeof(hash));\r
+}\r
+\r
+// Check the user's password, return 1 if OK\r
+static int check_password(const char *method, const char *ha1, const char *uri,\r
+                          const char *nonce, const char *nc, const char *cnonce,\r
+                          const char *qop, const char *response) {\r
+  char ha2[32 + 1], expected_response[32 + 1];\r
+\r
+  // Some of the parameters may be NULL\r
+  if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL ||\r
+      qop == NULL || response == NULL) {\r
+    return 0;\r
+  }\r
+\r
+  // NOTE(lsm): due to a bug in MSIE, we do not compare the URI\r
+  // TODO(lsm): check for authentication timeout\r
+  if (// strcmp(dig->uri, c->ouri) != 0 ||\r
+      strlen(response) != 32\r
+      // || now - strtoul(dig->nonce, NULL, 10) > 3600\r
+      ) {\r
+    return 0;\r
+  }\r
+\r
+  mg_md5(ha2, method, ":", uri, NULL);\r
+  mg_md5(expected_response, ha1, ":", nonce, ":", nc,\r
+      ":", cnonce, ":", qop, ":", ha2, NULL);\r
+\r
+  return mg_strcasecmp(response, expected_response) == 0;\r
+}\r
+\r
+// Use the global passwords file, if specified by auth_gpass option,\r
+// or search for .htpasswd in the requested directory.\r
+static void open_auth_file(struct mg_connection *conn, const char *path,\r
+                           struct file *filep) {\r
+  char name[PATH_MAX];\r
+  const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];\r
+\r
+  if (gpass != NULL) {\r
+    // Use global passwords file\r
+    if (!mg_fopen(conn, gpass, "r", filep)) {\r
+      cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));\r
+    }\r
+  } else if (mg_stat(conn, path, filep) && filep->is_directory) {\r
+    mg_snprintf(conn, name, sizeof(name), "%s%c%s",\r
+                path, '/', PASSWORDS_FILE_NAME);\r
+    mg_fopen(conn, name, "r", filep);\r
+  } else {\r
+     // Try to find .htpasswd in requested directory.\r
+    for (p = path, e = p + strlen(p) - 1; e > p; e--)\r
+      if (e[0] == '/')\r
+        break;\r
+    mg_snprintf(conn, name, sizeof(name), "%.*s%c%s",\r
+                (int) (e - p), p, '/', PASSWORDS_FILE_NAME);\r
+    mg_fopen(conn, name, "r", filep);\r
+  }\r
+}\r
+\r
+// Parsed Authorization header\r
+struct ah {\r
+  char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;\r
+};\r
+\r
+// Return 1 on success. Always initializes the ah structure.\r
+static int parse_auth_header(struct mg_connection *conn, char *buf,\r
+                             size_t buf_size, struct ah *ah) {\r
+  char *name, *value, *s;\r
+  const char *auth_header;\r
+\r
+  (void) memset(ah, 0, sizeof(*ah));\r
+  if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||\r
+      mg_strncasecmp(auth_header, "Digest ", 7) != 0) {\r
+    return 0;\r
+  }\r
+\r
+  // Make modifiable copy of the auth header\r
+  (void) mg_strlcpy(buf, auth_header + 7, buf_size);\r
+  s = buf;\r
+\r
+  // Parse authorization header\r
+  for (;;) {\r
+    // Gobble initial spaces\r
+    while (isspace(* (unsigned char *) s)) {\r
+      s++;\r
+    }\r
+    name = skip_quoted(&s, "=", " ", 0);\r
+    // Value is either quote-delimited, or ends at first comma or space.\r
+    if (s[0] == '\"') {\r
+      s++;\r
+      value = skip_quoted(&s, "\"", " ", '\\');\r
+      if (s[0] == ',') {\r
+        s++;\r
+      }\r
+    } else {\r
+      value = skip_quoted(&s, ", ", " ", 0);  // IE uses commas, FF uses spaces\r
+    }\r
+    if (*name == '\0') {\r
+      break;\r
+    }\r
+\r
+    if (!strcmp(name, "username")) {\r
+      ah->user = value;\r
+    } else if (!strcmp(name, "cnonce")) {\r
+      ah->cnonce = value;\r
+    } else if (!strcmp(name, "response")) {\r
+      ah->response = value;\r
+    } else if (!strcmp(name, "uri")) {\r
+      ah->uri = value;\r
+    } else if (!strcmp(name, "qop")) {\r
+      ah->qop = value;\r
+    } else if (!strcmp(name, "nc")) {\r
+      ah->nc = value;\r
+    } else if (!strcmp(name, "nonce")) {\r
+      ah->nonce = value;\r
+    }\r
+  }\r
+\r
+  // CGI needs it as REMOTE_USER\r
+  if (ah->user != NULL) {\r
+    conn->request_info.remote_user = mg_strdup(ah->user);\r
+  } else {\r
+    return 0;\r
+  }\r
+\r
+  return 1;\r
+}\r
+\r
+static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p) {\r
+  char *eof;\r
+  size_t len;\r
+\r
+  if (filep->membuf != NULL && *p != NULL) {\r
+    eof = memchr(*p, '\n', &filep->membuf[filep->size] - *p);\r
+    len = (size_t) (eof - *p) > size - 1 ? size - 1 : (size_t) (eof - *p);\r
+    memcpy(buf, *p, len);\r
+    buf[len] = '\0';\r
+    *p = eof;\r
+    return eof;\r
+  } else if (filep->fp != NULL) {\r
+    return fgets(buf, size, filep->fp);\r
+  } else {\r
+    return NULL;\r
+  }\r
+}\r
+\r
+// Authorize against the opened passwords file. Return 1 if authorized.\r
+static int authorize(struct mg_connection *conn, struct file *filep) {\r
+  struct ah ah;\r
+  char line[256], f_user[256], ha1[256], f_domain[256], buf[MG_BUF_LEN], *p;\r
+\r
+  if (!parse_auth_header(conn, buf, sizeof(buf), &ah)) {\r
+    return 0;\r
+  }\r
+\r
+  // Loop over passwords file\r
+  p = (char *) filep->membuf;\r
+  while (mg_fgets(line, sizeof(line), filep, &p) != NULL) {\r
+    if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) != 3) {\r
+      continue;\r
+    }\r
+\r
+    if (!strcmp(ah.user, f_user) &&\r
+        !strcmp(conn->ctx->config[AUTHENTICATION_DOMAIN], f_domain))\r
+      return check_password(conn->request_info.request_method, ha1, ah.uri,\r
+                            ah.nonce, ah.nc, ah.cnonce, ah.qop, ah.response);\r
+  }\r
+\r
+  return 0;\r
+}\r
+\r
+// Return 1 if request is authorised, 0 otherwise.\r
+static int check_authorization(struct mg_connection *conn, const char *path) {\r
+  char fname[PATH_MAX];\r
+  struct vec uri_vec, filename_vec;\r
+  const char *list;\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+  int authorized = 1;\r
+\r
+  list = conn->ctx->config[PROTECT_URI];\r
+  while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {\r
+    if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {\r
+      mg_snprintf(conn, fname, sizeof(fname), "%.*s",\r
+                  (int) filename_vec.len, filename_vec.ptr);\r
+      if (!mg_fopen(conn, fname, "r", &file)) {\r
+        cry(conn, "%s: cannot open %s: %s", __func__, fname, strerror(errno));\r
+      }\r
+      break;\r
+    }\r
+  }\r
+\r
+  if (!is_file_opened(&file)) {\r
+    open_auth_file(conn, path, &file);\r
+  }\r
+\r
+  if (is_file_opened(&file)) {\r
+    authorized = authorize(conn, &file);\r
+    mg_fclose(&file);\r
+  }\r
+\r
+  return authorized;\r
+}\r
+\r
+static void send_authorization_request(struct mg_connection *conn) {\r
+  conn->status_code = 401;\r
+  mg_printf(conn,\r
+            "HTTP/1.1 401 Unauthorized\r\n"\r
+            "Content-Length: 0\r\n"\r
+            "WWW-Authenticate: Digest qop=\"auth\", "\r
+            "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",\r
+            conn->ctx->config[AUTHENTICATION_DOMAIN],\r
+            (unsigned long) time(NULL));\r
+}\r
+\r
+static int is_authorized_for_put(struct mg_connection *conn) {\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+  const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];\r
+  int ret = 0;\r
+\r
+  if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {\r
+    ret = authorize(conn, &file);\r
+    mg_fclose(&file);\r
+  }\r
+\r
+  return ret;\r
+}\r
+\r
+int mg_modify_passwords_file(const char *fname, const char *domain,\r
+                             const char *user, const char *pass) {\r
+  int found;\r
+  char line[512], u[512], d[512], ha1[33], tmp[PATH_MAX];\r
+  FILE *fp, *fp2;\r
+\r
+  found = 0;\r
+  fp = fp2 = NULL;\r
+\r
+  // Regard empty password as no password - remove user record.\r
+  if (pass != NULL && pass[0] == '\0') {\r
+    pass = NULL;\r
+  }\r
+\r
+  (void) snprintf(tmp, sizeof(tmp), "%s.tmp", fname);\r
+\r
+  // Create the file if does not exist\r
+  if ((fp = fopen(fname, "a+")) != NULL) {\r
+    (void) fclose(fp);\r
+  }\r
+\r
+  // Open the given file and temporary file\r
+  if ((fp = fopen(fname, "r")) == NULL) {\r
+    return 0;\r
+  } else if ((fp2 = fopen(tmp, "w+")) == NULL) {\r
+    fclose(fp);\r
+    return 0;\r
+  }\r
+\r
+  // Copy the stuff to temporary file\r
+  while (fgets(line, sizeof(line), fp) != NULL) {\r
+    if (sscanf(line, "%[^:]:%[^:]:%*s", u, d) != 2) {\r
+      continue;\r
+    }\r
+\r
+    if (!strcmp(u, user) && !strcmp(d, domain)) {\r
+      found++;\r
+      if (pass != NULL) {\r
+        mg_md5(ha1, user, ":", domain, ":", pass, NULL);\r
+        fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);\r
+      }\r
+    } else {\r
+      fprintf(fp2, "%s", line);\r
+    }\r
+  }\r
+\r
+  // If new user, just add it\r
+  if (!found && pass != NULL) {\r
+    mg_md5(ha1, user, ":", domain, ":", pass, NULL);\r
+    fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);\r
+  }\r
+\r
+  // Close files\r
+  fclose(fp);\r
+  fclose(fp2);\r
+\r
+  // Put the temp file in place of real file\r
+  remove(fname);\r
+  rename(tmp, fname);\r
+\r
+  return 1;\r
+}\r
+\r
+struct de {\r
+  struct mg_connection *conn;\r
+  char *file_name;\r
+  struct file file;\r
+};\r
+\r
+static void url_encode(const char *src, char *dst, size_t dst_len) {\r
+  static const char *dont_escape = "._-$,;~()";\r
+  static const char *hex = "0123456789abcdef";\r
+  const char *end = dst + dst_len - 1;\r
+\r
+  for (; *src != '\0' && dst < end; src++, dst++) {\r
+    if (isalnum(*(const unsigned char *) src) ||\r
+        strchr(dont_escape, * (const unsigned char *) src) != NULL) {\r
+      *dst = *src;\r
+    } else if (dst + 2 < end) {\r
+      dst[0] = '%';\r
+      dst[1] = hex[(* (const unsigned char *) src) >> 4];\r
+      dst[2] = hex[(* (const unsigned char *) src) & 0xf];\r
+      dst += 2;\r
+    }\r
+  }\r
+\r
+  *dst = '\0';\r
+}\r
+\r
+static void print_dir_entry(struct de *de) {\r
+  char size[64], mod[64], href[PATH_MAX];\r
+\r
+  if (de->file.is_directory) {\r
+    mg_snprintf(de->conn, size, sizeof(size), "%s", "[DIRECTORY]");\r
+  } else {\r
+     // We use (signed) cast below because MSVC 6 compiler cannot\r
+     // convert unsigned __int64 to double. Sigh.\r
+    if (de->file.size < 1024) {\r
+      mg_snprintf(de->conn, size, sizeof(size), "%d", (int) de->file.size);\r
+    } else if (de->file.size < 0x100000) {\r
+      mg_snprintf(de->conn, size, sizeof(size),\r
+                  "%.1fk", (double) de->file.size / 1024.0);\r
+    } else if (de->file.size < 0x40000000) {\r
+      mg_snprintf(de->conn, size, sizeof(size),\r
+                  "%.1fM", (double) de->file.size / 1048576);\r
+    } else {\r
+      mg_snprintf(de->conn, size, sizeof(size),\r
+                  "%.1fG", (double) de->file.size / 1073741824);\r
+    }\r
+  }\r
+  strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M",\r
+           localtime(&de->file.modification_time));\r
+  url_encode(de->file_name, href, sizeof(href));\r
+  de->conn->num_bytes_sent += mg_printf(de->conn,\r
+      "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"\r
+      "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",\r
+      de->conn->request_info.uri, href, de->file.is_directory ? "/" : "",\r
+      de->file_name, de->file.is_directory ? "/" : "", mod, size);\r
+}\r
+\r
+// This function is called from send_directory() and used for\r
+// sorting directory entries by size, or name, or modification time.\r
+// On windows, __cdecl specification is needed in case if project is built\r
+// with __stdcall convention. qsort always requires __cdels callback.\r
+static int WINCDECL compare_dir_entries(const void *p1, const void *p2) {\r
+  const struct de *a = (const struct de *) p1, *b = (const struct de *) p2;\r
+  const char *query_string = a->conn->request_info.query_string;\r
+  int cmp_result = 0;\r
+\r
+  if (query_string == NULL) {\r
+    query_string = "na";\r
+  }\r
+\r
+  if (a->file.is_directory && !b->file.is_directory) {\r
+    return -1;  // Always put directories on top\r
+  } else if (!a->file.is_directory && b->file.is_directory) {\r
+    return 1;   // Always put directories on top\r
+  } else if (*query_string == 'n') {\r
+    cmp_result = strcmp(a->file_name, b->file_name);\r
+  } else if (*query_string == 's') {\r
+    cmp_result = a->file.size == b->file.size ? 0 :\r
+      a->file.size > b->file.size ? 1 : -1;\r
+  } else if (*query_string == 'd') {\r
+    cmp_result = a->file.modification_time == b->file.modification_time ? 0 :\r
+      a->file.modification_time > b->file.modification_time ? 1 : -1;\r
+  }\r
+\r
+  return query_string[1] == 'd' ? -cmp_result : cmp_result;\r
+}\r
+\r
+static int must_hide_file(struct mg_connection *conn, const char *path) {\r
+  const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";\r
+  const char *pattern = conn->ctx->config[HIDE_FILES];\r
+  return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 ||\r
+    (pattern != NULL && match_prefix(pattern, strlen(pattern), path) > 0);\r
+}\r
+\r
+static int scan_directory(struct mg_connection *conn, const char *dir,\r
+                          void *data, void (*cb)(struct de *, void *)) {\r
+  char path[PATH_MAX];\r
+  struct dirent *dp;\r
+  DIR *dirp;\r
+  struct de de;\r
+\r
+  if ((dirp = opendir(dir)) == NULL) {\r
+    return 0;\r
+  } else {\r
+    de.conn = conn;\r
+\r
+    while ((dp = readdir(dirp)) != NULL) {\r
+      // Do not show current dir and hidden files\r
+      if (!strcmp(dp->d_name, ".") ||\r
+          !strcmp(dp->d_name, "..") ||\r
+          must_hide_file(conn, dp->d_name)) {\r
+        continue;\r
+      }\r
+\r
+      mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);\r
+\r
+      // If we don't memset stat structure to zero, mtime will have\r
+      // garbage and strftime() will segfault later on in\r
+      // print_dir_entry(). memset is required only if mg_stat()\r
+      // fails. For more details, see\r
+      // http://code.google.com/p/mongoose/issues/detail?id=79\r
+      memset(&de.file, 0, sizeof(de.file));\r
+      mg_stat(conn, path, &de.file);\r
+\r
+      de.file_name = dp->d_name;\r
+      cb(&de, data);\r
+    }\r
+    (void) closedir(dirp);\r
+  }\r
+  return 1;\r
+}\r
+\r
+struct dir_scan_data {\r
+  struct de *entries;\r
+  int num_entries;\r
+  int arr_size;\r
+};\r
+\r
+static void dir_scan_callback(struct de *de, void *data) {\r
+  struct dir_scan_data *dsd = (struct dir_scan_data *) data;\r
+\r
+  if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {\r
+    dsd->arr_size *= 2;\r
+    dsd->entries = (struct de *) realloc(dsd->entries, dsd->arr_size *\r
+                                         sizeof(dsd->entries[0]));\r
+  }\r
+  if (dsd->entries == NULL) {\r
+    // TODO(lsm): propagate an error to the caller\r
+    dsd->num_entries = 0;\r
+  } else {\r
+    dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);\r
+    dsd->entries[dsd->num_entries].file = de->file;\r
+    dsd->entries[dsd->num_entries].conn = de->conn;\r
+    dsd->num_entries++;\r
+  }\r
+}\r
+\r
+static void handle_directory_request(struct mg_connection *conn,\r
+                                     const char *dir) {\r
+  int i, sort_direction;\r
+  struct dir_scan_data data = { NULL, 0, 128 };\r
+\r
+  if (!scan_directory(conn, dir, &data, dir_scan_callback)) {\r
+    send_http_error(conn, 500, "Cannot open directory",\r
+                    "Error: opendir(%s): %s", dir, strerror(ERRNO));\r
+    return;\r
+  }\r
+\r
+  sort_direction = conn->request_info.query_string != NULL &&\r
+    conn->request_info.query_string[1] == 'd' ? 'a' : 'd';\r
+\r
+  conn->must_close = 1;\r
+  mg_printf(conn, "%s",\r
+            "HTTP/1.1 200 OK\r\n"\r
+            "Connection: close\r\n"\r
+            "Content-Type: text/html; charset=utf-8\r\n\r\n");\r
+\r
+  conn->num_bytes_sent += mg_printf(conn,\r
+      "<html><head><title>Index of %s</title>"\r
+      "<style>th {text-align: left;}</style></head>"\r
+      "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"\r
+      "<tr><th><a href=\"?n%c\">Name</a></th>"\r
+      "<th><a href=\"?d%c\">Modified</a></th>"\r
+      "<th><a href=\"?s%c\">Size</a></th></tr>"\r
+      "<tr><td colspan=\"3\"><hr></td></tr>",\r
+      conn->request_info.uri, conn->request_info.uri,\r
+      sort_direction, sort_direction, sort_direction);\r
+\r
+  // Print first entry - link to a parent directory\r
+  conn->num_bytes_sent += mg_printf(conn,\r
+      "<tr><td><a href=\"%s%s\">%s</a></td>"\r
+      "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",\r
+      conn->request_info.uri, "..", "Parent directory", "-", "-");\r
+\r
+  // Sort and print directory entries\r
+  qsort(data.entries, (size_t) data.num_entries, sizeof(data.entries[0]),\r
+        compare_dir_entries);\r
+  for (i = 0; i < data.num_entries; i++) {\r
+    print_dir_entry(&data.entries[i]);\r
+    free(data.entries[i].file_name);\r
+  }\r
+  free(data.entries);\r
+\r
+  conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");\r
+  conn->status_code = 200;\r
+}\r
+\r
+// Send len bytes from the opened file to the client.\r
+static void send_file_data(struct mg_connection *conn, struct file *filep,\r
+                           int64_t offset, int64_t len) {\r
+  char buf[MG_BUF_LEN];\r
+  int to_read, num_read, num_written;\r
+\r
+  if (len > 0 && filep->membuf != NULL && filep->size > 0) {\r
+    if (len > filep->size - offset) {\r
+      len = filep->size - offset;\r
+    }\r
+    mg_write(conn, filep->membuf + offset, (size_t) len);\r
+  } else if (len > 0 && filep->fp != NULL) {\r
+    fseeko(filep->fp, offset, SEEK_SET);\r
+    while (len > 0) {\r
+      // Calculate how much to read from the file in the buffer\r
+      to_read = sizeof(buf);\r
+      if ((int64_t) to_read > len) {\r
+        to_read = (int) len;\r
+      }\r
+\r
+      // Read from file, exit the loop on error\r
+      if ((num_read = fread(buf, 1, (size_t) to_read, filep->fp)) <= 0) {\r
+        break;\r
+      }\r
+\r
+      // Send read bytes to the client, exit the loop on error\r
+      if ((num_written = mg_write(conn, buf, (size_t) num_read)) != num_read) {\r
+        break;\r
+      }\r
+\r
+      // Both read and were successful, adjust counters\r
+      conn->num_bytes_sent += num_written;\r
+      len -= num_written;\r
+    }\r
+  }\r
+}\r
+\r
+static int parse_range_header(const char *header, int64_t *a, int64_t *b) {\r
+  return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);\r
+}\r
+\r
+static void gmt_time_string(char *buf, size_t buf_len, time_t *t) {\r
+  strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));\r
+}\r
+\r
+static void construct_etag(char *buf, size_t buf_len,\r
+                           const struct file *filep) {\r
+  snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"",\r
+           (unsigned long) filep->modification_time, filep->size);\r
+}\r
+\r
+static void fclose_on_exec(struct file *filep) {\r
+  if (filep != NULL && filep->fp != NULL) {\r
+#ifndef _WIN32\r
+    fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC);\r
+#endif\r
+  }\r
+}\r
+\r
+static void handle_file_request(struct mg_connection *conn, const char *path,\r
+                                struct file *filep) {\r
+  char date[64], lm[64], etag[64], range[64];\r
+  const char *msg = "OK", *hdr;\r
+  time_t curtime = time(NULL);\r
+  int64_t cl, r1, r2;\r
+  struct vec mime_vec;\r
+  int n;\r
+\r
+  get_mime_type(conn->ctx, path, &mime_vec);\r
+  cl = filep->size;\r
+  conn->status_code = 200;\r
+  range[0] = '\0';\r
+\r
+  if (!mg_fopen(conn, path, "rb", filep)) {\r
+    send_http_error(conn, 500, http_500_error,\r
+                    "fopen(%s): %s", path, strerror(ERRNO));\r
+    return;\r
+  }\r
+  fclose_on_exec(filep);\r
+\r
+  // If Range: header specified, act accordingly\r
+  r1 = r2 = 0;\r
+  hdr = mg_get_header(conn, "Range");\r
+  if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 &&\r
+      r1 >= 0 && r2 > 0) {\r
+    conn->status_code = 206;\r
+    cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1: cl - r1;\r
+    mg_snprintf(conn, range, sizeof(range),\r
+                "Content-Range: bytes "\r
+                "%" INT64_FMT "-%"\r
+                INT64_FMT "/%" INT64_FMT "\r\n",\r
+                r1, r1 + cl - 1, filep->size);\r
+    msg = "Partial Content";\r
+  }\r
+\r
+  // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to\r
+  // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3\r
+  gmt_time_string(date, sizeof(date), &curtime);\r
+  gmt_time_string(lm, sizeof(lm), &filep->modification_time);\r
+  construct_etag(etag, sizeof(etag), filep);\r
+\r
+  (void) mg_printf(conn,\r
+      "HTTP/1.1 %d %s\r\n"\r
+      "Date: %s\r\n"\r
+      "Last-Modified: %s\r\n"\r
+      "Etag: %s\r\n"\r
+      "Content-Type: %.*s\r\n"\r
+      "Content-Length: %" INT64_FMT "\r\n"\r
+      "Connection: %s\r\n"\r
+      "Accept-Ranges: bytes\r\n"\r
+      "%s\r\n",\r
+      conn->status_code, msg, date, lm, etag, (int) mime_vec.len,\r
+      mime_vec.ptr, cl, suggest_connection_header(conn), range);\r
+\r
+  if (strcmp(conn->request_info.request_method, "HEAD") != 0) {\r
+    send_file_data(conn, filep, r1, cl);\r
+  }\r
+  mg_fclose(filep);\r
+}\r
+\r
+void mg_send_file(struct mg_connection *conn, const char *path) {\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+  if (mg_stat(conn, path, &file)) {\r
+    handle_file_request(conn, path, &file);\r
+  } else {\r
+    send_http_error(conn, 404, "Not Found", "%s", "File not found");\r
+  }\r
+}\r
+\r
+\r
+// Parse HTTP headers from the given buffer, advance buffer to the point\r
+// where parsing stopped.\r
+static void parse_http_headers(char **buf, struct mg_request_info *ri) {\r
+  int i;\r
+\r
+  for (i = 0; i < (int) ARRAY_SIZE(ri->http_headers); i++) {\r
+    ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);\r
+    ri->http_headers[i].value = skip(buf, "\r\n");\r
+    if (ri->http_headers[i].name[0] == '\0')\r
+      break;\r
+    ri->num_headers = i + 1;\r
+  }\r
+}\r
+\r
+static int is_valid_http_method(const char *method) {\r
+  return !strcmp(method, "GET") || !strcmp(method, "POST") ||\r
+    !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||\r
+    !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||\r
+    !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND");\r
+}\r
+\r
+// Parse HTTP request, fill in mg_request_info structure.\r
+// This function modifies the buffer by NUL-terminating\r
+// HTTP request components, header names and header values.\r
+static int parse_http_message(char *buf, int len, struct mg_request_info *ri) {\r
+  int is_request, request_length = get_request_len(buf, len);\r
+  if (request_length > 0) {\r
+    // Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_port\r
+    ri->remote_user = ri->request_method = ri->uri = ri->http_version = NULL;\r
+    ri->num_headers = 0;\r
+\r
+    buf[request_length - 1] = '\0';\r
+\r
+    // RFC says that all initial whitespaces should be ingored\r
+    while (*buf != '\0' && isspace(* (unsigned char *) buf)) {\r
+      buf++;\r
+    }\r
+    ri->request_method = skip(&buf, " ");\r
+    ri->uri = skip(&buf, " ");\r
+    ri->http_version = skip(&buf, "\r\n");\r
+    if (((is_request = is_valid_http_method(ri->request_method)) &&\r
+         memcmp(ri->http_version, "HTTP/", 5) != 0) ||\r
+        (!is_request && memcmp(ri->request_method, "HTTP/", 5)) != 0) {\r
+      request_length = -1;\r
+    } else {\r
+      if (is_request) {\r
+        ri->http_version += 5;\r
+      }\r
+      parse_http_headers(&buf, ri);\r
+    }\r
+  }\r
+  return request_length;\r
+}\r
+\r
+// Keep reading the input (either opened file descriptor fd, or socket sock,\r
+// or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the\r
+// buffer (which marks the end of HTTP request). Buffer buf may already\r
+// have some data. The length of the data is stored in nread.\r
+// Upon every read operation, increase nread by the number of bytes read.\r
+static int read_request(FILE *fp, struct mg_connection *conn,\r
+                        char *buf, int bufsiz, int *nread) {\r
+  int request_len, n = 0;\r
+\r
+  request_len = get_request_len(buf, *nread);\r
+  while (*nread < bufsiz && request_len == 0 &&\r
+         (n = pull(fp, conn, buf + *nread, bufsiz - *nread)) > 0) {\r
+    *nread += n;\r
+    request_len = get_request_len(buf, *nread);\r
+  }\r
+\r
+  return request_len <= 0 && n <= 0 ? -1 : request_len;\r
+}\r
+\r
+// For given directory path, substitute it to valid index file.\r
+// Return 0 if index file has been found, -1 if not found.\r
+// If the file is found, it's stats is returned in stp.\r
+static int substitute_index_file(struct mg_connection *conn, char *path,\r
+                                 size_t path_len, struct file *filep) {\r
+  const char *list = conn->ctx->config[INDEX_FILES];\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+  struct vec filename_vec;\r
+  size_t n = strlen(path);\r
+  int found = 0;\r
+\r
+  // The 'path' given to us points to the directory. Remove all trailing\r
+  // directory separator characters from the end of the path, and\r
+  // then append single directory separator character.\r
+  while (n > 0 && path[n - 1] == '/') {\r
+    n--;\r
+  }\r
+  path[n] = '/';\r
+\r
+  // Traverse index files list. For each entry, append it to the given\r
+  // path and see if the file exists. If it exists, break the loop\r
+  while ((list = next_option(list, &filename_vec, NULL)) != NULL) {\r
+\r
+    // Ignore too long entries that may overflow path buffer\r
+    if (filename_vec.len > path_len - (n + 2))\r
+      continue;\r
+\r
+    // Prepare full path to the index file\r
+    mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);\r
+\r
+    // Does it exist?\r
+    if (mg_stat(conn, path, &file)) {\r
+      // Yes it does, break the loop\r
+      *filep = file;\r
+      found = 1;\r
+      break;\r
+    }\r
+  }\r
+\r
+  // If no index file exists, restore directory path\r
+  if (!found) {\r
+    path[n] = '\0';\r
+  }\r
+\r
+  return found;\r
+}\r
+\r
+// Return True if we should reply 304 Not Modified.\r
+static int is_not_modified(const struct mg_connection *conn,\r
+                           const struct file *filep) {\r
+  char etag[64];\r
+  const char *ims = mg_get_header(conn, "If-Modified-Since");\r
+  const char *inm = mg_get_header(conn, "If-None-Match");\r
+  construct_etag(etag, sizeof(etag), filep);\r
+  return (inm != NULL && !mg_strcasecmp(etag, inm)) ||\r
+    (ims != NULL && filep->modification_time <= parse_date_string(ims));\r
+}\r
+\r
+static int forward_body_data(struct mg_connection *conn, FILE *fp,\r
+                             SOCKET sock, SSL *ssl) {\r
+  const char *expect, *body;\r
+  char buf[MG_BUF_LEN];\r
+  int to_read, nread, buffered_len, success = 0;\r
+\r
+  expect = mg_get_header(conn, "Expect");\r
+  assert(fp != NULL);\r
+\r
+  if (conn->content_len == -1) {\r
+    send_http_error(conn, 411, "Length Required", "%s", "");\r
+  } else if (expect != NULL && mg_strcasecmp(expect, "100-continue")) {\r
+    send_http_error(conn, 417, "Expectation Failed", "%s", "");\r
+  } else {\r
+    if (expect != NULL) {\r
+      (void) mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");\r
+    }\r
+\r
+    body = conn->buf + conn->request_len + conn->consumed_content;\r
+    buffered_len = &conn->buf[conn->data_len] - body;\r
+    assert(buffered_len >= 0);\r
+    assert(conn->consumed_content == 0);\r
+\r
+    if (buffered_len > 0) {\r
+      if ((int64_t) buffered_len > conn->content_len) {\r
+        buffered_len = (int) conn->content_len;\r
+      }\r
+      push(fp, sock, ssl, body, (int64_t) buffered_len);\r
+      conn->consumed_content += buffered_len;\r
+    }\r
+\r
+    nread = 0;\r
+    while (conn->consumed_content < conn->content_len) {\r
+      to_read = sizeof(buf);\r
+      if ((int64_t) to_read > conn->content_len - conn->consumed_content) {\r
+        to_read = (int) (conn->content_len - conn->consumed_content);\r
+      }\r
+      nread = pull(NULL, conn, buf, to_read);\r
+      if (nread <= 0 || push(fp, sock, ssl, buf, nread) != nread) {\r
+        break;\r
+      }\r
+      conn->consumed_content += nread;\r
+    }\r
+\r
+    if (conn->consumed_content == conn->content_len) {\r
+      success = nread >= 0;\r
+    }\r
+\r
+    // Each error code path in this function must send an error\r
+    if (!success) {\r
+      send_http_error(conn, 577, http_500_error, "%s", "");\r
+    }\r
+  }\r
+\r
+  return success;\r
+}\r
+\r
+#if !defined(NO_CGI)\r
+// This structure helps to create an environment for the spawned CGI program.\r
+// Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,\r
+// last element must be NULL.\r
+// However, on Windows there is a requirement that all these VARIABLE=VALUE\0\r
+// strings must reside in a contiguous buffer. The end of the buffer is\r
+// marked by two '\0' characters.\r
+// We satisfy both worlds: we create an envp array (which is vars), all\r
+// entries are actually pointers inside buf.\r
+struct cgi_env_block {\r
+  struct mg_connection *conn;\r
+  char buf[CGI_ENVIRONMENT_SIZE]; // Environment buffer\r
+  int len; // Space taken\r
+  char *vars[MAX_CGI_ENVIR_VARS]; // char **envp\r
+  int nvars; // Number of variables\r
+};\r
+\r
+static char *addenv(struct cgi_env_block *block,\r
+                    PRINTF_FORMAT_STRING(const char *fmt), ...)\r
+  PRINTF_ARGS(2, 3);\r
+\r
+// Append VARIABLE=VALUE\0 string to the buffer, and add a respective\r
+// pointer into the vars array.\r
+static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {\r
+  int n, space;\r
+  char *added;\r
+  va_list ap;\r
+\r
+  // Calculate how much space is left in the buffer\r
+  space = sizeof(block->buf) - block->len - 2;\r
+  assert(space >= 0);\r
+\r
+  // Make a pointer to the free space int the buffer\r
+  added = block->buf + block->len;\r
+\r
+  // Copy VARIABLE=VALUE\0 string into the free space\r
+  va_start(ap, fmt);\r
+  n = mg_vsnprintf(block->conn, added, (size_t) space, fmt, ap);\r
+  va_end(ap);\r
+\r
+  // Make sure we do not overflow buffer and the envp array\r
+  if (n > 0 && n + 1 < space &&\r
+      block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {\r
+    // Append a pointer to the added string into the envp array\r
+    block->vars[block->nvars++] = added;\r
+    // Bump up used length counter. Include \0 terminator\r
+    block->len += n + 1;\r
+  } else {\r
+    cry(block->conn, "%s: CGI env buffer truncated for [%s]", __func__, fmt);\r
+  }\r
+\r
+  return added;\r
+}\r
+\r
+static void prepare_cgi_environment(struct mg_connection *conn,\r
+                                    const char *prog,\r
+                                    struct cgi_env_block *blk) {\r
+  const char *s, *slash;\r
+  struct vec var_vec;\r
+  char *p, src_addr[20];\r
+  int  i;\r
+\r
+  blk->len = blk->nvars = 0;\r
+  blk->conn = conn;\r
+  sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);\r
+\r
+  addenv(blk, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);\r
+  addenv(blk, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);\r
+  addenv(blk, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);\r
+\r
+  // Prepare the environment block\r
+  addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");\r
+  addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");\r
+  addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP\r
+\r
+  // TODO(lsm): fix this for IPv6 case\r
+  addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));\r
+\r
+  addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method);\r
+  addenv(blk, "REMOTE_ADDR=%s", src_addr);\r
+  addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port);\r
+  addenv(blk, "REQUEST_URI=%s", conn->request_info.uri);\r
+\r
+  // SCRIPT_NAME\r
+  assert(conn->request_info.uri[0] == '/');\r
+  slash = strrchr(conn->request_info.uri, '/');\r
+  if ((s = strrchr(prog, '/')) == NULL)\r
+    s = prog;\r
+  addenv(blk, "SCRIPT_NAME=%.*s%s", (int) (slash - conn->request_info.uri),\r
+         conn->request_info.uri, s);\r
+\r
+  addenv(blk, "SCRIPT_FILENAME=%s", prog);\r
+  addenv(blk, "PATH_TRANSLATED=%s", prog);\r
+  addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");\r
+\r
+  if ((s = mg_get_header(conn, "Content-Type")) != NULL)\r
+    addenv(blk, "CONTENT_TYPE=%s", s);\r
+\r
+  if (conn->request_info.query_string != NULL)\r
+    addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string);\r
+\r
+  if ((s = mg_get_header(conn, "Content-Length")) != NULL)\r
+    addenv(blk, "CONTENT_LENGTH=%s", s);\r
+\r
+  if ((s = getenv("PATH")) != NULL)\r
+    addenv(blk, "PATH=%s", s);\r
+\r
+  if (conn->path_info != NULL) {\r
+    addenv(blk, "PATH_INFO=%s", conn->path_info);\r
+  }\r
+\r
+#if defined(_WIN32)\r
+  if ((s = getenv("COMSPEC")) != NULL) {\r
+    addenv(blk, "COMSPEC=%s", s);\r
+  }\r
+  if ((s = getenv("SYSTEMROOT")) != NULL) {\r
+    addenv(blk, "SYSTEMROOT=%s", s);\r
+  }\r
+  if ((s = getenv("SystemDrive")) != NULL) {\r
+    addenv(blk, "SystemDrive=%s", s);\r
+  }\r
+#else\r
+  if ((s = getenv("LD_LIBRARY_PATH")) != NULL)\r
+    addenv(blk, "LD_LIBRARY_PATH=%s", s);\r
+#endif // _WIN32\r
+\r
+  if ((s = getenv("PERLLIB")) != NULL)\r
+    addenv(blk, "PERLLIB=%s", s);\r
+\r
+  if (conn->request_info.remote_user != NULL) {\r
+    addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user);\r
+    addenv(blk, "%s", "AUTH_TYPE=Digest");\r
+  }\r
+\r
+  // Add all headers as HTTP_* variables\r
+  for (i = 0; i < conn->request_info.num_headers; i++) {\r
+    p = addenv(blk, "HTTP_%s=%s",\r
+        conn->request_info.http_headers[i].name,\r
+        conn->request_info.http_headers[i].value);\r
+\r
+    // Convert variable name into uppercase, and change - to _\r
+    for (; *p != '=' && *p != '\0'; p++) {\r
+      if (*p == '-')\r
+        *p = '_';\r
+      *p = (char) toupper(* (unsigned char *) p);\r
+    }\r
+  }\r
+\r
+  // Add user-specified variables\r
+  s = conn->ctx->config[CGI_ENVIRONMENT];\r
+  while ((s = next_option(s, &var_vec, NULL)) != NULL) {\r
+    addenv(blk, "%.*s", (int) var_vec.len, var_vec.ptr);\r
+  }\r
+\r
+  blk->vars[blk->nvars++] = NULL;\r
+  blk->buf[blk->len++] = '\0';\r
+\r
+  assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));\r
+  assert(blk->len > 0);\r
+  assert(blk->len < (int) sizeof(blk->buf));\r
+}\r
+\r
+static void handle_cgi_request(struct mg_connection *conn, const char *prog) {\r
+  int headers_len, data_len, i, fd_stdin[2], fd_stdout[2];\r
+  const char *status, *status_text;\r
+  char buf[16384], *pbuf, dir[PATH_MAX], *p;\r
+  struct mg_request_info ri;\r
+  struct cgi_env_block blk;\r
+  FILE *in, *out;\r
+  struct file fout = STRUCT_FILE_INITIALIZER;\r
+  pid_t pid;\r
+\r
+  prepare_cgi_environment(conn, prog, &blk);\r
+\r
+  // CGI must be executed in its own directory. 'dir' must point to the\r
+  // directory containing executable program, 'p' must point to the\r
+  // executable program name relative to 'dir'.\r
+  (void) mg_snprintf(conn, dir, sizeof(dir), "%s", prog);\r
+  if ((p = strrchr(dir, '/')) != NULL) {\r
+    *p++ = '\0';\r
+  } else {\r
+    dir[0] = '.', dir[1] = '\0';\r
+    p = (char *) prog;\r
+  }\r
+\r
+  pid = (pid_t) -1;\r
+  fd_stdin[0] = fd_stdin[1] = fd_stdout[0] = fd_stdout[1] = -1;\r
+  in = out = NULL;\r
+\r
+  if (pipe(fd_stdin) != 0 || pipe(fd_stdout) != 0) {\r
+    send_http_error(conn, 500, http_500_error,\r
+        "Cannot create CGI pipe: %s", strerror(ERRNO));\r
+    goto done;\r
+  }\r
+\r
+  pid = spawn_process(conn, p, blk.buf, blk.vars, fd_stdin[0], fd_stdout[1],\r
+                      dir);\r
+  // spawn_process() must close those!\r
+  // If we don't mark them as closed, close() attempt before\r
+  // return from this function throws an exception on Windows.\r
+  // Windows does not like when closed descriptor is closed again.\r
+  fd_stdin[0] = fd_stdout[1] = -1;\r
+\r
+  if (pid == (pid_t) -1) {\r
+    send_http_error(conn, 500, http_500_error,\r
+        "Cannot spawn CGI process [%s]: %s", prog, strerror(ERRNO));\r
+    goto done;\r
+  }\r
+\r
+  if ((in = fdopen(fd_stdin[1], "wb")) == NULL ||\r
+      (out = fdopen(fd_stdout[0], "rb")) == NULL) {\r
+    send_http_error(conn, 500, http_500_error,\r
+        "fopen: %s", strerror(ERRNO));\r
+    goto done;\r
+  }\r
+\r
+  setbuf(in, NULL);\r
+  setbuf(out, NULL);\r
+  fout.fp = out;\r
+\r
+  // Send POST data to the CGI process if needed\r
+  if (!strcmp(conn->request_info.request_method, "POST") &&\r
+      !forward_body_data(conn, in, INVALID_SOCKET, NULL)) {\r
+    goto done;\r
+  }\r
+\r
+  // Close so child gets an EOF.\r
+  fclose(in);\r
+  in = NULL;\r
+  fd_stdin[1] = -1;\r
+\r
+  // Now read CGI reply into a buffer. We need to set correct\r
+  // status code, thus we need to see all HTTP headers first.\r
+  // Do not send anything back to client, until we buffer in all\r
+  // HTTP headers.\r
+  data_len = 0;\r
+  headers_len = read_request(out, conn, buf, sizeof(buf), &data_len);\r
+  if (headers_len <= 0) {\r
+    send_http_error(conn, 500, http_500_error,\r
+                    "CGI program sent malformed or too big (>%u bytes) "\r
+                    "HTTP headers: [%.*s]",\r
+                    (unsigned) sizeof(buf), data_len, buf);\r
+    goto done;\r
+  }\r
+  pbuf = buf;\r
+  buf[headers_len - 1] = '\0';\r
+  parse_http_headers(&pbuf, &ri);\r
+\r
+  // Make up and send the status line\r
+  status_text = "OK";\r
+  if ((status = get_header(&ri, "Status")) != NULL) {\r
+    conn->status_code = atoi(status);\r
+    status_text = status;\r
+    while (isdigit(* (unsigned char *) status_text) || *status_text == ' ') {\r
+      status_text++;\r
+    }\r
+  } else if (get_header(&ri, "Location") != NULL) {\r
+    conn->status_code = 302;\r
+  } else {\r
+    conn->status_code = 200;\r
+  }\r
+  if (get_header(&ri, "Connection") != NULL &&\r
+      !mg_strcasecmp(get_header(&ri, "Connection"), "keep-alive")) {\r
+    conn->must_close = 1;\r
+  }\r
+  (void) mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code,\r
+                   status_text);\r
+\r
+  // Send headers\r
+  for (i = 0; i < ri.num_headers; i++) {\r
+    mg_printf(conn, "%s: %s\r\n",\r
+              ri.http_headers[i].name, ri.http_headers[i].value);\r
+  }\r
+  mg_write(conn, "\r\n", 2);\r
+\r
+  // Send chunk of data that may have been read after the headers\r
+  conn->num_bytes_sent += mg_write(conn, buf + headers_len,\r
+                                   (size_t)(data_len - headers_len));\r
+\r
+  // Read the rest of CGI output and send to the client\r
+  send_file_data(conn, &fout, 0, INT64_MAX);\r
+\r
+done:\r
+  if (pid != (pid_t) -1) {\r
+    kill(pid, SIGKILL);\r
+  }\r
+  if (fd_stdin[0] != -1) {\r
+    close(fd_stdin[0]);\r
+  }\r
+  if (fd_stdout[1] != -1) {\r
+    close(fd_stdout[1]);\r
+  }\r
+\r
+  if (in != NULL) {\r
+    fclose(in);\r
+  } else if (fd_stdin[1] != -1) {\r
+    close(fd_stdin[1]);\r
+  }\r
+\r
+  if (out != NULL) {\r
+    fclose(out);\r
+  } else if (fd_stdout[0] != -1) {\r
+    close(fd_stdout[0]);\r
+  }\r
+}\r
+#endif // !NO_CGI\r
+\r
+// For a given PUT path, create all intermediate subdirectories\r
+// for given path. Return 0 if the path itself is a directory,\r
+// or -1 on error, 1 if OK.\r
+static int put_dir(struct mg_connection *conn, const char *path) {\r
+  char buf[PATH_MAX];\r
+  const char *s, *p;\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+  int len, res = 1;\r
+\r
+  for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {\r
+    len = p - path;\r
+    if (len >= (int) sizeof(buf)) {\r
+      res = -1;\r
+      break;\r
+    }\r
+    memcpy(buf, path, len);\r
+    buf[len] = '\0';\r
+\r
+    // Try to create intermediate directory\r
+    DEBUG_TRACE(("mkdir(%s)", buf));\r
+    if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {\r
+      res = -1;\r
+      break;\r
+    }\r
+\r
+    // Is path itself a directory?\r
+    if (p[1] == '\0') {\r
+      res = 0;\r
+    }\r
+  }\r
+\r
+  return res;\r
+}\r
+\r
+static void put_file(struct mg_connection *conn, const char *path) {\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+  const char *range;\r
+  int64_t r1, r2;\r
+  int rc;\r
+\r
+  conn->status_code = mg_stat(conn, path, &file) ? 200 : 201;\r
+\r
+  if ((rc = put_dir(conn, path)) == 0) {\r
+    mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", conn->status_code);\r
+  } else if (rc == -1) {\r
+    send_http_error(conn, 500, http_500_error,\r
+                    "put_dir(%s): %s", path, strerror(ERRNO));\r
+  } else if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {\r
+    mg_fclose(&file);\r
+    send_http_error(conn, 500, http_500_error,\r
+                    "fopen(%s): %s", path, strerror(ERRNO));\r
+  } else {\r
+    fclose_on_exec(&file);\r
+    range = mg_get_header(conn, "Content-Range");\r
+    r1 = r2 = 0;\r
+    if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {\r
+      conn->status_code = 206;\r
+      fseeko(file.fp, r1, SEEK_SET);\r
+    }\r
+    if (forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {\r
+      mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", conn->status_code);\r
+    }\r
+    mg_fclose(&file);\r
+  }\r
+}\r
+\r
+static void send_ssi_file(struct mg_connection *, const char *,\r
+                          struct file *, int);\r
+\r
+static void do_ssi_include(struct mg_connection *conn, const char *ssi,\r
+                           char *tag, int include_level) {\r
+  char file_name[MG_BUF_LEN], path[PATH_MAX], *p;\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+\r
+  // sscanf() is safe here, since send_ssi_file() also uses buffer\r
+  // of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.\r
+  if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {\r
+    // File name is relative to the webserver root\r
+    (void) mg_snprintf(conn, path, sizeof(path), "%s%c%s",\r
+        conn->ctx->config[DOCUMENT_ROOT], '/', file_name);\r
+  } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1) {\r
+    // File name is relative to the webserver working directory\r
+    // or it is absolute system path\r
+    (void) mg_snprintf(conn, path, sizeof(path), "%s", file_name);\r
+  } else if (sscanf(tag, " \"%[^\"]\"", file_name) == 1) {\r
+    // File name is relative to the currect document\r
+    (void) mg_snprintf(conn, path, sizeof(path), "%s", ssi);\r
+    if ((p = strrchr(path, '/')) != NULL) {\r
+      p[1] = '\0';\r
+    }\r
+    (void) mg_snprintf(conn, path + strlen(path),\r
+        sizeof(path) - strlen(path), "%s", file_name);\r
+  } else {\r
+    cry(conn, "Bad SSI #include: [%s]", tag);\r
+    return;\r
+  }\r
+\r
+  if (!mg_fopen(conn, path, "rb", &file)) {\r
+    cry(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",\r
+        tag, path, strerror(ERRNO));\r
+  } else {\r
+    fclose_on_exec(&file);\r
+    if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],\r
+                     strlen(conn->ctx->config[SSI_EXTENSIONS]), path) > 0) {\r
+      send_ssi_file(conn, path, &file, include_level + 1);\r
+    } else {\r
+      send_file_data(conn, &file, 0, INT64_MAX);\r
+    }\r
+    mg_fclose(&file);\r
+  }\r
+}\r
+\r
+#if !defined(NO_POPEN)\r
+static void do_ssi_exec(struct mg_connection *conn, char *tag) {\r
+  char cmd[MG_BUF_LEN];\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+\r
+  if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {\r
+    cry(conn, "Bad SSI #exec: [%s]", tag);\r
+  } else if ((file.fp = popen(cmd, "r")) == NULL) {\r
+    cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));\r
+  } else {\r
+    send_file_data(conn, &file, 0, INT64_MAX);\r
+    pclose(file.fp);\r
+  }\r
+}\r
+#endif // !NO_POPEN\r
+\r
+static int mg_fgetc(struct file *filep, int offset) {\r
+  if (filep->membuf != NULL && offset >=0 && offset < filep->size) {\r
+    return ((unsigned char *) filep->membuf)[offset];\r
+  } else if (filep->fp != NULL) {\r
+    return fgetc(filep->fp);\r
+  } else {\r
+    return EOF;\r
+  }\r
+}\r
+\r
+static void send_ssi_file(struct mg_connection *conn, const char *path,\r
+                          struct file *filep, int include_level) {\r
+  char buf[MG_BUF_LEN];\r
+  int ch, offset, len, in_ssi_tag;\r
+\r
+  if (include_level > 10) {\r
+    cry(conn, "SSI #include level is too deep (%s)", path);\r
+    return;\r
+  }\r
+\r
+  in_ssi_tag = len = offset = 0;\r
+  while ((ch = mg_fgetc(filep, offset)) != EOF) {\r
+    if (in_ssi_tag && ch == '>') {\r
+      in_ssi_tag = 0;\r
+      buf[len++] = (char) ch;\r
+      buf[len] = '\0';\r
+      assert(len <= (int) sizeof(buf));\r
+      if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {\r
+        // Not an SSI tag, pass it\r
+        (void) mg_write(conn, buf, (size_t) len);\r
+      } else {\r
+        if (!memcmp(buf + 5, "include", 7)) {\r
+          do_ssi_include(conn, path, buf + 12, include_level);\r
+#if !defined(NO_POPEN)\r
+        } else if (!memcmp(buf + 5, "exec", 4)) {\r
+          do_ssi_exec(conn, buf + 9);\r
+#endif // !NO_POPEN\r
+        } else {\r
+          cry(conn, "%s: unknown SSI " "command: \"%s\"", path, buf);\r
+        }\r
+      }\r
+      len = 0;\r
+    } else if (in_ssi_tag) {\r
+      if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {\r
+        // Not an SSI tag\r
+        in_ssi_tag = 0;\r
+      } else if (len == (int) sizeof(buf) - 2) {\r
+        cry(conn, "%s: SSI tag is too large", path);\r
+        len = 0;\r
+      }\r
+      buf[len++] = ch & 0xff;\r
+    } else if (ch == '<') {\r
+      in_ssi_tag = 1;\r
+      if (len > 0) {\r
+        mg_write(conn, buf, (size_t) len);\r
+      }\r
+      len = 0;\r
+      buf[len++] = ch & 0xff;\r
+    } else {\r
+      buf[len++] = ch & 0xff;\r
+      if (len == (int) sizeof(buf)) {\r
+        mg_write(conn, buf, (size_t) len);\r
+        len = 0;\r
+      }\r
+    }\r
+  }\r
+\r
+  // Send the rest of buffered data\r
+  if (len > 0) {\r
+    mg_write(conn, buf, (size_t) len);\r
+  }\r
+}\r
+\r
+static void handle_ssi_file_request(struct mg_connection *conn,\r
+                                    const char *path) {\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+\r
+  if (!mg_fopen(conn, path, "rb", &file)) {\r
+    send_http_error(conn, 500, http_500_error, "fopen(%s): %s", path,\r
+                    strerror(ERRNO));\r
+  } else {\r
+    conn->must_close = 1;\r
+    fclose_on_exec(&file);\r
+    mg_printf(conn, "HTTP/1.1 200 OK\r\n"\r
+              "Content-Type: text/html\r\nConnection: %s\r\n\r\n",\r
+              suggest_connection_header(conn));\r
+    send_ssi_file(conn, path, &file, 0);\r
+    mg_fclose(&file);\r
+  }\r
+}\r
+\r
+static void send_options(struct mg_connection *conn) {\r
+  conn->status_code = 200;\r
+\r
+  mg_printf(conn, "%s", "HTTP/1.1 200 OK\r\n"\r
+            "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS\r\n"\r
+            "DAV: 1\r\n\r\n");\r
+}\r
+\r
+// Writes PROPFIND properties for a collection element\r
+static void print_props(struct mg_connection *conn, const char* uri,\r
+                        struct file *filep) {\r
+  char mtime[64];\r
+  gmt_time_string(mtime, sizeof(mtime), &filep->modification_time);\r
+  conn->num_bytes_sent += mg_printf(conn,\r
+      "<d:response>"\r
+       "<d:href>%s</d:href>"\r
+       "<d:propstat>"\r
+        "<d:prop>"\r
+         "<d:resourcetype>%s</d:resourcetype>"\r
+         "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"\r
+         "<d:getlastmodified>%s</d:getlastmodified>"\r
+        "</d:prop>"\r
+        "<d:status>HTTP/1.1 200 OK</d:status>"\r
+       "</d:propstat>"\r
+      "</d:response>\n",\r
+      uri,\r
+      filep->is_directory ? "<d:collection/>" : "",\r
+      filep->size,\r
+      mtime);\r
+}\r
+\r
+static void print_dav_dir_entry(struct de *de, void *data) {\r
+  char href[PATH_MAX];\r
+  struct mg_connection *conn = (struct mg_connection *) data;\r
+  mg_snprintf(conn, href, sizeof(href), "%s%s",\r
+              conn->request_info.uri, de->file_name);\r
+  print_props(conn, href, &de->file);\r
+}\r
+\r
+static void handle_propfind(struct mg_connection *conn, const char *path,\r
+                            struct file *filep) {\r
+  const char *depth = mg_get_header(conn, "Depth");\r
+\r
+  conn->must_close = 1;\r
+  conn->status_code = 207;\r
+  mg_printf(conn, "HTTP/1.1 207 Multi-Status\r\n"\r
+            "Connection: close\r\n"\r
+            "Content-Type: text/xml; charset=utf-8\r\n\r\n");\r
+\r
+  conn->num_bytes_sent += mg_printf(conn,\r
+      "<?xml version=\"1.0\" encoding=\"utf-8\"?>"\r
+      "<d:multistatus xmlns:d='DAV:'>\n");\r
+\r
+  // Print properties for the requested resource itself\r
+  print_props(conn, conn->request_info.uri, filep);\r
+\r
+  // If it is a directory, print directory entries too if Depth is not 0\r
+  if (filep->is_directory &&\r
+      !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") &&\r
+      (depth == NULL || strcmp(depth, "0") != 0)) {\r
+    scan_directory(conn, path, conn, &print_dav_dir_entry);\r
+  }\r
+\r
+  conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");\r
+}\r
+\r
+#if defined(USE_WEBSOCKET)\r
+\r
+// START OF SHA-1 code\r
+// Copyright(c) By Steve Reid <steve@edmweb.com>\r
+#define SHA1HANDSOFF\r
+#if defined(__sun)\r
+#include "solarisfixes.h"\r
+#endif\r
+\r
+union char64long16 { unsigned char c[64]; uint32_t l[16]; };\r
+\r
+#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))\r
+\r
+static uint32_t blk0(union char64long16 *block, int i) {\r
+  // Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN\r
+  if (!is_big_endian()) {\r
+    block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |\r
+      (rol(block->l[i], 8) & 0x00FF00FF);\r
+  }\r
+  return block->l[i];\r
+}\r
+\r
+#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \\r
+    ^block->l[(i+2)&15]^block->l[i&15],1))\r
+#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30);\r
+#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);\r
+#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);\r
+#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);\r
+#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);\r
+\r
+typedef struct {\r
+    uint32_t state[5];\r
+    uint32_t count[2];\r
+    unsigned char buffer[64];\r
+} SHA1_CTX;\r
+\r
+static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) {\r
+  uint32_t a, b, c, d, e;\r
+  union char64long16 block[1];\r
+\r
+  memcpy(block, buffer, 64);\r
+  a = state[0];\r
+  b = state[1];\r
+  c = state[2];\r
+  d = state[3];\r
+  e = state[4];\r
+  R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3);\r
+  R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7);\r
+  R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11);\r
+  R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15);\r
+  R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);\r
+  R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);\r
+  R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);\r
+  R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);\r
+  R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);\r
+  R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);\r
+  R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);\r
+  R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);\r
+  R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);\r
+  R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);\r
+  R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);\r
+  R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);\r
+  R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);\r
+  R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);\r
+  R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);\r
+  R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);\r
+  state[0] += a;\r
+  state[1] += b;\r
+  state[2] += c;\r
+  state[3] += d;\r
+  state[4] += e;\r
+  a = b = c = d = e = 0;\r
+  memset(block, '\0', sizeof(block));\r
+}\r
+\r
+static void SHA1Init(SHA1_CTX* context) {\r
+  context->state[0] = 0x67452301;\r
+  context->state[1] = 0xEFCDAB89;\r
+  context->state[2] = 0x98BADCFE;\r
+  context->state[3] = 0x10325476;\r
+  context->state[4] = 0xC3D2E1F0;\r
+  context->count[0] = context->count[1] = 0;\r
+}\r
+\r
+static void SHA1Update(SHA1_CTX* context, const unsigned char* data,\r
+                       uint32_t len) {\r
+  uint32_t i, j;\r
+\r
+  j = context->count[0];\r
+  if ((context->count[0] += len << 3) < j)\r
+    context->count[1]++;\r
+  context->count[1] += (len>>29);\r
+  j = (j >> 3) & 63;\r
+  if ((j + len) > 63) {\r
+    memcpy(&context->buffer[j], data, (i = 64-j));\r
+    SHA1Transform(context->state, context->buffer);\r
+    for ( ; i + 63 < len; i += 64) {\r
+      SHA1Transform(context->state, &data[i]);\r
+    }\r
+    j = 0;\r
+  }\r
+  else i = 0;\r
+  memcpy(&context->buffer[j], &data[i], len - i);\r
+}\r
+\r
+static void SHA1Final(unsigned char digest[20], SHA1_CTX* context) {\r
+  unsigned i;\r
+  unsigned char finalcount[8], c;\r
+\r
+  for (i = 0; i < 8; i++) {\r
+    finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]\r
+                                     >> ((3-(i & 3)) * 8) ) & 255);\r
+  }\r
+  c = 0200;\r
+  SHA1Update(context, &c, 1);\r
+  while ((context->count[0] & 504) != 448) {\r
+    c = 0000;\r
+    SHA1Update(context, &c, 1);\r
+  }\r
+  SHA1Update(context, finalcount, 8);\r
+  for (i = 0; i < 20; i++) {\r
+    digest[i] = (unsigned char)\r
+      ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);\r
+  }\r
+  memset(context, '\0', sizeof(*context));\r
+  memset(&finalcount, '\0', sizeof(finalcount));\r
+}\r
+// END OF SHA1 CODE\r
+\r
+static void base64_encode(const unsigned char *src, int src_len, char *dst) {\r
+  static const char *b64 =\r
+    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";\r
+  int i, j, a, b, c;\r
+\r
+  for (i = j = 0; i < src_len; i += 3) {\r
+    a = src[i];\r
+    b = i + 1 >= src_len ? 0 : src[i + 1];\r
+    c = i + 2 >= src_len ? 0 : src[i + 2];\r
+\r
+    dst[j++] = b64[a >> 2];\r
+    dst[j++] = b64[((a & 3) << 4) | (b >> 4)];\r
+    if (i + 1 < src_len) {\r
+      dst[j++] = b64[(b & 15) << 2 | (c >> 6)];\r
+    }\r
+    if (i + 2 < src_len) {\r
+      dst[j++] = b64[c & 63];\r
+    }\r
+  }\r
+  while (j % 4 != 0) {\r
+    dst[j++] = '=';\r
+  }\r
+  dst[j++] = '\0';\r
+}\r
+\r
+static void send_websocket_handshake(struct mg_connection *conn) {\r
+  static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";\r
+  char buf[100], sha[20], b64_sha[sizeof(sha) * 2];\r
+  SHA1_CTX sha_ctx;\r
+\r
+  mg_snprintf(conn, buf, sizeof(buf), "%s%s",\r
+              mg_get_header(conn, "Sec-WebSocket-Key"), magic);\r
+  SHA1Init(&sha_ctx);\r
+  SHA1Update(&sha_ctx, (unsigned char *) buf, strlen(buf));\r
+  SHA1Final((unsigned char *) sha, &sha_ctx);\r
+  base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);\r
+  mg_printf(conn, "%s%s%s",\r
+            "HTTP/1.1 101 Switching Protocols\r\n"\r
+            "Upgrade: websocket\r\n"\r
+            "Connection: Upgrade\r\n"\r
+            "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n");\r
+}\r
+\r
+static void read_websocket(struct mg_connection *conn) {\r
+  unsigned char *buf = (unsigned char *) conn->buf + conn->request_len;\r
+  int n, len, mask_len, body_len, discard_len;\r
+\r
+  for (;;) {\r
+    if ((body_len = conn->data_len - conn->request_len) >= 2) {\r
+      len = buf[1] & 127;\r
+      mask_len = buf[1] & 128 ? 4 : 0;\r
+      if (len < 126) {\r
+        conn->content_len = 2 + mask_len + len;\r
+      } else if (len == 126 && body_len >= 4) {\r
+        conn->content_len = 4 + mask_len + ((((int) buf[2]) << 8) + buf[3]);\r
+      } else if (body_len >= 10) {\r
+        conn->content_len = 10 + mask_len +\r
+          (((uint64_t) htonl(* (uint32_t *) &buf[2])) << 32) +\r
+          htonl(* (uint32_t *) &buf[6]);\r
+      }\r
+    }\r
+\r
+    if (conn->content_len > 0) {\r
+      if (conn->ctx->callbacks.websocket_data != NULL &&\r
+          conn->ctx->callbacks.websocket_data(conn) == 0) {\r
+        break;  // Callback signalled to exit\r
+      }\r
+      discard_len = conn->content_len > body_len ?\r
+          body_len : (int) conn->content_len;\r
+      memmove(buf, buf + discard_len, conn->data_len - discard_len);\r
+      conn->data_len -= discard_len;\r
+      conn->content_len = conn->consumed_content = 0;\r
+    } else {\r
+      n = pull(NULL, conn, conn->buf + conn->data_len,\r
+               conn->buf_size - conn->data_len);\r
+      if (n <= 0) {\r
+        break;\r
+      }\r
+      conn->data_len += n;\r
+    }\r
+  }\r
+}\r
+\r
+static void handle_websocket_request(struct mg_connection *conn) {\r
+  if (strcmp(mg_get_header(conn, "Sec-WebSocket-Version"), "13") != 0) {\r
+    send_http_error(conn, 426, "Upgrade Required", "%s", "Upgrade Required");\r
+  } else if (conn->ctx->callbacks.websocket_connect != NULL &&\r
+             conn->ctx->callbacks.websocket_connect(conn) != 0) {\r
+    // Callback has returned non-zero, do not proceed with handshake\r
+  } else {\r
+    send_websocket_handshake(conn);\r
+    if (conn->ctx->callbacks.websocket_ready != NULL) {\r
+      conn->ctx->callbacks.websocket_ready(conn);\r
+    }\r
+    read_websocket(conn);\r
+  }\r
+}\r
+\r
+static int is_websocket_request(const struct mg_connection *conn) {\r
+  const char *host, *upgrade, *connection, *version, *key;\r
+\r
+  host = mg_get_header(conn, "Host");\r
+  upgrade = mg_get_header(conn, "Upgrade");\r
+  connection = mg_get_header(conn, "Connection");\r
+  key = mg_get_header(conn, "Sec-WebSocket-Key");\r
+  version = mg_get_header(conn, "Sec-WebSocket-Version");\r
+\r
+  return host != NULL && upgrade != NULL && connection != NULL &&\r
+    key != NULL && version != NULL &&\r
+    strstr(upgrade, "websocket") != NULL &&\r
+    strstr(connection, "Upgrade") != NULL;\r
+}\r
+#endif // !USE_WEBSOCKET\r
+\r
+static int isbyte(int n) {\r
+  return n >= 0 && n <= 255;\r
+}\r
+\r
+static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {\r
+  int n, a, b, c, d, slash = 32, len = 0;\r
+\r
+  if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||\r
+      sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&\r
+      isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&\r
+      slash >= 0 && slash < 33) {\r
+    len = n;\r
+    *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;\r
+    *mask = slash ? 0xffffffffU << (32 - slash) : 0;\r
+  }\r
+\r
+  return len;\r
+}\r
+\r
+static int set_throttle(const char *spec, uint32_t remote_ip, const char *uri) {\r
+  int throttle = 0;\r
+  struct vec vec, val;\r
+  uint32_t net, mask;\r
+  char mult;\r
+  double v;\r
+\r
+  while ((spec = next_option(spec, &vec, &val)) != NULL) {\r
+    mult = ',';\r
+    if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0 ||\r
+        (lowercase(&mult) != 'k' && lowercase(&mult) != 'm' && mult != ',')) {\r
+      continue;\r
+    }\r
+    v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576 : 1;\r
+    if (vec.len == 1 && vec.ptr[0] == '*') {\r
+      throttle = (int) v;\r
+    } else if (parse_net(vec.ptr, &net, &mask) > 0) {\r
+      if ((remote_ip & mask) == net) {\r
+        throttle = (int) v;\r
+      }\r
+    } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {\r
+      throttle = (int) v;\r
+    }\r
+  }\r
+\r
+  return throttle;\r
+}\r
+\r
+static uint32_t get_remote_ip(const struct mg_connection *conn) {\r
+  return ntohl(* (uint32_t *) &conn->client.rsa.sin.sin_addr);\r
+}\r
+\r
+#ifdef USE_LUA\r
+\r
+#ifdef _WIN32\r
+static void *mmap(void *addr, int64_t len, int prot, int flags, int fd,\r
+                  int offset) {\r
+  HANDLE fh = (HANDLE) _get_osfhandle(fd);\r
+  HANDLE mh = CreateFileMapping(fh, 0, PAGE_READONLY, 0, 0, 0);\r
+  void *p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, (size_t) len);\r
+  CloseHandle(fh);\r
+  CloseHandle(mh);\r
+  return p;\r
+}\r
+#define munmap(x, y)  UnmapViewOfFile(x)\r
+#define MAP_FAILED NULL\r
+#define MAP_PRIVATE 0\r
+#define PROT_READ 0\r
+#else\r
+#include <sys/mman.h>\r
+#endif\r
+\r
+static void lsp(struct mg_connection *conn, const char *p, int64_t len,\r
+                lua_State *L) {\r
+  int i, j, pos = 0;\r
+\r
+  for (i = 0; i < len; i++) {\r
+    if (p[i] == '<' && p[i + 1] == '?') {\r
+      for (j = i + 1; j < len ; j++) {\r
+        if (p[j] == '?' && p[j + 1] == '>') {\r
+          mg_write(conn, p + pos, i - pos);\r
+          if (luaL_loadbuffer(L, p + (i + 2), j - (i + 2), "") == LUA_OK) {\r
+            lua_pcall(L, 0, LUA_MULTRET, 0);\r
+          }\r
+          pos = j + 2;\r
+          i = pos - 1;\r
+          break;\r
+        }\r
+      }\r
+    }\r
+  }\r
+\r
+  if (i > pos) {\r
+    mg_write(conn, p + pos, i - pos);\r
+  }\r
+}\r
+\r
+static int lsp_mg_print(lua_State *L) {\r
+  int i, num_args;\r
+  const char *str;\r
+  size_t size;\r
+  struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));\r
+\r
+  num_args = lua_gettop(L);\r
+  for (i = 1; i <= num_args; i++) {\r
+    if (lua_isstring(L, i)) {\r
+      str = lua_tolstring(L, i, &size);\r
+      mg_write(conn, str, size);\r
+    }\r
+  }\r
+\r
+  return 0;\r
+}\r
+\r
+static int lsp_mg_read(lua_State *L) {\r
+  struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));\r
+  char buf[1024];\r
+  int len = mg_read(conn, buf, sizeof(buf));\r
+\r
+  lua_settop(L, 0);\r
+  lua_pushlstring(L, buf, len);\r
+\r
+  return 1;\r
+}\r
+\r
+static void reg_string(struct lua_State *L, const char *name, const char *val) {\r
+  lua_pushstring(L, name);\r
+  lua_pushstring(L, val);\r
+  lua_rawset(L, -3);\r
+}\r
+\r
+static void reg_int(struct lua_State *L, const char *name, int val) {\r
+  lua_pushstring(L, name);\r
+  lua_pushinteger(L, val);\r
+  lua_rawset(L, -3);\r
+}\r
+\r
+static void prepare_lua_environment(struct mg_connection *conn, lua_State *L) {\r
+  const struct mg_request_info *ri = mg_get_request_info(conn);\r
+  extern void luaL_openlibs(lua_State *);\r
+  int i;\r
+\r
+  luaL_openlibs(L);\r
+#ifdef USE_LUA_SQLITE3\r
+  { extern int luaopen_lsqlite3(lua_State *); luaopen_lsqlite3(L); }\r
+#endif\r
+\r
+  // Register "print" function which calls mg_write()\r
+  lua_pushlightuserdata(L, conn);\r
+  lua_pushcclosure(L, lsp_mg_print, 1);\r
+  lua_setglobal(L, "print");\r
+\r
+  // Register mg_read()\r
+  lua_pushlightuserdata(L, conn);\r
+  lua_pushcclosure(L, lsp_mg_read, 1);\r
+  lua_setglobal(L, "read");\r
+\r
+  // Export request_info\r
+  lua_newtable(L);\r
+  reg_string(L, "request_method", ri->request_method);\r
+  reg_string(L, "uri", ri->uri);\r
+  reg_string(L, "http_version", ri->http_version);\r
+  reg_string(L, "query_string", ri->query_string);\r
+  reg_int(L, "remote_ip", ri->remote_ip);\r
+  reg_int(L, "remote_port", ri->remote_port);\r
+  reg_int(L, "num_headers", ri->num_headers);\r
+  lua_pushstring(L, "http_headers");\r
+  lua_newtable(L);\r
+  for (i = 0; i < ri->num_headers; i++) {\r
+    reg_string(L, ri->http_headers[i].name, ri->http_headers[i].value);\r
+  }\r
+  lua_rawset(L, -3);\r
+  lua_setglobal(L, "request_info");\r
+}\r
+\r
+static void handle_lsp_request(struct mg_connection *conn, const char *path,\r
+                               struct file *filep) {\r
+  void *p = NULL;\r
+  lua_State *L = NULL;\r
+\r
+  if (!mg_stat(conn, path, filep) || !mg_fopen(conn, path, "r", filep)) {\r
+    send_http_error(conn, 404, "Not Found", "%s", "File not found");\r
+  } else if (filep->membuf == NULL &&\r
+             (p = mmap(NULL, (size_t) filep->size, PROT_READ, MAP_PRIVATE,\r
+                       fileno(filep->fp), 0)) == MAP_FAILED) {\r
+    send_http_error(conn, 500, http_500_error, "mmap(%s, %zu, %d): %s", path,\r
+                    (size_t) filep->size, fileno(filep->fp), strerror(errno));\r
+  } else if ((L = luaL_newstate()) == NULL) {\r
+    send_http_error(conn, 500, http_500_error, "%s", "luaL_newstate failed");\r
+  } else {\r
+    // We're not sending HTTP headers here, Lua page must do it.\r
+    prepare_lua_environment(conn, L);\r
+    if (conn->ctx->callbacks.init_lua != NULL) {\r
+      conn->ctx->callbacks.init_lua(conn, L);\r
+    }\r
+    lsp(conn, filep->membuf == NULL ? p : filep->membuf, filep->size, L);\r
+  }\r
+\r
+  if (L) lua_close(L);\r
+  if (p) munmap(p, filep->size);\r
+  mg_fclose(filep);\r
+}\r
+#endif // USE_LUA\r
+\r
+int mg_upload(struct mg_connection *conn, const char *destination_dir) {\r
+  const char *content_type_header, *boundary_start;\r
+  char buf[MG_BUF_LEN], path[PATH_MAX], fname[1024], boundary[100], *s;\r
+  FILE *fp;\r
+  int bl, n, i, j, headers_len, boundary_len, len = 0, num_uploaded_files = 0;\r
+\r
+  // Request looks like this:\r
+  //\r
+  // POST /upload HTTP/1.1\r
+  // Host: 127.0.0.1:8080\r
+  // Content-Length: 244894\r
+  // Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryRVr\r
+  //\r
+  // ------WebKitFormBoundaryRVr\r
+  // Content-Disposition: form-data; name="file"; filename="accum.png"\r
+  // Content-Type: image/png\r
+  //\r
+  //  <89>PNG\r
+  //  <PNG DATA>\r
+  // ------WebKitFormBoundaryRVr\r
+\r
+  // Extract boundary string from the Content-Type header\r
+  if ((content_type_header = mg_get_header(conn, "Content-Type")) == NULL ||\r
+      (boundary_start = strstr(content_type_header, "boundary=")) == NULL ||\r
+      (sscanf(boundary_start, "boundary=\"%99[^\"]\"", boundary) == 0 &&\r
+       sscanf(boundary_start, "boundary=%99s", boundary) == 0) ||\r
+      boundary[0] == '\0') {\r
+    return num_uploaded_files;\r
+  }\r
+\r
+  boundary_len = strlen(boundary);\r
+  bl = boundary_len + 4;  // \r\n--<boundary>\r
+  for (;;) {\r
+    // Pull in headers\r
+    assert(len >= 0 && len <= (int) sizeof(buf));\r
+    while ((n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0) {\r
+      len += n;\r
+    }\r
+    if ((headers_len = get_request_len(buf, len)) <= 0) {\r
+      break;\r
+    }\r
+\r
+    // Fetch file name.\r
+    fname[0] = '\0';\r
+    for (i = j = 0; i < headers_len; i++) {\r
+      if (buf[i] == '\r' && buf[i + 1] == '\n') {\r
+        buf[i] = buf[i + 1] = '\0';\r
+        // TODO(lsm): don't expect filename to be the 3rd field,\r
+        // parse the header properly instead.\r
+        sscanf(&buf[j], "Content-Disposition: %*s %*s filename=\"%1023[^\"]",\r
+               fname);\r
+        j = i + 2;\r
+      }\r
+    }\r
+\r
+    // Give up if the headers are not what we expect\r
+    if (fname[0] == '\0') {\r
+      break;\r
+    }\r
+\r
+    // Move data to the beginning of the buffer\r
+    assert(len >= headers_len);\r
+    memmove(buf, &buf[headers_len], len - headers_len);\r
+    len -= headers_len;\r
+\r
+    // We open the file with exclusive lock held. This guarantee us\r
+    // there is no other thread can save into the same file simultaneously.\r
+    fp = NULL;\r
+    // Construct destination file name. Do not allow paths to have slashes.\r
+    if ((s = strrchr(fname, '/')) == NULL) {\r
+      s = fname;\r
+    }\r
+    // Open file in binary mode. TODO: set an exclusive lock.\r
+    snprintf(path, sizeof(path), "%s/%s", destination_dir, s);\r
+    if ((fp = fopen(path, "wb")) == NULL) {\r
+      break;\r
+    }\r
+\r
+    // Read POST data, write into file until boundary is found.\r
+    n = 0;\r
+    do {\r
+      len += n;\r
+      for (i = 0; i < len - bl; i++) {\r
+        if (!memcmp(&buf[i], "\r\n--", 4) &&\r
+            !memcmp(&buf[i + 4], boundary, boundary_len)) {\r
+          // Found boundary, that's the end of file data.\r
+          fwrite(buf, 1, i, fp);\r
+          fflush(fp);\r
+          num_uploaded_files++;\r
+          if (conn->ctx->callbacks.upload != NULL) {\r
+            conn->ctx->callbacks.upload(conn, path);\r
+          }\r
+          memmove(buf, &buf[i + bl], len - (i + bl));\r
+          len -= i + bl;\r
+          break;\r
+        }\r
+      }\r
+      if (len > bl) {\r
+        fwrite(buf, 1, len - bl, fp);\r
+        memmove(buf, &buf[len - bl], bl);\r
+        len = bl;\r
+      }\r
+    } while ((n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0);\r
+    fclose(fp);\r
+  }\r
+\r
+  return num_uploaded_files;\r
+}\r
+\r
+static int is_put_or_delete_request(const struct mg_connection *conn) {\r
+  const char *s = conn->request_info.request_method;\r
+  return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE"));\r
+}\r
+\r
+static int get_first_ssl_listener_index(const struct mg_context *ctx) {\r
+  int i, index = -1;\r
+  for (i = 0; index == -1 && i < ctx->num_listening_sockets; i++) {\r
+    index = ctx->listening_sockets[i].is_ssl ? i : -1;\r
+  }\r
+  return index;\r
+}\r
+\r
+static void redirect_to_https_port(struct mg_connection *conn, int ssl_index) {\r
+  char host[1025];\r
+  const char *host_header;\r
+\r
+  if ((host_header = mg_get_header(conn, "Host")) == NULL ||\r
+      sscanf(host_header, "%1024[^:]", host) == 0) {\r
+    // Cannot get host from the Host: header. Fallback to our IP address.\r
+    sockaddr_to_string(host, sizeof(host), &conn->client.lsa);\r
+  }\r
+\r
+  mg_printf(conn, "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s\r\n\r\n",\r
+            host, (int) ntohs(conn->ctx->listening_sockets[ssl_index].\r
+                              lsa.sin.sin_port), conn->request_info.uri);\r
+}\r
+\r
+// This is the heart of the Mongoose's logic.\r
+// This function is called when the request is read, parsed and validated,\r
+// and Mongoose must decide what action to take: serve a file, or\r
+// a directory, or call embedded function, etcetera.\r
+static void handle_request(struct mg_connection *conn) {\r
+  struct mg_request_info *ri = &conn->request_info;\r
+  char path[PATH_MAX];\r
+  int uri_len, ssl_index;\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+\r
+  if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL) {\r
+    * ((char *) conn->request_info.query_string++) = '\0';\r
+  }\r
+  uri_len = (int) strlen(ri->uri);\r
+  url_decode(ri->uri, uri_len, (char *) ri->uri, uri_len + 1, 0);\r
+  remove_double_dots_and_double_slashes((char *) ri->uri);\r
+  convert_uri_to_file_name(conn, path, sizeof(path), &file);\r
+  conn->throttle = set_throttle(conn->ctx->config[THROTTLE],\r
+                                get_remote_ip(conn), ri->uri);\r
+\r
+  DEBUG_TRACE(("%s", ri->uri));\r
+  if (conn->ctx->callbacks.begin_request != NULL &&\r
+      conn->ctx->callbacks.begin_request(conn)) {\r
+    // Do nothing, callback has served the request\r
+  } else if (!conn->client.is_ssl && conn->client.ssl_redir &&\r
+      (ssl_index = get_first_ssl_listener_index(conn->ctx)) > -1) {\r
+    redirect_to_https_port(conn, ssl_index);\r
+  } else if (!is_put_or_delete_request(conn) &&\r
+             !check_authorization(conn, path)) {\r
+    send_authorization_request(conn);\r
+#if defined(USE_WEBSOCKET)\r
+  } else if (is_websocket_request(conn)) {\r
+    handle_websocket_request(conn);\r
+#endif\r
+  } else if (!strcmp(ri->request_method, "OPTIONS")) {\r
+    send_options(conn);\r
+  } else if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {\r
+    send_http_error(conn, 404, "Not Found", "Not Found");\r
+  } else if (is_put_or_delete_request(conn) &&\r
+             (conn->ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL ||\r
+              is_authorized_for_put(conn) != 1)) {\r
+    send_authorization_request(conn);\r
+  } else if (!strcmp(ri->request_method, "PUT")) {\r
+    put_file(conn, path);\r
+  } else if (!strcmp(ri->request_method, "DELETE")) {\r
+    if (mg_remove(path) == 0) {\r
+      send_http_error(conn, 200, "OK", "%s", "");\r
+    } else {\r
+      send_http_error(conn, 500, http_500_error, "remove(%s): %s", path,\r
+                      strerror(ERRNO));\r
+    }\r
+  } else if ((file.membuf == NULL && file.modification_time == (time_t) 0) ||\r
+             must_hide_file(conn, path)) {\r
+    send_http_error(conn, 404, "Not Found", "%s", "File not found");\r
+  } else if (file.is_directory && ri->uri[uri_len - 1] != '/') {\r
+    mg_printf(conn, "HTTP/1.1 301 Moved Permanently\r\n"\r
+              "Location: %s/\r\n\r\n", ri->uri);\r
+  } else if (!strcmp(ri->request_method, "PROPFIND")) {\r
+    handle_propfind(conn, path, &file);\r
+  } else if (file.is_directory &&\r
+             !substitute_index_file(conn, path, sizeof(path), &file)) {\r
+    if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")) {\r
+      handle_directory_request(conn, path);\r
+    } else {\r
+      send_http_error(conn, 403, "Directory Listing Denied",\r
+          "Directory listing denied");\r
+    }\r
+#ifdef USE_LUA\r
+  } else if (match_prefix("**.lp$", 6, path) > 0) {\r
+    handle_lsp_request(conn, path, &file);\r
+#endif\r
+#if !defined(NO_CGI)\r
+  } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],\r
+                          strlen(conn->ctx->config[CGI_EXTENSIONS]),\r
+                          path) > 0) {\r
+    if (strcmp(ri->request_method, "POST") &&\r
+        strcmp(ri->request_method, "HEAD") &&\r
+        strcmp(ri->request_method, "GET")) {\r
+      send_http_error(conn, 501, "Not Implemented",\r
+                      "Method %s is not implemented", ri->request_method);\r
+    } else {\r
+      handle_cgi_request(conn, path);\r
+    }\r
+#endif // !NO_CGI\r
+  } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],\r
+                          strlen(conn->ctx->config[SSI_EXTENSIONS]),\r
+                          path) > 0) {\r
+    handle_ssi_file_request(conn, path);\r
+  } else if (is_not_modified(conn, &file)) {\r
+    send_http_error(conn, 304, "Not Modified", "%s", "");\r
+  } else {\r
+    handle_file_request(conn, path, &file);\r
+  }\r
+}\r
+\r
+static void close_all_listening_sockets(struct mg_context *ctx) {\r
+  int i;\r
+  for (i = 0; i < ctx->num_listening_sockets; i++) {\r
+    closesocket(ctx->listening_sockets[i].sock);\r
+  }\r
+  free(ctx->listening_sockets);\r
+}\r
+\r
+// Valid listening port specification is: [ip_address:]port[s]\r
+// Examples: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s\r
+// TODO(lsm): add parsing of the IPv6 address\r
+static int parse_port_string(const struct vec *vec, struct socket *so) {\r
+  int a, b, c, d, port, len;\r
+\r
+  // MacOS needs that. If we do not zero it, subsequent bind() will fail.\r
+  // Also, all-zeroes in the socket address means binding to all addresses\r
+  // for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).\r
+  memset(so, 0, sizeof(*so));\r
+\r
+  if (sscanf(vec->ptr, "%d.%d.%d.%d:%d%n", &a, &b, &c, &d, &port, &len) == 5) {\r
+    // Bind to a specific IPv4 address\r
+    so->lsa.sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);\r
+  } else if (sscanf(vec->ptr, "%d%n", &port, &len) != 1 ||\r
+             len <= 0 ||\r
+             len > (int) vec->len ||\r
+             (vec->ptr[len] && vec->ptr[len] != 's' &&\r
+              vec->ptr[len] != 'r' && vec->ptr[len] != ',')) {\r
+    return 0;\r
+  }\r
+\r
+  so->is_ssl = vec->ptr[len] == 's';\r
+  so->ssl_redir = vec->ptr[len] == 'r';\r
+#if defined(USE_IPV6)\r
+  so->lsa.sin6.sin6_family = AF_INET6;\r
+  so->lsa.sin6.sin6_port = htons((uint16_t) port);\r
+#else\r
+  so->lsa.sin.sin_family = AF_INET;\r
+  so->lsa.sin.sin_port = htons((uint16_t) port);\r
+#endif\r
+\r
+  return 1;\r
+}\r
+\r
+static int set_ports_option(struct mg_context *ctx) {\r
+  const char *list = ctx->config[LISTENING_PORTS];\r
+  int on = 1, success = 1;\r
+  struct vec vec;\r
+  struct socket so;\r
+\r
+  while (success && (list = next_option(list, &vec, NULL)) != NULL) {\r
+    if (!parse_port_string(&vec, &so)) {\r
+      cry(fc(ctx), "%s: %.*s: invalid port spec. Expecting list of: %s",\r
+          __func__, (int) vec.len, vec.ptr, "[IP_ADDRESS:]PORT[s|p]");\r
+      success = 0;\r
+    } else if (so.is_ssl && ctx->ssl_ctx == NULL) {\r
+      cry(fc(ctx), "Cannot add SSL socket, is -ssl_certificate option set?");\r
+      success = 0;\r
+    } else if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6)) ==\r
+               INVALID_SOCKET ||\r
+               // On Windows, SO_REUSEADDR is recommended only for\r
+               // broadcast UDP sockets\r
+               setsockopt(so.sock, SOL_SOCKET, SO_REUSEADDR,\r
+                          (void *) &on, sizeof(on)) != 0 ||\r
+               bind(so.sock, &so.lsa.sa, sizeof(so.lsa)) != 0 ||\r
+               listen(so.sock, SOMAXCONN) != 0) {\r
+      cry(fc(ctx), "%s: cannot bind to %.*s: %s", __func__,\r
+          (int) vec.len, vec.ptr, strerror(ERRNO));\r
+      closesocket(so.sock);\r
+      success = 0;\r
+    } else {\r
+      set_close_on_exec(so.sock);\r
+      // TODO: handle realloc failure\r
+      ctx->listening_sockets = realloc(ctx->listening_sockets,\r
+                                       (ctx->num_listening_sockets + 1) *\r
+                                       sizeof(ctx->listening_sockets[0]));\r
+      ctx->listening_sockets[ctx->num_listening_sockets] = so;\r
+      ctx->num_listening_sockets++;\r
+    }\r
+  }\r
+\r
+  if (!success) {\r
+    close_all_listening_sockets(ctx);\r
+  }\r
+\r
+  return success;\r
+}\r
+\r
+static void log_header(const struct mg_connection *conn, const char *header,\r
+                       FILE *fp) {\r
+  const char *header_value;\r
+\r
+  if ((header_value = mg_get_header(conn, header)) == NULL) {\r
+    (void) fprintf(fp, "%s", " -");\r
+  } else {\r
+    (void) fprintf(fp, " \"%s\"", header_value);\r
+  }\r
+}\r
+\r
+static void log_access(const struct mg_connection *conn) {\r
+  const struct mg_request_info *ri;\r
+  FILE *fp;\r
+  char date[64], src_addr[20];\r
+\r
+  fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL ?  NULL :\r
+    fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");\r
+\r
+  if (fp == NULL)\r
+    return;\r
+\r
+  strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z",\r
+           localtime(&conn->birth_time));\r
+\r
+  ri = &conn->request_info;\r
+  flockfile(fp);\r
+\r
+  sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);\r
+  fprintf(fp, "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT,\r
+          src_addr, ri->remote_user == NULL ? "-" : ri->remote_user, date,\r
+          ri->request_method ? ri->request_method : "-",\r
+          ri->uri ? ri->uri : "-", ri->http_version,\r
+          conn->status_code, conn->num_bytes_sent);\r
+  log_header(conn, "Referer", fp);\r
+  log_header(conn, "User-Agent", fp);\r
+  fputc('\n', fp);\r
+  fflush(fp);\r
+\r
+  funlockfile(fp);\r
+  fclose(fp);\r
+}\r
+\r
+// Verify given socket address against the ACL.\r
+// Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.\r
+static int check_acl(struct mg_context *ctx, uint32_t remote_ip) {\r
+  int allowed, flag;\r
+  uint32_t net, mask;\r
+  struct vec vec;\r
+  const char *list = ctx->config[ACCESS_CONTROL_LIST];\r
+\r
+  // If any ACL is set, deny by default\r
+  allowed = list == NULL ? '+' : '-';\r
+\r
+  while ((list = next_option(list, &vec, NULL)) != NULL) {\r
+    flag = vec.ptr[0];\r
+    if ((flag != '+' && flag != '-') ||\r
+        parse_net(&vec.ptr[1], &net, &mask) == 0) {\r
+      cry(fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__);\r
+      return -1;\r
+    }\r
+\r
+    if (net == (remote_ip & mask)) {\r
+      allowed = flag;\r
+    }\r
+  }\r
+\r
+  return allowed == '+';\r
+}\r
+\r
+#if !defined(_WIN32)\r
+static int set_uid_option(struct mg_context *ctx) {\r
+  struct passwd *pw;\r
+  const char *uid = ctx->config[RUN_AS_USER];\r
+  int success = 0;\r
+\r
+  if (uid == NULL) {\r
+    success = 1;\r
+  } else {\r
+    if ((pw = getpwnam(uid)) == NULL) {\r
+      cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);\r
+    } else if (setgid(pw->pw_gid) == -1) {\r
+      cry(fc(ctx), "%s: setgid(%s): %s", __func__, uid, strerror(errno));\r
+    } else if (setuid(pw->pw_uid) == -1) {\r
+      cry(fc(ctx), "%s: setuid(%s): %s", __func__, uid, strerror(errno));\r
+    } else {\r
+      success = 1;\r
+    }\r
+  }\r
+\r
+  return success;\r
+}\r
+#endif // !_WIN32\r
+\r
+#if !defined(NO_SSL)\r
+static pthread_mutex_t *ssl_mutexes;\r
+\r
+static int sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *)) {\r
+  return (conn->ssl = SSL_new(s)) != NULL &&\r
+    SSL_set_fd(conn->ssl, conn->client.sock) == 1 &&\r
+    func(conn->ssl) == 1;\r
+}\r
+\r
+// Return OpenSSL error message\r
+static const char *ssl_error(void) {\r
+  unsigned long err;\r
+  err = ERR_get_error();\r
+  return err == 0 ? "" : ERR_error_string(err, NULL);\r
+}\r
+\r
+static void ssl_locking_callback(int mode, int mutex_num, const char *file,\r
+                                 int line) {\r
+  (void) line;\r
+  (void) file;\r
+\r
+  if (mode & 1) {  // 1 is CRYPTO_LOCK\r
+    (void) pthread_mutex_lock(&ssl_mutexes[mutex_num]);\r
+  } else {\r
+    (void) pthread_mutex_unlock(&ssl_mutexes[mutex_num]);\r
+  }\r
+}\r
+\r
+static unsigned long ssl_id_callback(void) {\r
+  return (unsigned long) pthread_self();\r
+}\r
+\r
+#if !defined(NO_SSL_DL)\r
+static int load_dll(struct mg_context *ctx, const char *dll_name,\r
+                    struct ssl_func *sw) {\r
+  union {void *p; void (*fp)(void);} u;\r
+  void  *dll_handle;\r
+  struct ssl_func *fp;\r
+\r
+  if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {\r
+    cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);\r
+    return 0;\r
+  }\r
+\r
+  for (fp = sw; fp->name != NULL; fp++) {\r
+#ifdef _WIN32\r
+    // GetProcAddress() returns pointer to function\r
+    u.fp = (void (*)(void)) dlsym(dll_handle, fp->name);\r
+#else\r
+    // dlsym() on UNIX returns void *. ISO C forbids casts of data pointers to\r
+    // function pointers. We need to use a union to make a cast.\r
+    u.p = dlsym(dll_handle, fp->name);\r
+#endif // _WIN32\r
+    if (u.fp == NULL) {\r
+      cry(fc(ctx), "%s: %s: cannot find %s", __func__, dll_name, fp->name);\r
+      return 0;\r
+    } else {\r
+      fp->ptr = u.fp;\r
+    }\r
+  }\r
+\r
+  return 1;\r
+}\r
+#endif // NO_SSL_DL\r
+\r
+// Dynamically load SSL library. Set up ctx->ssl_ctx pointer.\r
+static int set_ssl_option(struct mg_context *ctx) {\r
+  int i, size;\r
+  const char *pem;\r
+\r
+  // If PEM file is not specified, skip SSL initialization.\r
+  if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL) {\r
+    return 1;\r
+  }\r
+\r
+#if !defined(NO_SSL_DL)\r
+  if (!load_dll(ctx, SSL_LIB, ssl_sw) ||\r
+      !load_dll(ctx, CRYPTO_LIB, crypto_sw)) {\r
+    return 0;\r
+  }\r
+#endif // NO_SSL_DL\r
+\r
+  // Initialize SSL library\r
+  SSL_library_init();\r
+  SSL_load_error_strings();\r
+\r
+  if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {\r
+    cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());\r
+    return 0;\r
+  }\r
+\r
+  // If user callback returned non-NULL, that means that user callback has\r
+  // set up certificate itself. In this case, skip sertificate setting.\r
+  if ((ctx->callbacks.init_ssl == NULL ||\r
+       !ctx->callbacks.init_ssl(ctx->ssl_ctx)) &&\r
+      (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0 ||\r
+       SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0)) {\r
+    cry(fc(ctx), "%s: cannot open %s: %s", __func__, pem, ssl_error());\r
+    return 0;\r
+  }\r
+\r
+  if (pem != NULL) {\r
+    (void) SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);\r
+  }\r
+\r
+  // Initialize locking callbacks, needed for thread safety.\r
+  // http://www.openssl.org/support/faq.html#PROG1\r
+  size = sizeof(pthread_mutex_t) * CRYPTO_num_locks();\r
+  if ((ssl_mutexes = (pthread_mutex_t *) malloc((size_t)size)) == NULL) {\r
+    cry(fc(ctx), "%s: cannot allocate mutexes: %s", __func__, ssl_error());\r
+    return 0;\r
+  }\r
+\r
+  for (i = 0; i < CRYPTO_num_locks(); i++) {\r
+    pthread_mutex_init(&ssl_mutexes[i], NULL);\r
+  }\r
+\r
+  CRYPTO_set_locking_callback(&ssl_locking_callback);\r
+  CRYPTO_set_id_callback(&ssl_id_callback);\r
+\r
+  return 1;\r
+}\r
+\r
+static void uninitialize_ssl(struct mg_context *ctx) {\r
+  int i;\r
+  if (ctx->ssl_ctx != NULL) {\r
+    CRYPTO_set_locking_callback(NULL);\r
+    for (i = 0; i < CRYPTO_num_locks(); i++) {\r
+      pthread_mutex_destroy(&ssl_mutexes[i]);\r
+    }\r
+    CRYPTO_set_locking_callback(NULL);\r
+    CRYPTO_set_id_callback(NULL);\r
+  }\r
+}\r
+#endif // !NO_SSL\r
+\r
+static int set_gpass_option(struct mg_context *ctx) {\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+  const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];\r
+  if (path != NULL && !mg_stat(fc(ctx), path, &file)) {\r
+    cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));\r
+    return 0;\r
+  }\r
+  return 1;\r
+}\r
+\r
+static int set_acl_option(struct mg_context *ctx) {\r
+  return check_acl(ctx, (uint32_t) 0x7f000001UL) != -1;\r
+}\r
+\r
+static void reset_per_request_attributes(struct mg_connection *conn) {\r
+  conn->path_info = NULL;\r
+  conn->num_bytes_sent = conn->consumed_content = 0;\r
+  conn->status_code = -1;\r
+  conn->must_close = conn->request_len = conn->throttle = 0;\r
+}\r
+\r
+static void close_socket_gracefully(struct mg_connection *conn) {\r
+#if defined(_WIN32)\r
+  char buf[MG_BUF_LEN];\r
+  int n;\r
+#endif\r
+  struct linger linger;\r
+\r
+  // Set linger option to avoid socket hanging out after close. This prevent\r
+  // ephemeral port exhaust problem under high QPS.\r
+  linger.l_onoff = 1;\r
+  linger.l_linger = 1;\r
+  setsockopt(conn->client.sock, SOL_SOCKET, SO_LINGER,\r
+             (char *) &linger, sizeof(linger));\r
+\r
+  // Send FIN to the client\r
+  shutdown(conn->client.sock, SHUT_WR);\r
+  set_non_blocking_mode(conn->client.sock);\r
+\r
+#if defined(_WIN32)\r
+  // Read and discard pending incoming data. If we do not do that and close the\r
+  // socket, the data in the send buffer may be discarded. This\r
+  // behaviour is seen on Windows, when client keeps sending data\r
+  // when server decides to close the connection; then when client\r
+  // does recv() it gets no data back.\r
+  do {\r
+    n = pull(NULL, conn, buf, sizeof(buf));\r
+  } while (n > 0);\r
+#endif\r
+\r
+  // Now we know that our FIN is ACK-ed, safe to close\r
+  closesocket(conn->client.sock);\r
+}\r
+\r
+static void close_connection(struct mg_connection *conn) {\r
+  conn->must_close = 1;\r
+  if (conn->client.sock != INVALID_SOCKET) {\r
+    close_socket_gracefully(conn);\r
+  }\r
+#ifndef NO_SSL\r
+  // Must be done AFTER socket is closed\r
+  if (conn->ssl != NULL) {\r
+    SSL_free(conn->ssl);\r
+  }\r
+#endif\r
+}\r
+\r
+void mg_close_connection(struct mg_connection *conn) {\r
+#ifndef NO_SSL\r
+  if (conn->client_ssl_ctx != NULL) {\r
+    SSL_CTX_free((SSL_CTX *) conn->client_ssl_ctx);\r
+  }\r
+#endif\r
+  close_connection(conn);\r
+  free(conn);\r
+}\r
+\r
+struct mg_connection *mg_connect(const char *host, int port, int use_ssl,\r
+                                 char *ebuf, size_t ebuf_len) {\r
+  static struct mg_context fake_ctx;\r
+  struct mg_connection *conn = NULL;\r
+  struct sockaddr_in sin;\r
+  struct hostent *he;\r
+  int sock;\r
+\r
+  if (host == NULL) {\r
+    snprintf(ebuf, ebuf_len, "%s", "NULL host");\r
+  } else if (use_ssl && SSLv23_client_method == NULL) {\r
+    snprintf(ebuf, ebuf_len, "%s", "SSL is not initialized");\r
+  } else if ((he = gethostbyname(host)) == NULL) {\r
+    snprintf(ebuf, ebuf_len, "gethostbyname(%s): %s", host, strerror(ERRNO));\r
+  } else if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {\r
+    snprintf(ebuf, ebuf_len, "socket(): %s", strerror(ERRNO));\r
+  } else {\r
+    sin.sin_family = AF_INET;\r
+    sin.sin_port = htons((uint16_t) port);\r
+    sin.sin_addr = * (struct in_addr *) he->h_addr_list[0];\r
+    if (connect(sock, (struct sockaddr *) &sin, sizeof(sin)) != 0) {\r
+      snprintf(ebuf, ebuf_len, "connect(%s:%d): %s",\r
+               host, port, strerror(ERRNO));\r
+      closesocket(sock);\r
+    } else if ((conn = (struct mg_connection *)\r
+                calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {\r
+      snprintf(ebuf, ebuf_len, "calloc(): %s", strerror(ERRNO));\r
+      closesocket(sock);\r
+#ifndef NO_SSL\r
+    } else if (use_ssl && (conn->client_ssl_ctx =\r
+                           SSL_CTX_new(SSLv23_client_method())) == NULL) {\r
+      snprintf(ebuf, ebuf_len, "SSL_CTX_new error");\r
+      closesocket(sock);\r
+      free(conn);\r
+      conn = NULL;\r
+#endif // NO_SSL\r
+    } else {\r
+      conn->buf_size = MAX_REQUEST_SIZE;\r
+      conn->buf = (char *) (conn + 1);\r
+      conn->ctx = &fake_ctx;\r
+      conn->client.sock = sock;\r
+      conn->client.rsa.sin = sin;\r
+      conn->client.is_ssl = use_ssl;\r
+#ifndef NO_SSL\r
+      if (use_ssl) {\r
+        // SSL_CTX_set_verify call is needed to switch off server certificate\r
+        // checking, which is off by default in OpenSSL and on in yaSSL.\r
+        SSL_CTX_set_verify(conn->client_ssl_ctx, 0, 0);\r
+        sslize(conn, conn->client_ssl_ctx, SSL_connect);\r
+      }\r
+#endif\r
+    }\r
+  }\r
+\r
+  return conn;\r
+}\r
+\r
+static int is_valid_uri(const char *uri) {\r
+  // Conform to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2\r
+  // URI can be an asterisk (*) or should start with slash.\r
+  return uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0');\r
+}\r
+\r
+static int getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len) {\r
+  const char *cl;\r
+\r
+  ebuf[0] = '\0';\r
+  reset_per_request_attributes(conn);\r
+  conn->request_len = read_request(NULL, conn, conn->buf, conn->buf_size,\r
+                                   &conn->data_len);\r
+  assert(conn->request_len < 0 || conn->data_len >= conn->request_len);\r
+\r
+  if (conn->request_len == 0 && conn->data_len == conn->buf_size) {\r
+    snprintf(ebuf, ebuf_len, "%s", "Request Too Large");\r
+  } if (conn->request_len <= 0) {\r
+    snprintf(ebuf, ebuf_len, "%s", "Client closed connection");\r
+  } else if (parse_http_message(conn->buf, conn->buf_size,\r
+                                &conn->request_info) <= 0) {\r
+    snprintf(ebuf, ebuf_len, "Bad request: [%.*s]", conn->data_len, conn->buf);\r
+  } else {\r
+    // Request is valid\r
+    if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {\r
+      conn->content_len = strtoll(cl, NULL, 10);\r
+    } else if (!mg_strcasecmp(conn->request_info.request_method, "POST") ||\r
+               !mg_strcasecmp(conn->request_info.request_method, "PUT")) {\r
+      conn->content_len = -1;\r
+    } else {\r
+      conn->content_len = 0;\r
+    }\r
+    conn->birth_time = time(NULL);\r
+  }\r
+  return ebuf[0] == '\0';\r
+}\r
+\r
+struct mg_connection *mg_download(const char *host, int port, int use_ssl,\r
+                                  char *ebuf, size_t ebuf_len,\r
+                                  const char *fmt, ...) {\r
+  struct mg_connection *conn;\r
+  va_list ap;\r
+\r
+  va_start(ap, fmt);\r
+  ebuf[0] = '\0';\r
+  if ((conn = mg_connect(host, port, use_ssl, ebuf, ebuf_len)) == NULL) {\r
+  } else if (mg_vprintf(conn, fmt, ap) <= 0) {\r
+    snprintf(ebuf, ebuf_len, "%s", "Error sending request");\r
+  } else {\r
+    getreq(conn, ebuf, ebuf_len);\r
+  }\r
+  if (ebuf[0] != '\0' && conn != NULL) {\r
+    mg_close_connection(conn);\r
+    conn = NULL;\r
+  }\r
+\r
+  return conn;\r
+}\r
+\r
+static void process_new_connection(struct mg_connection *conn) {\r
+  struct mg_request_info *ri = &conn->request_info;\r
+  int keep_alive_enabled, keep_alive, discard_len;\r
+  char ebuf[100];\r
+\r
+  keep_alive_enabled = !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");\r
+  keep_alive = 0;\r
+\r
+  // Important: on new connection, reset the receiving buffer. Credit goes\r
+  // to crule42.\r
+  conn->data_len = 0;\r
+  do {\r
+    if (!getreq(conn, ebuf, sizeof(ebuf))) {\r
+      send_http_error(conn, 500, "Server Error", "%s", ebuf);\r
+    } else if (!is_valid_uri(conn->request_info.uri)) {\r
+      snprintf(ebuf, sizeof(ebuf), "Invalid URI: [%s]", ri->uri);\r
+      send_http_error(conn, 400, "Bad Request", "%s", ebuf);\r
+    } else if (strcmp(ri->http_version, "1.0") &&\r
+               strcmp(ri->http_version, "1.1")) {\r
+      snprintf(ebuf, sizeof(ebuf), "Bad HTTP version: [%s]", ri->http_version);\r
+      send_http_error(conn, 505, "Bad HTTP version", "%s", ebuf);\r
+    }\r
+\r
+    if (ebuf[0] == '\0') {\r
+      handle_request(conn);\r
+      if (conn->ctx->callbacks.end_request != NULL) {\r
+        conn->ctx->callbacks.end_request(conn, conn->status_code);\r
+      }\r
+      log_access(conn);\r
+    }\r
+    if (ri->remote_user != NULL) {\r
+      free((void *) ri->remote_user);\r
+    }\r
+\r
+    // NOTE(lsm): order is important here. should_keep_alive() call\r
+    // is using parsed request, which will be invalid after memmove's below.\r
+    // Therefore, memorize should_keep_alive() result now for later use\r
+    // in loop exit condition.\r
+    keep_alive = should_keep_alive(conn);\r
+\r
+    // Discard all buffered data for this request\r
+    discard_len = conn->content_len >= 0 &&\r
+      conn->request_len + conn->content_len < (int64_t) conn->data_len ?\r
+      (int) (conn->request_len + conn->content_len) : conn->data_len;\r
+    memmove(conn->buf, conn->buf + discard_len, conn->data_len - discard_len);\r
+    conn->data_len -= discard_len;\r
+    assert(conn->data_len >= 0);\r
+    assert(conn->data_len <= conn->buf_size);\r
+\r
+  } while (conn->ctx->stop_flag == 0 &&\r
+           keep_alive_enabled &&\r
+           conn->content_len >= 0 &&\r
+           keep_alive);\r
+}\r
+\r
+// Worker threads take accepted socket from the queue\r
+static int consume_socket(struct mg_context *ctx, struct socket *sp) {\r
+  (void) pthread_mutex_lock(&ctx->mutex);\r
+  DEBUG_TRACE(("going idle"));\r
+\r
+  // If the queue is empty, wait. We're idle at this point.\r
+  while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {\r
+    pthread_cond_wait(&ctx->sq_full, &ctx->mutex);\r
+  }\r
+\r
+  // If we're stopping, sq_head may be equal to sq_tail.\r
+  if (ctx->sq_head > ctx->sq_tail) {\r
+    // Copy socket from the queue and increment tail\r
+    *sp = ctx->queue[ctx->sq_tail % ARRAY_SIZE(ctx->queue)];\r
+    ctx->sq_tail++;\r
+    DEBUG_TRACE(("grabbed socket %d, going busy", sp->sock));\r
+\r
+    // Wrap pointers if needed\r
+    while (ctx->sq_tail > (int) ARRAY_SIZE(ctx->queue)) {\r
+      ctx->sq_tail -= ARRAY_SIZE(ctx->queue);\r
+      ctx->sq_head -= ARRAY_SIZE(ctx->queue);\r
+    }\r
+  }\r
+\r
+  (void) pthread_cond_signal(&ctx->sq_empty);\r
+  (void) pthread_mutex_unlock(&ctx->mutex);\r
+\r
+  return !ctx->stop_flag;\r
+}\r
+\r
+static void *worker_thread(void *thread_func_param) {\r
+  struct mg_context *ctx = thread_func_param;\r
+  struct mg_connection *conn;\r
+\r
+  conn = (struct mg_connection *) calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);\r
+  if (conn == NULL) {\r
+    cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");\r
+  } else {\r
+    conn->buf_size = MAX_REQUEST_SIZE;\r
+    conn->buf = (char *) (conn + 1);\r
+    conn->ctx = ctx;\r
+    conn->request_info.user_data = ctx->user_data;\r
+\r
+    // Call consume_socket() even when ctx->stop_flag > 0, to let it signal\r
+    // sq_empty condvar to wake up the master waiting in produce_socket()\r
+    while (consume_socket(ctx, &conn->client)) {\r
+      conn->birth_time = time(NULL);\r
+\r
+      // Fill in IP, port info early so even if SSL setup below fails,\r
+      // error handler would have the corresponding info.\r
+      // Thanks to Johannes Winkelmann for the patch.\r
+      // TODO(lsm): Fix IPv6 case\r
+      conn->request_info.remote_port = ntohs(conn->client.rsa.sin.sin_port);\r
+      memcpy(&conn->request_info.remote_ip,\r
+             &conn->client.rsa.sin.sin_addr.s_addr, 4);\r
+      conn->request_info.remote_ip = ntohl(conn->request_info.remote_ip);\r
+      conn->request_info.is_ssl = conn->client.is_ssl;\r
+\r
+      if (!conn->client.is_ssl\r
+#ifndef NO_SSL\r
+          || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)\r
+#endif\r
+         ) {\r
+        process_new_connection(conn);\r
+      }\r
+\r
+      close_connection(conn);\r
+    }\r
+    free(conn);\r
+  }\r
+\r
+  // Signal master that we're done with connection and exiting\r
+  (void) pthread_mutex_lock(&ctx->mutex);\r
+  ctx->num_threads--;\r
+  (void) pthread_cond_signal(&ctx->cond);\r
+  assert(ctx->num_threads >= 0);\r
+  (void) pthread_mutex_unlock(&ctx->mutex);\r
+\r
+  DEBUG_TRACE(("exiting"));\r
+  return NULL;\r
+}\r
+\r
+// Master thread adds accepted socket to a queue\r
+static void produce_socket(struct mg_context *ctx, const struct socket *sp) {\r
+  (void) pthread_mutex_lock(&ctx->mutex);\r
+\r
+  // If the queue is full, wait\r
+  while (ctx->stop_flag == 0 &&\r
+         ctx->sq_head - ctx->sq_tail >= (int) ARRAY_SIZE(ctx->queue)) {\r
+    (void) pthread_cond_wait(&ctx->sq_empty, &ctx->mutex);\r
+  }\r
+\r
+  if (ctx->sq_head - ctx->sq_tail < (int) ARRAY_SIZE(ctx->queue)) {\r
+    // Copy socket to the queue and increment head\r
+    ctx->queue[ctx->sq_head % ARRAY_SIZE(ctx->queue)] = *sp;\r
+    ctx->sq_head++;\r
+    DEBUG_TRACE(("queued socket %d", sp->sock));\r
+  }\r
+\r
+  (void) pthread_cond_signal(&ctx->sq_full);\r
+  (void) pthread_mutex_unlock(&ctx->mutex);\r
+}\r
+\r
+static int set_sock_timeout(SOCKET sock, int milliseconds) {\r
+#ifdef _WIN32\r
+  DWORD t = milliseconds;\r
+#else\r
+  struct timeval t;\r
+  t.tv_sec = milliseconds / 1000;\r
+  t.tv_usec = (milliseconds * 1000) % 1000000;\r
+#endif\r
+  return setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (void *) &t, sizeof(t)) ||\r
+    setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (void *) &t, sizeof(t));\r
+}\r
+\r
+static void accept_new_connection(const struct socket *listener,\r
+                                  struct mg_context *ctx) {\r
+  struct socket so;\r
+  char src_addr[20];\r
+  socklen_t len = sizeof(so.rsa);\r
+  int on = 1;\r
+\r
+  if ((so.sock = accept(listener->sock, &so.rsa.sa, &len)) == INVALID_SOCKET) {\r
+  } else if (!check_acl(ctx, ntohl(* (uint32_t *) &so.rsa.sin.sin_addr))) {\r
+    sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);\r
+    cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);\r
+    closesocket(so.sock);\r
+  } else {\r
+    // Put so socket structure into the queue\r
+    DEBUG_TRACE(("Accepted socket %d", (int) so.sock));\r
+    so.is_ssl = listener->is_ssl;\r
+    so.ssl_redir = listener->ssl_redir;\r
+    getsockname(so.sock, &so.lsa.sa, &len);\r
+    // Set TCP keep-alive. This is needed because if HTTP-level keep-alive\r
+    // is enabled, and client resets the connection, server won't get\r
+    // TCP FIN or RST and will keep the connection open forever. With TCP\r
+    // keep-alive, next keep-alive handshake will figure out that the client\r
+    // is down and will close the server end.\r
+    // Thanks to Igor Klopov who suggested the patch.\r
+    setsockopt(so.sock, SOL_SOCKET, SO_KEEPALIVE, (void *) &on, sizeof(on));\r
+    set_sock_timeout(so.sock, atoi(ctx->config[REQUEST_TIMEOUT]));\r
+    produce_socket(ctx, &so);\r
+  }\r
+}\r
+\r
+static void *master_thread(void *thread_func_param) {\r
+  struct mg_context *ctx = thread_func_param;\r
+  struct pollfd *pfd;\r
+  int i;\r
+\r
+  // Increase priority of the master thread\r
+#if defined(_WIN32)\r
+  SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);\r
+#endif\r
+\r
+#if defined(ISSUE_317)\r
+  struct sched_param sched_param;\r
+  sched_param.sched_priority = sched_get_priority_max(SCHED_RR);\r
+  pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);\r
+#endif\r
+\r
+  pfd = calloc(ctx->num_listening_sockets, sizeof(pfd[0]));\r
+  while (ctx->stop_flag == 0) {\r
+    for (i = 0; i < ctx->num_listening_sockets; i++) {\r
+      pfd[i].fd = ctx->listening_sockets[i].sock;\r
+      pfd[i].events = POLLIN;\r
+    }\r
+\r
+    if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {\r
+      for (i = 0; i < ctx->num_listening_sockets; i++) {\r
+        if (ctx->stop_flag == 0 && pfd[i].revents == POLLIN) {\r
+          accept_new_connection(&ctx->listening_sockets[i], ctx);\r
+        }\r
+      }\r
+    }\r
+  }\r
+  free(pfd);\r
+  DEBUG_TRACE(("stopping workers"));\r
+\r
+  // Stop signal received: somebody called mg_stop. Quit.\r
+  close_all_listening_sockets(ctx);\r
+\r
+  // Wakeup workers that are waiting for connections to handle.\r
+  pthread_cond_broadcast(&ctx->sq_full);\r
+\r
+  // Wait until all threads finish\r
+  (void) pthread_mutex_lock(&ctx->mutex);\r
+  while (ctx->num_threads > 0) {\r
+    (void) pthread_cond_wait(&ctx->cond, &ctx->mutex);\r
+  }\r
+  (void) pthread_mutex_unlock(&ctx->mutex);\r
+\r
+  // All threads exited, no sync is needed. Destroy mutex and condvars\r
+  (void) pthread_mutex_destroy(&ctx->mutex);\r
+  (void) pthread_cond_destroy(&ctx->cond);\r
+  (void) pthread_cond_destroy(&ctx->sq_empty);\r
+  (void) pthread_cond_destroy(&ctx->sq_full);\r
+\r
+#if !defined(NO_SSL)\r
+  uninitialize_ssl(ctx);\r
+#endif\r
+  DEBUG_TRACE(("exiting"));\r
+\r
+  // Signal mg_stop() that we're done.\r
+  // WARNING: This must be the very last thing this\r
+  // thread does, as ctx becomes invalid after this line.\r
+  ctx->stop_flag = 2;\r
+  return NULL;\r
+}\r
+\r
+static void free_context(struct mg_context *ctx) {\r
+  int i;\r
+\r
+  // Deallocate config parameters\r
+  for (i = 0; i < NUM_OPTIONS; i++) {\r
+    if (ctx->config[i] != NULL)\r
+      free(ctx->config[i]);\r
+  }\r
+\r
+#ifndef NO_SSL\r
+  // Deallocate SSL context\r
+  if (ctx->ssl_ctx != NULL) {\r
+    SSL_CTX_free(ctx->ssl_ctx);\r
+  }\r
+  if (ssl_mutexes != NULL) {\r
+    free(ssl_mutexes);\r
+    ssl_mutexes = NULL;\r
+  }\r
+#endif // !NO_SSL\r
+\r
+  // Deallocate context itself\r
+  free(ctx);\r
+}\r
+\r
+void mg_stop(struct mg_context *ctx) {\r
+  ctx->stop_flag = 1;\r
+\r
+  // Wait until mg_fini() stops\r
+  while (ctx->stop_flag != 2) {\r
+    (void) mg_sleep(10);\r
+  }\r
+  free_context(ctx);\r
+\r
+#if defined(_WIN32) && !defined(__SYMBIAN32__)\r
+  (void) WSACleanup();\r
+#endif // _WIN32\r
+}\r
+\r
+struct mg_context *mg_start(const struct mg_callbacks *callbacks,\r
+                            void *user_data,\r
+                            const char **options) {\r
+  struct mg_context *ctx;\r
+  const char *name, *value, *default_value;\r
+  int i;\r
+\r
+#if defined(_WIN32) && !defined(__SYMBIAN32__)\r
+  WSADATA data;\r
+  WSAStartup(MAKEWORD(2,2), &data);\r
+  InitializeCriticalSection(&global_log_file_lock);\r
+#endif // _WIN32\r
+\r
+  // Allocate context and initialize reasonable general case defaults.\r
+  // TODO(lsm): do proper error handling here.\r
+  if ((ctx = (struct mg_context *) calloc(1, sizeof(*ctx))) == NULL) {\r
+    return NULL;\r
+  }\r
+  ctx->callbacks = *callbacks;\r
+  ctx->user_data = user_data;\r
+\r
+  while (options && (name = *options++) != NULL) {\r
+    if ((i = get_option_index(name)) == -1) {\r
+      cry(fc(ctx), "Invalid option: %s", name);\r
+      free_context(ctx);\r
+      return NULL;\r
+    } else if ((value = *options++) == NULL) {\r
+      cry(fc(ctx), "%s: option value cannot be NULL", name);\r
+      free_context(ctx);\r
+      return NULL;\r
+    }\r
+    if (ctx->config[i] != NULL) {\r
+      cry(fc(ctx), "warning: %s: duplicate option", name);\r
+      free(ctx->config[i]);\r
+    }\r
+    ctx->config[i] = mg_strdup(value);\r
+    DEBUG_TRACE(("[%s] -> [%s]", name, value));\r
+  }\r
+\r
+  // Set default value if needed\r
+  for (i = 0; config_options[i * ENTRIES_PER_CONFIG_OPTION] != NULL; i++) {\r
+    default_value = config_options[i * ENTRIES_PER_CONFIG_OPTION + 2];\r
+    if (ctx->config[i] == NULL && default_value != NULL) {\r
+      ctx->config[i] = mg_strdup(default_value);\r
+      DEBUG_TRACE(("Setting default: [%s] -> [%s]",\r
+                   config_options[i * ENTRIES_PER_CONFIG_OPTION + 1],\r
+                   default_value));\r
+    }\r
+  }\r
+\r
+  // NOTE(lsm): order is important here. SSL certificates must\r
+  // be initialized before listening ports. UID must be set last.\r
+  if (!set_gpass_option(ctx) ||\r
+#if !defined(NO_SSL)\r
+      !set_ssl_option(ctx) ||\r
+#endif\r
+      !set_ports_option(ctx) ||\r
+#if !defined(_WIN32)\r
+      !set_uid_option(ctx) ||\r
+#endif\r
+      !set_acl_option(ctx)) {\r
+    free_context(ctx);\r
+    return NULL;\r
+  }\r
+\r
+#if !defined(_WIN32) && !defined(__SYMBIAN32__)\r
+  // Ignore SIGPIPE signal, so if browser cancels the request, it\r
+  // won't kill the whole process.\r
+  (void) signal(SIGPIPE, SIG_IGN);\r
+  // Also ignoring SIGCHLD to let the OS to reap zombies properly.\r
+  (void) signal(SIGCHLD, SIG_IGN);\r
+#endif // !_WIN32\r
+\r
+  (void) pthread_mutex_init(&ctx->mutex, NULL);\r
+  (void) pthread_cond_init(&ctx->cond, NULL);\r
+  (void) pthread_cond_init(&ctx->sq_empty, NULL);\r
+  (void) pthread_cond_init(&ctx->sq_full, NULL);\r
+\r
+  // Start master (listening) thread\r
+  mg_start_thread(master_thread, ctx);\r
+\r
+  // Start worker threads\r
+  for (i = 0; i < atoi(ctx->config[NUM_THREADS]); i++) {\r
+    if (mg_start_thread(worker_thread, ctx) != 0) {\r
+      cry(fc(ctx), "Cannot start worker thread: %d", ERRNO);\r
+    } else {\r
+      ctx->num_threads++;\r
+    }\r
+  }\r
+\r
+  return ctx;\r
+}\r
diff --git a/mongoose.h b/mongoose.h
new file mode 100644 (file)
index 0000000..20904f8
--- /dev/null
@@ -0,0 +1,292 @@
+// Copyright (c) 2004-2012 Sergey Lyubka\r
+//\r
+// Permission is hereby granted, free of charge, to any person obtaining a copy\r
+// of this software and associated documentation files (the "Software"), to deal\r
+// in the Software without restriction, including without limitation the rights\r
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r
+// copies of the Software, and to permit persons to whom the Software is\r
+// furnished to do so, subject to the following conditions:\r
+//\r
+// The above copyright notice and this permission notice shall be included in\r
+// all copies or substantial portions of the Software.\r
+//\r
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r
+// THE SOFTWARE.\r
+\r
+#ifndef MONGOOSE_HEADER_INCLUDED\r
+#define  MONGOOSE_HEADER_INCLUDED\r
+\r
+#include <stdio.h>\r
+#include <stddef.h>\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif // __cplusplus\r
+\r
+struct mg_context;     // Handle for the HTTP service itself\r
+struct mg_connection;  // Handle for the individual connection\r
+\r
+\r
+// This structure contains information about the HTTP request.\r
+struct mg_request_info {\r
+  const char *request_method; // "GET", "POST", etc\r
+  const char *uri;            // URL-decoded URI\r
+  const char *http_version;   // E.g. "1.0", "1.1"\r
+  const char *query_string;   // URL part after '?', not including '?', or NULL\r
+  const char *remote_user;    // Authenticated user, or NULL if no auth used\r
+  long remote_ip;             // Client's IP address\r
+  int remote_port;            // Client's port\r
+  int is_ssl;                 // 1 if SSL-ed, 0 if not\r
+  void *user_data;            // User data pointer passed to mg_start()\r
+\r
+  int num_headers;            // Number of HTTP headers\r
+  struct mg_header {\r
+    const char *name;         // HTTP header name\r
+    const char *value;        // HTTP header value\r
+  } http_headers[64];         // Maximum 64 headers\r
+};\r
+\r
+\r
+// This structure needs to be passed to mg_start(), to let mongoose know\r
+// which callbacks to invoke. For detailed description, see\r
+// https://github.com/valenok/mongoose/blob/master/UserManual.md\r
+struct mg_callbacks {\r
+  int  (*begin_request)(struct mg_connection *);\r
+  void (*end_request)(const struct mg_connection *, int reply_status_code);\r
+  int  (*log_message)(const struct mg_connection *, const char *message);\r
+  int  (*init_ssl)(void *ssl_context);\r
+  int (*websocket_connect)(const struct mg_connection *);\r
+  void (*websocket_ready)(struct mg_connection *);\r
+  int  (*websocket_data)(struct mg_connection *);\r
+  const char * (*open_file)(const struct mg_connection *,\r
+                             const char *path, size_t *data_len);\r
+  void (*init_lua)(struct mg_connection *, void *lua_context);\r
+  void (*upload)(struct mg_connection *, const char *file_name);\r
+};\r
+\r
+// Start web server.\r
+//\r
+// Parameters:\r
+//   callbacks: mg_callbacks structure with user-defined callbacks.\r
+//   options: NULL terminated list of option_name, option_value pairs that\r
+//            specify Mongoose configuration parameters.\r
+//\r
+// Side-effects: on UNIX, ignores SIGCHLD and SIGPIPE signals. If custom\r
+//    processing is required for these, signal handlers must be set up\r
+//    after calling mg_start().\r
+//\r
+//\r
+// Example:\r
+//   const char *options[] = {\r
+//     "document_root", "/var/www",\r
+//     "listening_ports", "80,443s",\r
+//     NULL\r
+//   };\r
+//   struct mg_context *ctx = mg_start(&my_func, NULL, options);\r
+//\r
+// Please refer to http://code.google.com/p/mongoose/wiki/MongooseManual\r
+// for the list of valid option and their possible values.\r
+//\r
+// Return:\r
+//   web server context, or NULL on error.\r
+struct mg_context *mg_start(const struct mg_callbacks *callbacks,\r
+                            void *user_data,\r
+                            const char **configuration_options);\r
+\r
+\r
+// Stop the web server.\r
+//\r
+// Must be called last, when an application wants to stop the web server and\r
+// release all associated resources. This function blocks until all Mongoose\r
+// threads are stopped. Context pointer becomes invalid.\r
+void mg_stop(struct mg_context *);\r
+\r
+\r
+// Get the value of particular configuration parameter.\r
+// The value returned is read-only. Mongoose does not allow changing\r
+// configuration at run time.\r
+// If given parameter name is not valid, NULL is returned. For valid\r
+// names, return value is guaranteed to be non-NULL. If parameter is not\r
+// set, zero-length string is returned.\r
+const char *mg_get_option(const struct mg_context *ctx, const char *name);\r
+\r
+\r
+// Return array of strings that represent valid configuration options.\r
+// For each option, a short name, long name, and default value is returned.\r
+// Array is NULL terminated.\r
+const char **mg_get_valid_option_names(void);\r
+\r
+\r
+// Add, edit or delete the entry in the passwords file.\r
+//\r
+// This function allows an application to manipulate .htpasswd files on the\r
+// fly by adding, deleting and changing user records. This is one of the\r
+// several ways of implementing authentication on the server side. For another,\r
+// cookie-based way please refer to the examples/chat.c in the source tree.\r
+//\r
+// If password is not NULL, entry is added (or modified if already exists).\r
+// If password is NULL, entry is deleted.\r
+//\r
+// Return:\r
+//   1 on success, 0 on error.\r
+int mg_modify_passwords_file(const char *passwords_file_name,\r
+                             const char *domain,\r
+                             const char *user,\r
+                             const char *password);\r
+\r
+\r
+// Return information associated with the request.\r
+struct mg_request_info *mg_get_request_info(struct mg_connection *);\r
+\r
+\r
+// Send data to the client.\r
+// Return:\r
+//  0   when the connection has been closed\r
+//  -1  on error\r
+//  number of bytes written on success\r
+int mg_write(struct mg_connection *, const void *buf, size_t len);\r
+\r
+\r
+#undef PRINTF_FORMAT_STRING\r
+#if _MSC_VER >= 1400\r
+#include <sal.h>\r
+#if _MSC_VER > 1400\r
+#define PRINTF_FORMAT_STRING(s) _Printf_format_string_ s\r
+#else\r
+#define PRINTF_FORMAT_STRING(s) __format_string s\r
+#endif\r
+#else\r
+#define PRINTF_FORMAT_STRING(s) s\r
+#endif\r
+\r
+#ifdef __GNUC__\r
+#define PRINTF_ARGS(x, y) __attribute__((format(printf, x, y)))\r
+#else\r
+#define PRINTF_ARGS(x, y)\r
+#endif\r
+\r
+// Send data to the browser using printf() semantics.\r
+//\r
+// Works exactly like mg_write(), but allows to do message formatting.\r
+// Below are the macros for enabling compiler-specific checks for\r
+// printf-like arguments.\r
+int mg_printf(struct mg_connection *,\r
+              PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3);\r
+\r
+\r
+// Send contents of the entire file together with HTTP headers.\r
+void mg_send_file(struct mg_connection *conn, const char *path);\r
+\r
+\r
+// Read data from the remote end, return number of bytes read.\r
+int mg_read(struct mg_connection *, void *buf, size_t len);\r
+\r
+\r
+// Get the value of particular HTTP header.\r
+//\r
+// This is a helper function. It traverses request_info->http_headers array,\r
+// and if the header is present in the array, returns its value. If it is\r
+// not present, NULL is returned.\r
+const char *mg_get_header(const struct mg_connection *, const char *name);\r
+\r
+\r
+// Get a value of particular form variable.\r
+//\r
+// Parameters:\r
+//   data: pointer to form-uri-encoded buffer. This could be either POST data,\r
+//         or request_info.query_string.\r
+//   data_len: length of the encoded data.\r
+//   var_name: variable name to decode from the buffer\r
+//   dst: destination buffer for the decoded variable\r
+//   dst_len: length of the destination buffer\r
+//\r
+// Return:\r
+//   On success, length of the decoded variable.\r
+//   On error:\r
+//      -1 (variable not found).\r
+//      -2 (destination buffer is NULL, zero length or too small to hold the decoded variable).\r
+//\r
+// Destination buffer is guaranteed to be '\0' - terminated if it is not\r
+// NULL or zero length.\r
+int mg_get_var(const char *data, size_t data_len,\r
+               const char *var_name, char *dst, size_t dst_len);\r
+\r
+// Fetch value of certain cookie variable into the destination buffer.\r
+//\r
+// Destination buffer is guaranteed to be '\0' - terminated. In case of\r
+// failure, dst[0] == '\0'. Note that RFC allows many occurrences of the same\r
+// parameter. This function returns only first occurrence.\r
+//\r
+// Return:\r
+//   On success, value length.\r
+//   On error:\r
+//      -1 (either "Cookie:" header is not present at all or the requested parameter is not found).\r
+//      -2 (destination buffer is NULL, zero length or too small to hold the value).\r
+int mg_get_cookie(const struct mg_connection *,\r
+                  const char *cookie_name, char *buf, size_t buf_len);\r
+\r
+\r
+// Download data from the remote web server.\r
+//   host: host name to connect to, e.g. "foo.com", or "10.12.40.1".\r
+//   port: port number, e.g. 80.\r
+//   use_ssl: wether to use SSL connection.\r
+//   error_buffer, error_buffer_size: error message placeholder.\r
+//   request_fmt,...: HTTP request.\r
+// Return:\r
+//   On success, valid pointer to the new connection, suitable for mg_read().\r
+//   On error, NULL. error_buffer contains error message.\r
+// Example:\r
+//   char ebuf[100];\r
+//   struct mg_connection *conn;\r
+//   conn = mg_download("google.com", 80, 0, ebuf, sizeof(ebuf),\r
+//                      "%s", "GET / HTTP/1.0\r\nHost: google.com\r\n\r\n");\r
+struct mg_connection *mg_download(const char *host, int port, int use_ssl,\r
+                                  char *error_buffer, size_t error_buffer_size,\r
+                                  PRINTF_FORMAT_STRING(const char *request_fmt),\r
+                                  ...) PRINTF_ARGS(6, 7);\r
+\r
+\r
+// Close the connection opened by mg_download().\r
+void mg_close_connection(struct mg_connection *conn);\r
+\r
+\r
+// File upload functionality. Each uploaded file gets saved into a temporary\r
+// file and MG_UPLOAD event is sent.\r
+// Return number of uploaded files.\r
+int mg_upload(struct mg_connection *conn, const char *destination_dir);\r
+\r
+\r
+// Convenience function -- create detached thread.\r
+// Return: 0 on success, non-0 on error.\r
+typedef void * (*mg_thread_func_t)(void *);\r
+int mg_start_thread(mg_thread_func_t f, void *p);\r
+\r
+\r
+// Return builtin mime type for the given file name.\r
+// For unrecognized extensions, "text/plain" is returned.\r
+const char *mg_get_builtin_mime_type(const char *file_name);\r
+\r
+\r
+// Return Mongoose version.\r
+const char *mg_version(void);\r
+\r
+\r
+// MD5 hash given strings.\r
+// Buffer 'buf' must be 33 bytes long. Varargs is a NULL terminated list of\r
+// ASCIIz strings. When function returns, buf will contain human-readable\r
+// MD5 hash. Example:\r
+//   char buf[33];\r
+//   mg_md5(buf, "aa", "bb", NULL);\r
+void mg_md5(char buf[33], ...);\r
+\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif // __cplusplus\r
+\r
+#endif // MONGOOSE_HEADER_INCLUDED\r