Parcourir la source

Merge branch 'master' of https://github.com/bel2125/civetweb

Maarten Fremouw il y a 11 ans
Parent
commit
8276b220a7

+ 2 - 2
README.md

@@ -4,8 +4,8 @@
 There is a new home!!!
 -----------------
 https://github.com/bel2125/civetweb
-Bel has been taking the lead on Civetweb, so teh official repositiory 
-is being moved under his control for ease of maintanence.
+Bel has been taking the lead on Civetweb, so the official repository
+is being moved under his control for ease of maintenance.
 
 Project Mission
 -----------------

+ 1 - 0
RELEASE_NOTES.md

@@ -5,6 +5,7 @@ Release Notes v1.6 (Under Development)
 Changes
 -------
 
+- Support user defined error pages (bel)
 - Method to get POST request parameters via C++ interface (bel)
 - Re-Add unit tests for Linux and Windows (jmc-, bel)
 - Allow to specify title and tray icon for the Windows standalone server (bel)

+ 1 - 1
VS2012/civetweb/civetweb.vcxproj

@@ -27,7 +27,7 @@
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
     <ConfigurationType>Application</ConfigurationType>
     <UseDebugLibraries>true</UseDebugLibraries>
-    <PlatformToolset>v110_xp</PlatformToolset>
+    <PlatformToolset>v100</PlatformToolset>
     <CharacterSet>MultiByte</CharacterSet>
   </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">

+ 5 - 1
VS2012/civetweb_lua/civetweb_lua.vcxproj

@@ -28,7 +28,7 @@
     <ConfigurationType>Application</ConfigurationType>
     <UseDebugLibraries>true</UseDebugLibraries>
     <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>v110_xp</PlatformToolset>
+    <PlatformToolset>v100</PlatformToolset>
   </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
     <ConfigurationType>Application</ConfigurationType>
@@ -169,6 +169,10 @@
       <Project>{8f5e5d77-d269-4665-9e27-1045da6cf0d8}</Project>
     </ProjectReference>
   </ItemGroup>
+  <ItemGroup>
+    <None Include="..\..\src\md5.inl" />
+    <None Include="..\..\src\mod_lua.inl" />
+  </ItemGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
   <ImportGroup Label="ExtensionTargets">
   </ImportGroup>

+ 11 - 0
VS2012/civetweb_lua/civetweb_lua.vcxproj.filters

@@ -13,6 +13,9 @@
       <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
       <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
     </Filter>
+    <Filter Include="inl files">
+      <UniqueIdentifier>{1ef3413b-2315-48f2-ad22-57af6b4f7aca}</UniqueIdentifier>
+    </Filter>
   </ItemGroup>
   <ItemGroup>
     <Text Include="ReadMe.txt" />
@@ -46,4 +49,12 @@
       <Filter>Resource Files</Filter>
     </Image>
   </ItemGroup>
+  <ItemGroup>
+    <None Include="..\..\src\md5.inl">
+      <Filter>inl files</Filter>
+    </None>
+    <None Include="..\..\src\mod_lua.inl">
+      <Filter>inl files</Filter>
+    </None>
+  </ItemGroup>
 </Project>

+ 1 - 1
VS2012/ex_embed_cpp/ex_embed_cpp.vcxproj

@@ -27,7 +27,7 @@
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
     <ConfigurationType>Application</ConfigurationType>
     <UseDebugLibraries>true</UseDebugLibraries>
-    <PlatformToolset>v110_xp</PlatformToolset>
+    <PlatformToolset>v100</PlatformToolset>
     <CharacterSet>Unicode</CharacterSet>
   </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">

+ 1 - 1
VS2012/ex_embedded_c/ex_embedded_c.vcxproj

@@ -34,7 +34,7 @@
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
     <ConfigurationType>Application</ConfigurationType>
     <UseDebugLibraries>true</UseDebugLibraries>
-    <PlatformToolset>v110_xp</PlatformToolset>
+    <PlatformToolset>v100</PlatformToolset>
     <CharacterSet>Unicode</CharacterSet>
   </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">

+ 162 - 124
docs/UserManual.md

@@ -2,54 +2,62 @@
 Overview
 =====
 
-Civetweb is small and easy to use web server. It is self-contained, and does
-not require any external software to run.
+Civetweb is small and easy to use web server.
+It may be embedded into C/C++ host applications or used as a stand-alone
+server. See `Embedding.md` for information on embedding civetweb into
+host applications.
+
+The stand-alone server is self-contained, and does not require any external
+software to run. Some Windows users may need to install the
+[Visual C++ Redistributable](http://www.microsoft.com/en-us/download/details.aspx?id=30679).
 
 Installation
 ----
 
-### Some Windows users may be the install the
-[Visual C++ Redistributable for Visual Studio 2012](http://www.microsoft.com/en-us/download/details.aspx?id=30679)
+On Windows, UNIX and Mac, the civetweb stand-alone executable may be started
+from the command line.
+Running `civetweb` in a terminal, optionally followed by configuration parameters
+(`civetweb [OPTIONS]`) or a configuration file name (`civetweb [config_file_name]`),
+starts the web server.
+
+For UNIX and Mac, civetweb does not detach from the terminal.
+Pressing `Ctrl-C` keys will stop the server.
 
 On Windows, civetweb iconifies itself to the system tray icon when started.
 Right-click on the icon pops up a menu, where it is possible to stop
-civetweb, or configure it, or install it as Windows service. The easiest way
-to share a folder on Windows is to copy `civetweb.exe` to a folder,
-double-click the exe, and launch a browser at
+civetweb, or configure it, or install it as Windows service.
+
+When started without options, the server exposes the local directory at
+[http](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol) port 8080.
+Thus, the easiest way to share a folder on Windows is to copy `civetweb.exe`
+to this folder, double-click the exe, and launch a browser at
 [http://localhost:8080](http://localhost:8080). Note that 'localhost' should
 be changed to a machine's name if a folder is accessed from other computer.
 
-On UNIX and Mac, civetweb is a command line utility. Running `civetweb` in
-terminal, optionally followed by configuration parameters
-(`civetweb [OPTIONS]`) or configuration file name
-(`civetweb [config_file_name]`) starts the
-web server. Civetweb does not detach from terminal. Pressing `Ctrl-C` keys
-would stop the server.
-
 When started, civetweb first searches for the configuration file.
 If configuration file is specified explicitly in the command line, i.e.
 `civetweb path_to_config_file`, then specified configuration file is used.
 Otherwise, civetweb would search for file `civetweb.conf` in the same directory
-where binary is located, and use it. Configuration file can be absent.
-
+the executable is located, and use it. This configuration file is optional.
 
-Configuration file is a sequence of lines, each line containing
-command line argument name and it's value. Empty lines, and lines beginning
-with `#`, are ignored. Here is the example of `civetweb.conf` file:
+The configuration file is a sequence of lines, each line containing one
+command line argument name and the corresponding value.
+Empty lines, and lines beginning with `#`, are ignored.
+Here is the example of `civetweb.conf` file:
 
     document_root c:\www
-    listening_ports 8080,8043s
+    listening_ports 80,443s
     ssl_certificate c:\civetweb\ssl_cert.pem
 
-When configuration file is processed, civetweb process command line arguments,
-if they are specified. Command line arguments therefore can override
-configuration file settings. Command line arguments must start with `-`.
-For example, if `civetweb.conf` has line
-`document_root /var/www`, and civetweb has been started as
-`civetweb -document_root /etc`, then `/etc` directory will be served as
-document root, because command line options take priority over
-configuration file. Configuration options section below provide a good
-overview of Civetweb features.
+When a configuration file is used, additional command line arguments may
+override the configuration file settings.
+All command line arguments must start with `-`.
+
+For example: The above `civetweb.conf` file is used, and civetweb started as
+`civetweb -document_root D:\web`. Then the `D:\web` directory will be served
+as document root, because command line options take priority over the
+configuration file. The configuration options section below provides a good
+overview of the Civetweb features.
 
 Note that configuration options on the command line must start with `-`,
 but their names are the same as in the config file. All option names are
@@ -64,12 +72,12 @@ listed in the next section. Thus, the following two setups are equivalent:
     document_root /var/www
     $ civetweb
 
-Civetweb can also be used to modify `.htpasswd` passwords file:
+Civetweb can also be used to modify `.htpasswd` passwords files:
 
     civetweb -A <htpasswd_file> <realm> <user> <passwd>
 
-Unlike other web servers, civetweb does not require CGI scripts be located in
-a special directory. CGI scripts can be anywhere. CGI (and SSI) files are
+Unlike other web servers, civetweb does not require CGI scripts to be located
+in a special directory. CGI scripts can be anywhere. CGI (and SSI) files are
 recognized by the file name pattern. Civetweb uses shell-like glob
 patterns. Pattern match starts at the beginning of the string, so essentially
 patterns are prefix patterns. Syntax is as follows:
@@ -88,66 +96,71 @@ All other characters in the pattern match themselves. Examples:
 
 # Configuration Options
 
-Below is a list of configuration options Civetweb understands. Every option
-is followed by it's default value. If default value is not present, then
-it is empty.
+Below is a list of configuration options understood by Civetweb.
+Every option is followed by it's default value. If a default value is not
+present, then the default is empty.
 
-### cgi_pattern `**.cgi$|**.pl$|**.php$`
+### cgi\_pattern `**.cgi$|**.pl$|**.php$`
 All files that match `cgi_pattern` are treated as CGI files. Default pattern
 allows CGI files be anywhere. To restrict CGIs to a certain directory,
-use `/path/to/cgi-bin/**.cgi` as pattern. Note that full file path is
+use `/path/to/cgi-bin/**.cgi` as pattern. Note that the full file path is
 matched against the pattern, not the URI.
 
-### cgi_environment
+### cgi\_environment
 Extra environment variables to be passed to the CGI script in
 addition to standard ones. The list must be comma-separated list
 of name=value pairs, like this: `VARIABLE1=VALUE1,VARIABLE2=VALUE2`.
 
 ### put\_delete\_auth\_file
-Passwords file for PUT and DELETE requests. Without it, PUT and DELETE requests
-will fail.
+Passwords file for PUT and DELETE requests. Without password file, it will not
+be possible to, PUT new files to the server or DELETE existing ones. PUT and
+DELETE requests might still be handled by Lua scripts and CGI paged.
 
-### cgi_interpreter
+### cgi\_interpreter
 Path to an executable to use as CGI interpreter for __all__ CGI scripts
-regardless script extension. If this option is not set (which is a default),
-Civetweb looks at first line of a CGI script,
-[shebang line](http://en.wikipedia.org/wiki/Shebang_(Unix\)), for an interpreter.
+regardless of the script file extension. If this option is not set (which is
+the default), Civetweb looks at first line of a CGI script,
+[shebang line](http://en.wikipedia.org/wiki/Shebang_(Unix\)), for an
+interpreter (not only on Linux and Mac but also for Windows).
 
-For example, if both PHP and perl CGIs are used, then
+For example, if both PHP and Perl CGIs are used, then
 `#!/path/to/php-cgi.exe` and `#!/path/to/perl.exe` must be first lines of the
 respective CGI scripts. Note that paths should be either full file paths,
-or file paths relative to the current working directory of civetweb server.
-If civetweb is started by mouse double-click on Windows, current working
-directory is a directory where civetweb executable is located.
+or file paths relative to the current working directory of the civetweb
+server. If civetweb is started by mouse double-click on Windows, the current
+working directory is the directory where the civetweb executable is located.
 
-If all CGIs use the same interpreter, for example they are all PHP, then
-`cgi_interpreter` can be set to the path to `php-cgi.exe` executable and
-shebang line in the CGI scripts can be omitted.
-Note that PHP scripts must use `php-cgi.exe` executable, not `php.exe`.
+If all CGIs use the same interpreter, for example they are all PHP, it is
+more efficient to set `cgi_interpreter` to the path to `php-cgi.exe`.
+The  shebang line in the CGI scripts can be omitted in this case.
+Note that PHP scripts must use `php-cgi.exe` as executable, not `php.exe`.
 
-### protect_uri
+### protect\_uri
 Comma separated list of URI=PATH pairs, specifying that given
-URIs must be protected with respected password files. Paths must be full
-file paths.
+URIs must be protected with password files specified by PATH.
+All Paths must be full file paths.
 
 ### authentication_domain `mydomain.com`
-Authorization realm used in `.htpasswd` authorization.
+Authorization realm used for HTTP digest authentication. This domain is
+used in the encoding of the `.htpasswd` authorization files as well.
+Changing the domain retroactively will render the existing passwords useless.
 
-### ssi_pattern `**.shtml$|**.shtm$`
-All files that match `ssi_pattern` are treated as SSI.
+### ssi\_pattern `**.shtml$|**.shtm$`
+All files that match `ssi_pattern` are treated as Server Side Includes (SSI).
 
-Server Side Includes (SSI) is a simple interpreted server-side scripting
-language which is most commonly used to include the contents of a file into
-a web page. It can be useful when it is desirable to include a common piece
+SSI is a simple interpreted server-side scripting language which is most
+commonly used to include the contents of another file into a web page.
+It can be useful when it is desirable to include a common piece
 of code throughout a website, for example, headers and footers.
 
 In order for a webpage to recognize an SSI-enabled HTML file, the filename
 should end with a special extension, by default the extension should be
-either `.shtml` or `.shtm`.
+either `.shtml` or `.shtm`. These extentions may be changed using the
+`ssi_pattern` option.
 
 Unknown SSI directives are silently ignored by civetweb. Currently, two SSI
 directives are supported, `<!--#include ...>` and
-`<!--#exec "command">`. Note that `<!--#include ...>` directive supports
+`<!--#exec "command">`. Note that the `<!--#include ...>` directive supports
 three path specifications:
 
     <!--#include virtual="path">  Path is relative to web server root
@@ -158,7 +171,8 @@ three path specifications:
 
 The `include` directive may be used to include the contents of a file or the
 result of running a CGI script. The `exec` directive is used to execute a
-command on a server, and show command's output. Example:
+command on a server, and show the output that would have been printed to
+stdout (the terminal window) otherwise. Example:
 
     <!--#exec "ls -l" -->
 
@@ -179,21 +193,21 @@ megabytes respectively. A limit of 0 means unlimited rate. The
 last matching rule wins. Examples:
 
     *=1k,10.0.0.0/8=0   limit all accesses to 1 kilobyte per second,
-                        but give connections from 10.0.0.0/8 subnet
+                        but give connections the from 10.0.0.0/8 subnet
                         unlimited speed
 
     /downloads/=5k      limit accesses to all URIs in `/downloads/` to
                         5 kilobytes per second. All other accesses are unlimited
 
 ### access\_log\_file
-Path to a file for access logs. Either full path, or relative to current
+Path to a file for access logs. Either full path, or relative to the current
 working directory. If absent (default), then accesses are not logged.
 
 ### enable\_directory\_listing `yes`
 Enable directory listing, either `yes` or `no`.
 
 ### error\_log\_file
-Path to a file for error logs. Either full path, or relative to current
+Path to a file for error logs. Either full path, or relative to the current
 working directory. If absent (default), then errors are not logged.
 
 ### global\_auth\_file
@@ -201,28 +215,31 @@ Path to a global passwords file, either full path or relative to the current
 working directory. If set, per-directory `.htpasswd` files are ignored,
 and all requests are authorized against that file.
 
-The file has to include the realm set through `authentication_domain` and the password in digest format:
+The file has to include the realm set through `authentication_domain` and the
+password in digest format:
 
     user:realm:digest
     test:test.com:ce0220efc2dd2fad6185e1f1af5a4327
 
-(e.g. use [this generator](http://www.askapache.com/online-tools/htpasswd-generator))
+Password files may be generated using `civetweb -A` as explained above, or
+online tools e.g. [this generator](http://www.askapache.com/online-tools/htpasswd-generator).
 
-### index_files `index.html,index.htm,index.cgi,index.shtml,index.php`
-Comma-separated list of files to be treated as directory index
-files.
+### index\_files `index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php`
+Comma-separated list of files to be treated as directory index files.
+If more than one matching file is present in a directory, the one listed to the left
+is used as a directory index.
 
 In case built-in Lua support has been enabled, `index.lp,index.lsp,index.lua`
-are additional default files.
+are additional default index files, ordered before `index.cgi`.
 
 ### enable\_keep\_alive `no`
 Enable connection keep alive, either `yes` or `no`.
 
-Experimental feature. Allows clients to reuse TCP connection for
-subsequent HTTP requests, which improves performance.
-For this to work when using request handlers it's important to add the correct
-Content-Length HTTP header for each request. If this is forgotten the client
-will time out.
+Experimental feature. Allows clients to reuse TCP connection for subsequent
+HTTP requests, which improves performance.
+For this to work when using request handlers it is important to add the
+correct Content-Length HTTP header for each request. If this is forgotten the
+client will time out.
 
 ### access\_control\_list
 An Access Control List (ACL) allows restrictions to be put on the list of IP
@@ -239,14 +256,15 @@ the last match wins. Examples:
     -0.0.0.0/0,+192.168/16    deny all accesses, only allow 192.168/16 subnet
 
 To learn more about subnet masks, see the
-[Wikipedia page on Subnetwork](http://en.wikipedia.org/wiki/Subnetwork)
+[Wikipedia page on Subnetwork](http://en.wikipedia.org/wiki/Subnetwork).
 
 ### extra\_mime\_types
-Extra mime types to recognize, in form `extension1=type1,exten-
-sion2=type2,...`. Extension must include dot.  Example:
+Extra mime types, in tha form `extension1=type1,exten-sion2=type2,...`.
+See the [Wikipedia page on Internet media types](http://en.wikipedia.org/wiki/Internet_media_type).
+Extension must include a leading dot. Example:
 `.cpp=plain/text,.java=plain/text`
 
-### listening_ports `8080`
+### listening\_ports `8080`
 Comma-separated list of ports to listen on. If the port is SSL, a
 letter `s` must be appended, for example, `80,443s` will open
 port 80 and port 443, and connections on port 443 will be SSL-ed.
@@ -260,33 +278,34 @@ an IP address and a colon must be pre-pended to the port number.
 For example, to bind to a loopback interface on port 80 and to
 all interfaces on HTTPS port 443, use `127.0.0.1:80,443s`.
 
-### document_root `.`
-A directory to serve. By default, current directory is served. Current
-directory is commonly referenced as dot (`.`).
+### document\_root `.`
+A directory to serve. By default, the current workubg directory is served.
+The current directory is commonly referenced as dot (`.`).
 
-### ssl_certificate
-Path to SSL certificate file. This option is only required when at least one
-of the `listening_ports` is SSL. The file must be in PEM format,
-and it must have both private key and certificate, see for example
+### ssl\_certificate
+Path to the SSL certificate file. This option is only required when at least
+one of the `listening\_ports` is SSL. The file must be in PEM format,
+and it must have both, private key and certificate, see for example
 [ssl_cert.pem](https://github.com/sunsetbrew/civetweb/blob/master/resources/ssl_cert.pem)
 A description how to create a certificate can be found in doc/OpenSSL.md
 
-### num_threads `50`
+### num\_threads `50`
 Number of worker threads. Civetweb handles each incoming connection in a
-separate thread. Therefore, the value of this option is effectively a number
+separate thread. Therefore, the value of this option is effectively the number
 of concurrent HTTP connections Civetweb can handle.
 
 ### run\_as\_user
 Switch to given user credentials after startup. Usually, this option is
-required when civetweb needs to bind on privileged port on UNIX. To do
-that, civetweb needs to be started as root. But running as root is a bad idea,
-therefore this option can be used to drop privileges. Example:
+required when civetweb needs to bind on privileged ports on UNIX. To do
+that, civetweb needs to be started as root. From a security point of view,
+running as root is not advisable, therefore this option can be used to drop
+privileges. Example:
 
-    civetweb -listening_ports 80 -run_as_user nobody
+    civetweb -listening_ports 80 -run_as_user webserver
 
 ### url\_rewrite\_patterns
 Comma-separated list of URL rewrites in the form of
-`uri_pattern=file_or_directory_path`. When Civetweb receives the request,
+`uri_pattern=file_or_directory_path`. When Civetweb receives any request,
 it constructs the file name to show by combining `document_root` and the URI.
 However, if the rewrite option is used and `uri_pattern` matches the
 requested URI, then `document_root` is ignored. Instead,
@@ -300,48 +319,63 @@ to redirect all accesses to `.doc` files to a special script, do:
 
     civetweb -url_rewrite_patterns **.doc$=/path/to/cgi-bin/handle_doc.cgi
 
-Or, to imitate user home directories support, do:
+Or, to imitate support for user home directories, do:
 
     civetweb -url_rewrite_patterns /~joe/=/home/joe/,/~bill=/home/bill/
 
 ### hide\_files\_patterns
 A pattern for the files to hide. Files that match the pattern will not
 show up in directory listing and return `404 Not Found` if requested. Pattern
-must be for a file name only, not including directory name. Example:
+must be for a file name only, not including directory names. Example:
 
-    civetweb -hide_files_patterns secret.txt|even_more_secret.txt
+    civetweb -hide_files_patterns secret.txt|*.hide
 
 ### request\_timeout\_ms `30000`
 Timeout for network read and network write operations, in milliseconds.
-If client intends to keep long-running connection, either increase this value
-or use keep-alive messages.
+If a client intends to keep long-running connection, either increase this
+value or (better) use keep-alive messages.
 
-### lua_preload_file
+### lua\_preload\_file
 This configuration option can be used to specify a Lua script file, which
 is executed before the actual web page script (Lua script, Lua server page
 or Lua websocket). It can be used to modify the Lua environment of all web
-page scripts, e.g., by loading additional libraries required by all scripts
-or to achieve backward compatibility by defining obsolete functions.
+page scripts, e.g., by loading additional libraries or defining functions
+required by all scripts.
+It may be used to achieve backward compatibility by defining obsolete
+functions as well.
 
-### lua_script_pattern `"**.lua$`
+### lua\_script\_pattern `"**.lua$`
 A pattern for files that are interpreted as Lua scripts by the server.
 In contrast to Lua server pages, Lua scripts use plain Lua syntax.
 An example can be found in the test directory.
 
-### lua_server_page_pattern `**.lp$|**.lsp$`
+### lua\_server\_page\_pattern `**.lp$|**.lsp$`
 Files matching this pattern are treated as Lua server pages.
 In contrast to Lua scripts, the content of a Lua server pages is delivered
 directly to the client. Lua script parts are delimited from the standard
 content by including them between <? and ?> tags.
 An example can be found in the test directory.
 
-### websocket_root
+### websocket\_root
 In case civetweb is built with Lua and websocket support, Lua scripts may
 be used for websockets as well. Since websockets use a different URL scheme
 (ws, wss) than other http pages (http, https), the Lua scripts used for
 websockets may also be served from a different directory. By default,
 the document_root is used as websocket_root as well.
 
+### access\_control\_allow\_origin
+Access-Control-Allow-Origin header field, used for cross-origin resource
+sharing (CORS).
+See the [Wikipedia page on CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing).
+
+### error\_pages
+This option may be used to specify a directory for user defined error pages.
+The error pages may be specified for an individual http status code (e.g.,
+404 - page requested by the client not found), a group of http status codes
+(e.g., 4xx - all client errors) or all errors. The corresponding error pages
+must be called error404.ext, error4xx.ext or error.ext, whereas the file
+extention may be one of the extentions specified for the index_files option.
+See the [Wikipedia page on HTTP status codes](http://en.wikipedia.org/wiki/HTTP_status_code).
 
 # Lua Scripts and Lua Server Pages
 Pre-built Windows and Mac civetweb binaries have built-in Lua scripting
@@ -358,8 +392,9 @@ PHP. Lua script elements must be enclosed in `<?  ?>` blocks, and can appear
 anywhere on the page. Furthermore, Lua Server Pages offer the opportunity to
 insert the content of a variable by enclosing the Lua variable name in
 `<?=  ?>` blocks, similar to PHP.
-For example, to print current weekday name and the URI of the current page,
-one can write:
+For example, to print the current weekday name and the URI of the current
+page, one can write:
+
     <p>
       <span>Today is:</span>
       <? mg.write(os.date("%A")) ?>
@@ -368,17 +403,17 @@ one can write:
       URI is <?=mg.request_info.uri?>
     </p>
 
-Lua is known for it's speed and small size. Civetweb uses Lua version 5.2.2,
-the documentation for it can be found at
+Lua is known for it's speed and small size. Civetweb currently uses Lua
+version 5.2.2. The documentation for it can be found in the
 [Lua 5.2 reference manual](http://www.lua.org/manual/5.2/).
 
 
-Note that this example uses function `mg.write()`, which prints data to the
-web page. Using function `mg.write()` is the way to generate web content from
-inside Lua code. In addition to `mg.write()`, all standard library functions
-are accessible from the Lua code (please check reference manual for details),
-and also information about the request is available in `mg.request_info`
-object, like request method, all headers, etcetera.
+Note that this example uses function `mg.write()`, which sends data to the
+web client. Using `mg.write()` is the way to generate web content from inside
+Lua code. In addition to `mg.write()`, all standard Lua library functions
+are accessible from the Lua code (please check the reference manual for
+details). Information on the request is available in the `mg.request_info`
+object, like the request method, all HTTP headers, etcetera.
 
 [page2.lua](https://github.com/sunsetbrew/civetweb/blob/master/test/page2.lua)
 is an example for a plain Lua script.
@@ -393,13 +428,15 @@ to see additional information on the elements of the `mg.request_info` object.
 
 Civetweb also provides access to the [SQlite3 database](http://www.sqlite.org/)
 through the [LuaSQLite3 interface](http://lua.sqlite.org/index.cgi/doc/tip/doc/lsqlite3.wiki)
-in Lua. An example is given in
+in Lua. Examples are given in
+[page.lua](https://github.com/bel2125/civetweb/blob/master/test/page.lua) and
 [page.lp](https://github.com/sunsetbrew/civetweb/blob/master/test/page.lp).
 
 
 Civetweb exports the following functions to Lua:
 
 mg (table):
+
     mg.read()                  -- reads a chunk from POST data, returns it as a string
     mg.write(str)              -- writes string to the client
     mg.include(path)           -- sources another Lua file
@@ -431,6 +468,7 @@ mg (table):
          .remote_user          -- user name if authenticated, nil otherwise
 
 connect (function):
+
     -- Connect to the remote TCP server. This function is an implementation
     -- of simple socket interface. It returns a socket object with three
     -- methods: send, recv, close, which are synchronous (blocking).
@@ -450,25 +488,25 @@ connect (function):
 
 
 **IMPORTANT: Civetweb does not send HTTP headers for Lua pages. Therefore,
-every Lua Page must begin with HTTP reply line and headers**, like this:
+every Lua Page must begin with a HTTP reply line and headers**, like this:
 
     <? print('HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n') ?>
     <html><body>
       ... the rest of the web page ...
 
-To serve Lua Page, civetweb creates Lua context. That context is used for
+To serve a Lua Page, civetweb creates a Lua context. That context is used for
 all Lua blocks within the page. That means, all Lua blocks on the same page
 share the same context. If one block defines a variable, for example, that
-variable is visible in the block that follows.
+variable is visible in all block that follow.
 
 # Common Problems
 - PHP doesn't work - getting empty page, or 'File not found' error. The
   reason for that is wrong paths to the interpreter. Remember that with PHP,
-  correct interpreter is `php-cgi.exe` (`php-cgi` on UNIX). Solution: specify
-  full path to the PHP interpreter, e.g.:
+  the correct interpreter is `php-cgi.exe` (`php-cgi` on UNIX).
+  Solution: specify the full path to the PHP interpreter, e.g.:
     `civetweb -cgi_interpreter /full/path/to/php-cgi`
 
-- Civetweb fails to start. If Civetweb exits immediately when run, this
+- Civetweb fails to start. If Civetweb exits immediately when started, this
   usually indicates a syntax error in the configuration file
   (named `civetweb.conf` by default) or the command-line arguments.
   Syntax checking is omitted from Civetweb to keep its size low. However,

+ 331 - 220
src/civetweb.c

@@ -309,6 +309,40 @@ typedef int SOCKET;
 
 #endif /* End of Windows and UNIX specific includes */
 
+#ifdef _WIN32
+static CRITICAL_SECTION global_log_file_lock;
+static DWORD pthread_self(void)
+{
+    return GetCurrentThreadId();
+}
+
+int pthread_key_create(pthread_key_t *key, void (*_must_be_zero)(void*) /* destructor function not supported for windows */)
+{
+    assert(_must_be_zero == NULL);
+    if ((key!=0) && (_must_be_zero == NULL)) {
+        *key = TlsAlloc();
+        return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
+    }
+    return -2;
+}
+
+int pthread_key_delete(pthread_key_t key)
+{
+    return TlsFree(key) ? 0 : 1;
+}
+
+int pthread_setspecific(pthread_key_t key, void * value)
+{
+    return TlsSetValue(key, value) ? 0 : 1;
+}
+
+void *pthread_getspecific(pthread_key_t key)
+{
+    return TlsGetValue(key);
+}
+#endif /* _WIN32 */
+
+
 #include "civetweb.h"
 
 #define PASSWORDS_FILE_NAME ".htpasswd"
@@ -320,23 +354,30 @@ typedef int SOCKET;
 #endif
 #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
 
-#ifdef DEBUG_TRACE
-#undef DEBUG_TRACE
-#define DEBUG_TRACE(x)
-#else
+#if !defined(DEBUG_TRACE)
 #if defined(DEBUG)
-#define DEBUG_TRACE(x) do { \
-  flockfile(stdout); \
-  printf("*** %lu.%p.%s.%d: ", \
-         (unsigned long) time(NULL), (void *) pthread_self(), \
-         __func__, __LINE__); \
-  printf x; \
-  putchar('\n'); \
-  fflush(stdout); \
-  funlockfile(stdout); \
-} while (0)
+
+static void DEBUG_TRACE_FUNC(const char *func, unsigned line, PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(3, 4);
+
+static void DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...) {
+
+  va_list args;
+  flockfile(stdout);
+  printf("*** %lu.%p.%s.%d: ",
+         (unsigned long) time(NULL), (void *) pthread_self(),
+         func, line);
+  va_start(args, fmt);
+  vprintf(fmt, args);
+  va_end(args);
+  putchar('\n');
+  fflush(stdout);
+  funlockfile(stdout);
+}
+
+#define DEBUG_TRACE(fmt, ...) DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
+
 #else
-#define DEBUG_TRACE(x)
+#define DEBUG_TRACE(fmt, ...)
 #endif /* DEBUG */
 #endif /* DEBUG_TRACE */
 
@@ -459,39 +500,6 @@ static __inline void   mg_free(void * a)               {free(a);}
 #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
 #define free    DO_NOT_USE_THIS_FUNCTION__USE_mg_free
 
-#ifdef _WIN32
-static CRITICAL_SECTION global_log_file_lock;
-static DWORD pthread_self(void)
-{
-    return GetCurrentThreadId();
-}
-
-int pthread_key_create(pthread_key_t *key, void (*_must_be_zero)(void*) /* destructor function not supported for windows */)
-{
-    assert(_must_be_zero == NULL);
-    if ((key!=0) && (_must_be_zero == NULL)) {
-        *key = TlsAlloc();
-        return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
-    }
-    return -2;
-}
-
-int pthread_key_delete(pthread_key_t key)
-{
-    return TlsFree(key) ? 0 : 1;
-}
-
-int pthread_setspecific(pthread_key_t key, void * value)
-{
-    return TlsSetValue(key, value) ? 0 : 1;
-}
-
-void *pthread_getspecific(pthread_key_t key)
-{
-    return TlsGetValue(key);
-}
-#endif /* _WIN32 */
-
 #define MD5_STATIC static
 #include "md5.inl"
 
@@ -678,7 +686,7 @@ enum {
 #if defined(USE_LUA) && defined(USE_WEBSOCKET)
     LUA_WEBSOCKET_EXTENSIONS,
 #endif
-    ACCESS_CONTROL_ALLOW_ORIGIN,
+    ACCESS_CONTROL_ALLOW_ORIGIN, ERROR_PAGES,
 
     NUM_OPTIONS
 };
@@ -699,9 +707,9 @@ static struct mg_option config_options[] = {
     {"global_auth_file",            CONFIG_TYPE_FILE,          NULL},
     {"index_files",                 12345,
 #ifdef USE_LUA
-    "index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,index.shtml,index.php"},
+    "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,index.shtml,index.php"},
 #else
-    "index.html,index.htm,index.cgi,index.shtml,index.php"},
+    "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
 #endif
     {"enable_keep_alive",           CONFIG_TYPE_BOOLEAN,       "no"},
     {"access_control_list",         12345,                     NULL},
@@ -727,6 +735,7 @@ static struct mg_option config_options[] = {
     {"lua_websocket_pattern",       CONFIG_TYPE_EXT_PATTERN,   "**.lua$"},
 #endif
     {"access_control_allow_origin", CONFIG_TYPE_STRING,        "*"},
+    {"error_pages",                 CONFIG_TYPE_DIRECTORY,     NULL},
 
     {NULL, CONFIG_TYPE_UNKNOWN, NULL}
 };
@@ -792,6 +801,7 @@ struct mg_connection {
     char *buf;                  /* Buffer for received data */
     char *path_info;            /* PATH_INFO part of the URL */
     int must_close;             /* 1 if connection must be closed */
+    int in_error_handler;       /* 1 if in handler for user defined error pages */
     int buf_size;               /* Buffer size */
     int request_len;            /* Size of the request + headers in a buffer */
     int data_len;               /* Total size of data in a buffer */
@@ -891,6 +901,115 @@ static void mg_fclose(struct file *filep)
     }
 }
 
+static void mg_strlcpy(register char *dst, register const char *src, size_t n)
+{
+    for (; *src != '\0' && n > 1; n--) {
+        *dst++ = *src++;
+    }
+    *dst = '\0';
+}
+
+static int lowercase(const char *s)
+{
+    return tolower(* (const unsigned char *) s);
+}
+
+int mg_strncasecmp(const char *s1, const char *s2, size_t len)
+{
+    int diff = 0;
+
+    if (len > 0)
+        do {
+            diff = lowercase(s1++) - lowercase(s2++);
+        } while (diff == 0 && s1[-1] != '\0' && --len > 0);
+
+    return diff;
+}
+
+static int mg_strcasecmp(const char *s1, const char *s2)
+{
+    int diff;
+
+    do {
+        diff = lowercase(s1++) - lowercase(s2++);
+    } while (diff == 0 && s1[-1] != '\0');
+
+    return diff;
+}
+
+static char * mg_strndup(const char *ptr, size_t len)
+{
+    char *p;
+
+    if ((p = (char *) mg_malloc(len + 1)) != NULL) {
+        mg_strlcpy(p, ptr, len + 1);
+    }
+
+    return p;
+}
+
+static char * mg_strdup(const char *str)
+{
+    return mg_strndup(str, strlen(str));
+}
+
+static const char *mg_strcasestr(const char *big_str, const char *small_str)
+{
+    int i, big_len = (int)strlen(big_str), small_len = (int)strlen(small_str);
+
+    for (i = 0; i <= big_len - small_len; i++) {
+        if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
+            return big_str + i;
+        }
+    }
+
+    return NULL;
+}
+
+/* Like snprintf(), but never returns negative value, or a value
+   that is larger than a supplied buffer.
+   Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability
+   in his audit report. */
+static int mg_vsnprintf(struct mg_connection *conn, char *buf, size_t buflen,
+                        const char *fmt, va_list ap)
+{
+    int n;
+
+    if (buflen == 0)
+        return 0;
+
+    n = vsnprintf(buf, buflen, fmt, ap);
+
+    if (n < 0) {
+        mg_cry(conn, "vsnprintf error");
+        n = 0;
+    } else if (n >= (int) buflen) {
+        mg_cry(conn, "truncating vsnprintf buffer: [%.*s]",
+               n > 200 ? 200 : n, buf);
+        n = (int) buflen - 1;
+    }
+    buf[n] = '\0';
+
+    return n;
+}
+
+static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
+                       PRINTF_FORMAT_STRING(const char *fmt), ...)
+PRINTF_ARGS(4, 5);
+
+static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
+                       const char *fmt, ...)
+{
+    va_list ap;
+    int n;
+
+    va_start(ap, fmt);
+    n = mg_vsnprintf(conn, buf, buflen, fmt, ap);
+    va_end(ap);
+
+    return n;
+}
+
 static int get_option_index(const char *name)
 {
     int i;
@@ -936,7 +1055,7 @@ static void sockaddr_to_string(char *buf, size_t len,
               (void *) &usa->sin6.sin6_addr, buf, len);
 #elif defined(_WIN32)
     /* Only Windows Vista (and newer) have inet_ntop() */
-    strncpy(buf, inet_ntoa(usa->sin.sin_addr), len);
+    mg_strlcpy(buf, inet_ntoa(usa->sin.sin_addr), len);
 #else
     inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, len);
 #endif
@@ -951,7 +1070,7 @@ static void gmt_time_string(char *buf, size_t buf_len, time_t *t)
     if (tm != NULL) {
         strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
     } else {
-        strncpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
+        mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
         buf[buf_len - 1] = '\0';
     }
 }
@@ -1016,115 +1135,6 @@ struct mg_request_info *mg_get_request_info(struct mg_connection *conn)
     return &conn->request_info;
 }
 
-static void mg_strlcpy(register char *dst, register const char *src, size_t n)
-{
-    for (; *src != '\0' && n > 1; n--) {
-        *dst++ = *src++;
-    }
-    *dst = '\0';
-}
-
-static int lowercase(const char *s)
-{
-    return tolower(* (const unsigned char *) s);
-}
-
-int mg_strncasecmp(const char *s1, const char *s2, size_t len)
-{
-    int diff = 0;
-
-    if (len > 0)
-        do {
-            diff = lowercase(s1++) - lowercase(s2++);
-        } while (diff == 0 && s1[-1] != '\0' && --len > 0);
-
-    return diff;
-}
-
-static int mg_strcasecmp(const char *s1, const char *s2)
-{
-    int diff;
-
-    do {
-        diff = lowercase(s1++) - lowercase(s2++);
-    } while (diff == 0 && s1[-1] != '\0');
-
-    return diff;
-}
-
-static char * mg_strndup(const char *ptr, size_t len)
-{
-    char *p;
-
-    if ((p = (char *) mg_malloc(len + 1)) != NULL) {
-        mg_strlcpy(p, ptr, len + 1);
-    }
-
-    return p;
-}
-
-static char * mg_strdup(const char *str)
-{
-    return mg_strndup(str, strlen(str));
-}
-
-static const char *mg_strcasestr(const char *big_str, const char *small_str)
-{
-    int i, big_len = (int)strlen(big_str), small_len = (int)strlen(small_str);
-
-    for (i = 0; i <= big_len - small_len; i++) {
-        if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
-            return big_str + i;
-        }
-    }
-
-    return NULL;
-}
-
-/* Like snprintf(), but never returns negative value, or a value
-   that is larger than a supplied buffer.
-   Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability
-   in his audit report. */
-static int mg_vsnprintf(struct mg_connection *conn, char *buf, size_t buflen,
-                        const char *fmt, va_list ap)
-{
-    int n;
-
-    if (buflen == 0)
-        return 0;
-
-    n = vsnprintf(buf, buflen, fmt, ap);
-
-    if (n < 0) {
-        mg_cry(conn, "vsnprintf error");
-        n = 0;
-    } else if (n >= (int) buflen) {
-        mg_cry(conn, "truncating vsnprintf buffer: [%.*s]",
-               n > 200 ? 200 : n, buf);
-        n = (int) buflen - 1;
-    }
-    buf[n] = '\0';
-
-    return n;
-}
-
-static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
-                       PRINTF_FORMAT_STRING(const char *fmt), ...)
-PRINTF_ARGS(4, 5);
-
-static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
-                       const char *fmt, ...)
-{
-    va_list ap;
-    int n;
-
-    va_start(ap, fmt);
-    n = mg_vsnprintf(conn, buf, buflen, fmt, ap);
-    va_end(ap);
-
-    return n;
-}
-
 /* Skip the characters until one of the delimiters characters found.
    0-terminate resulting word. Skip the delimiter and following whitespaces.
    Advance pointer to buffer to the next word. Return found 0-terminated word.
@@ -1301,6 +1311,9 @@ static const char *suggest_connection_header(const struct mg_connection *conn)
     return should_keep_alive(conn) ? "keep-alive" : "close";
 }
 
+static void handle_file_based_request(struct mg_connection *conn, const char *path, struct file *filep);
+static int mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
+
 static void send_http_error(struct mg_connection *, int, const char *,
                             PRINTF_FORMAT_STRING(const char *fmt), ...)
 PRINTF_ARGS(4, 5);
@@ -1311,27 +1324,72 @@ static void send_http_error(struct mg_connection *conn, int status,
 {
     char buf[MG_BUF_LEN];
     va_list ap;
-    int len = 0;
+    int len = 0, i, page_handler_found, scope;
     char date[64];
     time_t curtime = time(NULL);
+    const char *error_handler = NULL;
+    struct file error_page_file = STRUCT_FILE_INITIALIZER;
+    const char *error_page_file_ext, *tstr;
 
     conn->status_code = status;
-    if (conn->ctx->callbacks.http_error == NULL ||
+    if (conn->in_error_handler ||
+        conn->ctx->callbacks.http_error == NULL ||
         conn->ctx->callbacks.http_error(conn, status)) {
-        buf[0] = '\0';
 
+        if (!conn->in_error_handler) {
+            /* Send user defined error pages, if defined */
+            error_handler = conn->ctx->config[ERROR_PAGES];
+            error_page_file_ext = conn->ctx->config[INDEX_FILES];
+            page_handler_found = 0;
+            if (error_handler != NULL) {
+                for (scope=1; (scope<=3) && !page_handler_found; scope++) {
+                    switch (scope) {
+                    case 1:
+                        len = mg_snprintf(conn, buf, sizeof(buf)-32, "%serror%03u.", error_handler, status);
+                        break;
+                    case 2:
+                        len = mg_snprintf(conn, buf, sizeof(buf)-32, "%serror%01uxx.", error_handler, status/100);
+                        break;
+                    default:
+                        len = mg_snprintf(conn, buf, sizeof(buf)-32, "%serror.", error_handler);
+                        break;
+                    }
+                    tstr = strchr(error_page_file_ext, '.');
+                    while (tstr) {
+                        for (i=1; i<32 && tstr[i]!=0 && tstr[i]!=','; i++) buf[len+i-1]=tstr[i];
+                        buf[len+i-1]=0;
+                        if (mg_stat(conn, buf, &error_page_file)) {
+                            page_handler_found = 1;
+                            break;
+                        }
+                        tstr = strchr(tstr+i, '.');
+                    }
+                }
+            }
+
+            if (page_handler_found) {
+                conn->in_error_handler = 1;
+                handle_file_based_request(conn, buf, &error_page_file);
+                conn->in_error_handler = 0;
+                return;
+            }
+        }
+
+        buf[0] = '\0';
         gmt_time_string(date, sizeof(date), &curtime);
 
         /* Errors 1xx, 204 and 304 MUST NOT send a body */
         if (status > 199 && status != 204 && status != 304) {
-            len = mg_snprintf(conn, buf, sizeof(buf), "Error %d: %s", status, reason);
-            buf[len++] = '\n';
+            len = mg_snprintf(conn, buf, sizeof(buf)-1, "Error %d: %s", status, reason);
+            buf[len] = '\n';
+            len++;
+            buf[len] = 0;
 
             va_start(ap, fmt);
             len += mg_vsnprintf(conn, buf + len, sizeof(buf) - len, fmt, ap);
             va_end(ap);
         }
-        DEBUG_TRACE(("[%s]", buf));
+        DEBUG_TRACE("[%s]", buf);
 
         mg_printf(conn, "HTTP/1.1 %d %s\r\n"
                         "Content-Length: %d\r\n"
@@ -1603,8 +1661,7 @@ static int path_cannot_disclose_cgi(const char *path)
     return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
 }
 
-static int mg_stat(struct mg_connection *conn, const char *path,
-                   struct file *filep)
+static int mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
 {
     wchar_t wbuf[PATH_MAX];
     WIN32_FILE_ATTRIBUTE_DATA info;
@@ -1804,7 +1861,7 @@ static int mg_join_thread(pthread_t threadid)
         int err;
 
         err = GetLastError();
-        DEBUG_TRACE(("WaitForSingleObject() failed, error %d", err));
+        DEBUG_TRACE("WaitForSingleObject() failed, error %d", err);
     } else {
         if (dwevent == WAIT_OBJECT_0) {
             CloseHandle(threadid);
@@ -1910,7 +1967,7 @@ static pid_t spawn_process(struct mg_connection *conn, const char *prog,
     mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%s\"%s\\%s\"",
                 interp, interp[0] == '\0' ? "" : " ", full_dir, prog);
 
-    DEBUG_TRACE(("Running [%s]", cmdline));
+    DEBUG_TRACE("Running [%s]", cmdline);
     if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE,
                        CREATE_NEW_PROCESS_GROUP, envblk, NULL, &si, &pi) == 0) {
         mg_cry(conn, "%s: CreateProcess(%s): %ld",
@@ -2649,7 +2706,7 @@ static time_t parse_date_string(const char *datetime)
     static const unsigned short days_before_month[] = {
         0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
     };
-    char month_str[32];
+    char month_str[32]={0};
     int second, minute, hour, day, month, year, leap_days, days;
     time_t result = (time_t) 0;
 
@@ -3006,6 +3063,9 @@ static int parse_auth_header(struct mg_connection *conn, char *buf,
     /* Convert the nonce from the client to a number and check it. */
     /* Server side nonce check is valuable in all situations but one: if the server restarts frequently,
        but the client should not see that, so the server should accept nonces from previous starts. */
+    if (ah->nonce == NULL) {
+        return 0;
+    }
     nonce = strtoul(ah->nonce, &s, 10);
     if ((s == NULL) || (*s != 0)) {
         return 0;
@@ -3038,9 +3098,7 @@ static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p)
 
     if (filep->membuf != NULL && *p != NULL) {
         memend = (char *) &filep->membuf[filep->size];
-        eof = (char *) memchr(*p, '\n', memend - *p); /* Search for \n from p
-                                                         till the end of
-                                                         stream */
+        eof = (char *) memchr(*p, '\n', memend - *p); /* Search for \n from p till the end of stream */
         if (eof != NULL) {
             eof += 1; /* Include \n */
         } else {
@@ -3071,9 +3129,12 @@ static int authorize(struct mg_connection *conn, struct file *filep)
     /* Loop over passwords file */
     p = (char *) filep->membuf;
     while (mg_fgets(line, sizeof(line), filep, &p) != NULL) {
-        if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) != 3) {
+        if (sscanf(line, "%255[^:]:%255[^:]:%255s", f_user, f_domain, ha1) != 3) {
             continue;
         }
+        f_user[255]=0;
+        f_domain[255]=0;
+        ha1[255]=0;
 
         if (!strcmp(ah.user, f_user) &&
             !strcmp(conn->ctx->config[AUTHENTICATION_DOMAIN], f_domain))
@@ -3162,8 +3223,8 @@ static int is_authorized_for_put(struct mg_connection *conn)
 int mg_modify_passwords_file(const char *fname, const char *domain,
                              const char *user, const char *pass)
 {
-    int found;
-    char line[512], u[512] = "", d[512] ="", ha1[33], tmp[PATH_MAX+1];
+    int found, i;
+    char line[512], u[512] = "", d[512] ="", ha1[33], tmp[PATH_MAX+8];
     FILE *fp, *fp2;
 
     found = 0;
@@ -3174,6 +3235,25 @@ int mg_modify_passwords_file(const char *fname, const char *domain,
         pass = NULL;
     }
 
+    /* Other arguments must not be empty */
+    if (fname == NULL || domain == NULL || user == NULL) return 0;
+
+    /* Using the given file format, user name and domain must not contain ':' */
+    if (strchr(user, ':') != NULL) return 0;
+    if (strchr(domain, ':') != NULL) return 0;
+
+    /* Do not allow control characters like newline in user name and domain.
+       Do not allow excessively long names either. */
+    for (i=0; user[i]!=0 && i<255; i++) {
+        if (iscntrl(user[i])) return 0;
+    }
+    if (user[i]) return 0;
+    for (i=0; domain[i]!=0 && i<255; i++) {
+        if (iscntrl(domain[i])) return 0;
+    }
+    if (domain[i]) return 0;
+
+    /* Create a temporary file name */
     (void) snprintf(tmp, sizeof(tmp) - 1, "%s.tmp", fname);
     tmp[sizeof(tmp) - 1] = 0;
 
@@ -3192,9 +3272,11 @@ int mg_modify_passwords_file(const char *fname, const char *domain,
 
     /* Copy the stuff to temporary file */
     while (fgets(line, sizeof(line), fp) != NULL) {
-        if (sscanf(line, "%[^:]:%[^:]:%*s", u, d) != 2) {
+        if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
             continue;
         }
+        u[255]=0;
+        d[255]=0;
 
         if (!strcmp(u, user) && !strcmp(d, domain)) {
             found++;
@@ -3308,7 +3390,7 @@ static void print_dir_entry(struct de *de)
     if (tm != NULL) {
         strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
     } else {
-        strncpy(mod, "01-Jan-1970 00:00", sizeof(mod));
+        mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
         mod[sizeof(mod) - 1] = '\0';
     }
     mg_url_encode(de->file_name, href, sizeof(href));
@@ -3613,8 +3695,7 @@ static void fclose_on_exec(struct file *filep, struct mg_connection *conn)
     }
 }
 
-static void handle_file_request(struct mg_connection *conn, const char *path,
-                                struct file *filep)
+static void handle_static_file_request(struct mg_connection *conn, const char *path, struct file *filep)
 {
     char date[64], lm[64], etag[64], range[64];
     const char *msg = "OK", *hdr;
@@ -3713,7 +3794,7 @@ void mg_send_file(struct mg_connection *conn, const char *path)
 {
     struct file file = STRUCT_FILE_INITIALIZER;
     if (mg_stat(conn, path, &file)) {
-        handle_file_request(conn, path, &file);
+        handle_static_file_request(conn, path, &file);
     } else {
         send_http_error(conn, 404, "Not Found", "%s", "File not found");
     }
@@ -4036,6 +4117,11 @@ static void prepare_cgi_environment(struct mg_connection *conn,
         addenv(blk, "PATH_INFO=%s", conn->path_info);
     }
 
+    if (conn->status_code > 0) {
+        /* CGI error handler should show the status code */
+        addenv(blk, "STATUS=%d", conn->status_code);
+    }
+
 #if defined(_WIN32)
     if ((s = getenv("COMSPEC")) != NULL) {
         addenv(blk, "COMSPEC=%s", s);
@@ -4284,7 +4370,7 @@ static int put_dir(struct mg_connection *conn, const char *path)
         buf[len] = '\0';
 
         /* Try to create intermediate directory */
-        DEBUG_TRACE(("mkdir(%s)", buf));
+        DEBUG_TRACE("mkdir(%s)", buf);
         if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
             res = -1;
             break;
@@ -4394,24 +4480,27 @@ static void send_ssi_file(struct mg_connection *, const char *,
 static void do_ssi_include(struct mg_connection *conn, const char *ssi,
                            char *tag, int include_level)
 {
-    char file_name[MG_BUF_LEN], path[PATH_MAX], *p;
+    char file_name[MG_BUF_LEN], path[512], *p;
     struct file file = STRUCT_FILE_INITIALIZER;
     size_t len;
 
     /* sscanf() is safe here, since send_ssi_file() also uses buffer
        of size MG_BUF_LEN to get the tag. So strlen(tag) is
        always < MG_BUF_LEN. */
-    if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
+    if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
         /* File name is relative to the webserver root */
+        file_name[511]=0;
         (void) mg_snprintf(conn, path, sizeof(path), "%s%c%s",
                            conn->ctx->config[DOCUMENT_ROOT], '/', file_name);
-    } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
+    } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
         /* File name is relative to the webserver working directory
            or it is absolute system path */
+        file_name[511]=0;
         (void) mg_snprintf(conn, path, sizeof(path), "%s", file_name);
-    } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
-               sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
+    } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1 ||
+               sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
         /* File name is relative to the currect document */
+        file_name[511]=0;
         (void) mg_snprintf(conn, path, sizeof(path), "%s", ssi);
         if ((p = strrchr(path, '/')) != NULL) {
             p[1] = '\0';
@@ -4441,16 +4530,19 @@ static void do_ssi_include(struct mg_connection *conn, const char *ssi,
 #if !defined(NO_POPEN)
 static void do_ssi_exec(struct mg_connection *conn, char *tag)
 {
-    char cmd[MG_BUF_LEN] = "";
+    char cmd[1024] = "";
     struct file file = STRUCT_FILE_INITIALIZER;
 
-    if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
+    if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
         mg_cry(conn, "Bad SSI #exec: [%s]", tag);
-    } else if ((file.fp = popen(cmd, "r")) == NULL) {
-        mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
     } else {
-        send_file_data(conn, &file, 0, INT64_MAX);
-        pclose(file.fp);
+        cmd[1023]=0;
+        if ((file.fp = popen(cmd, "r")) == NULL) {
+            mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
+        } else {
+            send_file_data(conn, &file, 0, INT64_MAX);
+            pclose(file.fp);
+        }
     }
 }
 #endif /* !NO_POPEN */
@@ -4935,7 +5027,7 @@ static void read_websocket(struct mg_connection *conn)
             }
         }
 
-        if (header_len > 0) {
+        if (header_len > 0 && body_len >= header_len) {
             /* Allocate space to hold websocket payload */
             data = mem;
             if (data_len > sizeof(mem)) {
@@ -5222,6 +5314,7 @@ int mg_upload(struct mg_connection *conn, const char *destination_dir)
         return num_uploaded_files;
     }
 
+    boundary[99]=0;
     boundary_len = (int)strlen(boundary);
     bl = boundary_len + 4;  /* \r\n--<boundary> */
     for (;;) {
@@ -5243,6 +5336,7 @@ int mg_upload(struct mg_connection *conn, const char *destination_dir)
                    parse the header properly instead. */
                 IGNORE_UNUSED_RESULT(sscanf(&buf[j], "Content-Disposition: %*s %*s filename=\"%1023[^\"]",
                                             fname));
+                fname[1023]=0;
                 j = i + 2;
             }
         }
@@ -5335,7 +5429,7 @@ static void redirect_to_https_port(struct mg_connection *conn, int ssl_index)
     if (host_header != NULL) {
         char *pos;
 
-        strncpy(host, host_header, hostlen);
+        mg_strlcpy(host, host_header, hostlen);
         host[hostlen - 1] = '\0';
         pos = strchr(host, ':');
         if (pos != NULL) {
@@ -5475,7 +5569,7 @@ static void handle_request(struct mg_connection *conn)
     conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
                                   get_remote_ip(conn), ri->uri);
 
-    DEBUG_TRACE(("%s", ri->uri));
+    DEBUG_TRACE("%s", ri->uri);
     /* Perform redirect and auth checks before calling begin_request() handler.
        Otherwise, begin_request() would need to perform auth checks and
        redirects. */
@@ -5550,12 +5644,20 @@ static void handle_request(struct mg_connection *conn)
             send_http_error(conn, 403, "Directory Listing Denied",
                             "Directory listing denied");
         }
+    } else {
+        handle_file_based_request(conn, path, &file);
+    }
+}
+
+static void handle_file_based_request(struct mg_connection *conn, const char *path, struct file *file)
+{
+    if (0) {
 #ifdef USE_LUA
     } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
                             (int)strlen(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
                             path) > 0) {
         /* Lua server page: an SSI like page containing mostly plain html code plus some tags with server generated contents. */
-        handle_lsp_request(conn, path, &file, NULL);
+        handle_lsp_request(conn, path, file, NULL);
     } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
                             (int)strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
                             path) > 0) {
@@ -5573,10 +5675,10 @@ static void handle_request(struct mg_connection *conn)
                             (int)strlen(conn->ctx->config[SSI_EXTENSIONS]),
                             path) > 0) {
         handle_ssi_file_request(conn, path);
-    } else if (is_not_modified(conn, &file)) {
+    } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
         send_http_error(conn, 304, "Not Modified", "%s", "");
     } else {
-        handle_file_request(conn, path, &file);
+        handle_static_file_request(conn, path, file);
     }
 }
 
@@ -5585,6 +5687,7 @@ static void close_all_listening_sockets(struct mg_context *ctx)
     int i;
     for (i = 0; i < ctx->num_listening_sockets; i++) {
         closesocket(ctx->listening_sockets[i].sock);
+        ctx->listening_sockets[i].sock = INVALID_SOCKET;
     }
     mg_free(ctx->listening_sockets);
     ctx->listening_sockets=0;
@@ -5602,9 +5705,10 @@ static int is_valid_port(unsigned int port)
    TODO(lsm): add parsing of the IPv6 address */
 static int parse_port_string(const struct vec *vec, struct socket *so)
 {
-    unsigned int a, b, c, d, ch, len, port;
+    unsigned int a, b, c, d, port;
+    int  ch, len;
 #if defined(USE_IPV6)
-    char buf[100];
+    char buf[100]={0};
 #endif
 
     /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
@@ -5618,7 +5722,6 @@ static int parse_port_string(const struct vec *vec, struct socket *so)
         so->lsa.sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
         so->lsa.sin.sin_port = htons((uint16_t) port);
 #if defined(USE_IPV6)
-
     } else if (sscanf(vec->ptr, "[%49[^]]]:%d%n", buf, &port, &len) == 2 &&
                inet_pton(AF_INET6, buf, &so->lsa.sin6.sin6_addr)) {
         /* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */
@@ -5632,6 +5735,7 @@ static int parse_port_string(const struct vec *vec, struct socket *so)
         port = len = 0;   /* Parsing failure. Make port invalid. */
     }
 
+    assert((len>=0) && ((unsigned)len<=(unsigned)vec->len)); /* sscanf and the option splitting code ensure this condition */
     ch = vec->ptr[len];  /* Next character after the port number */
     so->is_ssl = ch == 's';
     so->ssl_redir = ch == 'r';
@@ -5685,17 +5789,20 @@ static int set_ports_option(struct mg_context *ctx)
                    (int) vec.len, vec.ptr, ERRNO, strerror(errno));
             if (so.sock != INVALID_SOCKET) {
                 closesocket(so.sock);
+                so.sock = INVALID_SOCKET;
             }
             success = 0;
         } else if ((ptr = (struct socket *) mg_realloc(ctx->listening_sockets,
                           (ctx->num_listening_sockets + 1) *
                           sizeof(ctx->listening_sockets[0]))) == NULL) {
             closesocket(so.sock);
+            so.sock = INVALID_SOCKET;
             success = 0;
         } else if ((portPtr = (in_port_t*) mg_realloc(ctx->listening_ports,
                           (ctx->num_listening_sockets + 1) *
                           sizeof(ctx->listening_ports[0]))) == NULL) {
             closesocket(so.sock);
+            so.sock = INVALID_SOCKET;
             success = 0;
         }
         else {
@@ -5744,7 +5851,7 @@ static void log_access(const struct mg_connection *conn)
     if (tm != NULL) {
         strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
     } else {
-        strncpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
+        mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
         date[sizeof(date) - 1] = '\0';
     }
 
@@ -6029,6 +6136,7 @@ static void close_socket_gracefully(struct mg_connection *conn)
 
     /* Now we know that our FIN is ACK-ed, safe to close */
     closesocket(conn->client.sock);
+    conn->client.sock = INVALID_SOCKET;
 }
 
 static void close_connection(struct mg_connection *conn)
@@ -6088,11 +6196,13 @@ struct mg_connection *mg_connect(const char *host, int port, int use_ssl,
                        mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
         snprintf(ebuf, ebuf_len, "calloc(): %s", strerror(ERRNO));
         closesocket(sock);
+        sock = INVALID_SOCKET;
 #ifndef NO_SSL
     } else if (use_ssl && (conn->client_ssl_ctx =
                                SSL_CTX_new(SSLv23_client_method())) == NULL) {
         snprintf(ebuf, ebuf_len, "SSL_CTX_new error");
         closesocket(sock);
+        sock = INVALID_SOCKET;
         mg_free(conn);
         conn = NULL;
 #endif /* NO_SSL */
@@ -6254,7 +6364,7 @@ static void process_new_connection(struct mg_connection *conn)
 static int consume_socket(struct mg_context *ctx, struct socket *sp)
 {
     (void) pthread_mutex_lock(&ctx->mutex);
-    DEBUG_TRACE(("going idle"));
+    DEBUG_TRACE("going idle");
 
     /* If the queue is empty, wait. We're idle at this point. */
     while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
@@ -6266,7 +6376,7 @@ static int consume_socket(struct mg_context *ctx, struct socket *sp)
         /* Copy socket from the queue and increment tail */
         *sp = ctx->queue[ctx->sq_tail % ARRAY_SIZE(ctx->queue)];
         ctx->sq_tail++;
-        DEBUG_TRACE(("grabbed socket %d, going busy", sp->sock));
+        DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
 
         /* Wrap pointers if needed */
         while (ctx->sq_tail > (int) ARRAY_SIZE(ctx->queue)) {
@@ -6346,7 +6456,7 @@ static void *worker_thread_run(void *thread_func_param)
 #endif
     mg_free(conn);
 
-    DEBUG_TRACE(("exiting"));
+    DEBUG_TRACE("exiting");
     return NULL;
 }
 
@@ -6381,7 +6491,7 @@ static void produce_socket(struct mg_context *ctx, const struct socket *sp)
         /* Copy socket to the queue and increment head */
         ctx->queue[ctx->sq_head % ARRAY_SIZE(ctx->queue)] = *sp;
         ctx->sq_head++;
-        DEBUG_TRACE(("queued socket %d", sp->sock));
+        DEBUG_TRACE("queued socket %d", sp->sock);
     }
 
     (void) pthread_cond_signal(&ctx->sq_full);
@@ -6414,9 +6524,10 @@ static void accept_new_connection(const struct socket *listener,
         sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
         mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
         closesocket(so.sock);
+        so.sock = INVALID_SOCKET;
     } else {
         /* Put so socket structure into the queue */
-        DEBUG_TRACE(("Accepted socket %d", (int) so.sock));
+        DEBUG_TRACE("Accepted socket %d", (int) so.sock);
         set_close_on_exec(so.sock, fc(ctx));
         so.is_ssl = listener->is_ssl;
         so.ssl_redir = listener->ssl_redir;
@@ -6497,7 +6608,7 @@ static void master_thread_run(void *thread_func_param)
         }
     }
     mg_free(pfd);
-    DEBUG_TRACE(("stopping workers"));
+    DEBUG_TRACE("stopping workers");
 
     /* Stop signal received: somebody called mg_stop. Quit. */
     close_all_listening_sockets(ctx);
@@ -6518,16 +6629,10 @@ static void master_thread_run(void *thread_func_param)
         mg_join_thread(ctx->workerthreadids[i]);
     }
 
-    /* All threads exited, no sync is needed. Destroy mutex and condvars */
-    (void) pthread_mutex_destroy(&ctx->mutex);
-    (void) pthread_cond_destroy(&ctx->cond);
-    (void) pthread_cond_destroy(&ctx->sq_empty);
-    (void) pthread_cond_destroy(&ctx->sq_full);
-
 #if !defined(NO_SSL)
     uninitialize_ssl(ctx);
 #endif
-    DEBUG_TRACE(("exiting"));
+    DEBUG_TRACE("exiting");
 
 #if defined(_WIN32) && !defined(__SYMBIAN32__)
     CloseHandle(tls.pthread_cond_helper_mutex);
@@ -6564,6 +6669,12 @@ static void free_context(struct mg_context *ctx)
     if (ctx == NULL)
         return;
 
+    /* All threads exited, no sync is needed. Destroy mutex and condvars */
+    (void) pthread_mutex_destroy(&ctx->mutex);
+    (void) pthread_cond_destroy(&ctx->cond);
+    (void) pthread_cond_destroy(&ctx->sq_empty);
+    (void) pthread_cond_destroy(&ctx->sq_full);
+
     /* Deallocate config parameters */
     for (i = 0; i < NUM_OPTIONS; i++) {
         if (ctx->config[i] != NULL)
@@ -6715,7 +6826,7 @@ struct mg_context *mg_start(const struct mg_callbacks *callbacks,
             mg_free(ctx->config[i]);
         }
         ctx->config[i] = mg_strdup(value);
-        DEBUG_TRACE(("[%s] -> [%s]", name, value));
+        DEBUG_TRACE("[%s] -> [%s]", name, value);
     }
 
     /* Set default value if needed */

+ 397 - 25
src/main.c

@@ -77,17 +77,22 @@ extern char *_getcwd(char *buf, size_t size);
 #define MAX_OPTIONS 100
 #define MAX_CONF_FILE_LINE_SIZE (8 * 1024)
 
-static int exit_flag;
+static int exit_flag = 0;               /* Main loop should exit */
 static char server_base_name[40];       /* Set by init_server_name() */
 static char *server_name;               /* Set by init_server_name() */
 static char *icon_name;                 /* Set by init_server_name() */
 static char config_file[PATH_MAX] = ""; /* Set by process_command_line_arguments() */
 static struct mg_context *ctx;          /* Set by start_civetweb() */
+static int guard = 0;                   /* test if any dialog is already open */
 
 #if !defined(CONFIG_FILE)
 #define CONFIG_FILE "civetweb.conf"
 #endif /* !CONFIG_FILE */
 
+#if !defined(PASSWORDS_FILE_NAME)
+#define PASSWORDS_FILE_NAME ".htpasswd"
+#endif
+
 /* backup config file */
 #if !defined(CONFIG_FILE2) && defined(LINUX)
 #define CONFIG_FILE2 "/usr/local/etc/civetweb.conf"
@@ -129,18 +134,17 @@ static void die(const char *fmt, ...)
     exit(EXIT_FAILURE);
 }
 
+#ifdef WIN32
+static int MakeConsole();
+#endif
+
 static void show_usage_and_exit(void)
 {
     const struct mg_option *options;
     int i;
 
 #ifdef WIN32
-    if (!AttachConsole(ATTACH_PARENT_PROCESS)) {
-        AllocConsole();
-        AttachConsole(GetCurrentProcessId());
-    }
-    freopen("CON", "a", stdout);
-    freopen("CON", "a", stderr);
+    MakeConsole();
 #endif
 
     fprintf(stderr, "Civetweb v%s, built on %s\n",
@@ -168,7 +172,7 @@ static void show_usage_and_exit(void)
 static const char *config_file_top_comment =
     "# Civetweb web server configuration file.\n"
     "# For detailed description of every option, visit\n"
-    "# https://github.com/sunsetbrew/civetweb/blob/master/docs/UserManual.md\n"
+    "# https://github.com/bel2125/civetweb/blob/master/docs/UserManual.md\n"
     "# Lines starting with '#' and empty lines are ignored.\n"
     "# To make a change, remove leading '#', modify option's value,\n"
     "# save this file and then restart Civetweb.\n\n";
@@ -575,9 +579,10 @@ static void start_civetweb(int argc, char *argv[])
 #ifdef _WIN32
 enum {
     ID_ICON = 100, ID_QUIT, ID_SETTINGS, ID_SEPARATOR, ID_INSTALL_SERVICE,
-    ID_REMOVE_SERVICE, ID_STATIC, ID_GROUP,
+    ID_REMOVE_SERVICE, ID_STATIC, ID_GROUP, ID_PASSWORD,
     ID_SAVE, ID_RESET_DEFAULTS, ID_RESET_FILE, ID_RESET_ACTIVE,
-    ID_STATUS, ID_CONNECT,
+    ID_STATUS, ID_CONNECT, ID_ADD_USER, ID_ADD_USER_NAME, ID_ADD_USER_REALM,
+    ID_INPUT_LINE,
 
     /* All dynamically created text boxes for options have IDs starting from
        ID_CONTROLS, incremented by one. */
@@ -622,7 +627,6 @@ static void WINAPI ServiceMain(void)
     SetServiceStatus(hStatus, &ss);
 }
 
-
 static void show_error(void)
 {
     char buf[256];
@@ -667,7 +671,7 @@ static void save_config(HWND hDlg, FILE *fp)
     }
 }
 
-static BOOL CALLBACK DlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP)
+static BOOL CALLBACK SettingsDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP)
 {
     FILE *fp;
     int i, j;
@@ -740,7 +744,7 @@ static BOOL CALLBACK DlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP)
                     CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes") ?
                                    BST_CHECKED : BST_UNCHECKED);
                 } else {
-                    SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value);
+                    SetDlgItemText(hDlg, ID_CONTROLS + i, value == NULL ? "" : value);
                 }
             }
             break;
@@ -781,8 +785,8 @@ static BOOL CALLBACK DlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP)
         break;
 
     case WM_INITDIALOG:
-        SendMessage(hDlg, WM_SETICON,(WPARAM) ICON_SMALL, (LPARAM) hIcon);
-        SendMessage(hDlg, WM_SETICON,(WPARAM) ICON_BIG, (LPARAM) hIcon);
+        SendMessage(hDlg, WM_SETICON, (WPARAM) ICON_SMALL, (LPARAM) hIcon);
+        SendMessage(hDlg, WM_SETICON, (WPARAM) ICON_BIG, (LPARAM) hIcon);
         title = malloc(strlen(server_name)+16);
         if (title) {
             strcpy(title, server_name);
@@ -791,18 +795,229 @@ static BOOL CALLBACK DlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP)
             free(title);
         }
         SetFocus(GetDlgItem(hDlg, ID_SAVE));
-        for (i = 0; default_options[i].name != NULL; i++) {
-            name = default_options[i].name;
-            value = mg_get_option(ctx, name);
-            if (default_options[i].type == CONFIG_TYPE_BOOLEAN) {
-                CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes") ?
-                               BST_CHECKED : BST_UNCHECKED);
-            } else {
-                SetDlgItemText(hDlg, ID_CONTROLS + i, value == NULL ? "" : value);
+
+        /* Init dialog with active settings */
+        SendMessage(hDlg, WM_COMMAND, ID_RESET_ACTIVE, 0);
+        /* alternative: SendMessage(hDlg, WM_COMMAND, ID_RESET_FILE, 0); */
+        break;
+
+    default:
+        break;
+    }
+
+    return FALSE;
+}
+
+struct tstring_input_buf {
+    unsigned buflen;
+    char * buffer;
+};
+
+static BOOL CALLBACK InputDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP)
+{
+    static struct tstring_input_buf *inBuf = 0;
+    WORD ctrlId;
+
+    switch (msg) {
+    case WM_CLOSE:
+        inBuf = 0;
+        DestroyWindow(hDlg);
+        break;
+
+    case WM_COMMAND:
+        ctrlId = LOWORD(wParam);
+        if (ctrlId == IDOK) {
+            /* Add user */
+            GetWindowText(GetDlgItem(hDlg, ID_INPUT_LINE), inBuf->buffer, inBuf->buflen);
+            if (strlen(inBuf->buffer)>0) {
+                EndDialog(hDlg, IDOK);
             }
+        } else if (ctrlId == IDCANCEL) {
+            EndDialog(hDlg, IDCANCEL);
         }
         break;
 
+    case WM_INITDIALOG:
+        inBuf = (struct tstring_input_buf *) lP;
+        assert(inBuf != NULL);
+        assert((inBuf->buffer != NULL) && (inBuf->buflen != 0));
+        assert(strlen(inBuf->buffer) < inBuf->buflen);
+        SendMessage(hDlg, WM_SETICON, (WPARAM) ICON_SMALL, (LPARAM) hIcon);
+        SendMessage(hDlg, WM_SETICON, (WPARAM) ICON_BIG, (LPARAM) hIcon);
+        SendDlgItemMessage(hDlg, ID_INPUT_LINE, EM_LIMITTEXT, inBuf->buflen-1, 0);
+        SetWindowText(GetDlgItem(hDlg, ID_INPUT_LINE), inBuf->buffer);
+        SetWindowText(hDlg, "Modify password");
+        SetFocus(GetDlgItem(hDlg, ID_INPUT_LINE));
+        break;
+
+    default:
+        break;
+    }
+
+    return FALSE;
+}
+
+void suggest_passwd(char *passwd)
+{
+    unsigned u;
+    char * p;
+    union {
+        FILETIME ft;
+        LARGE_INTEGER li;
+    } num;
+
+    /* valid characters are 32 to 126 */
+    GetSystemTimeAsFileTime(&num.ft);
+    num.li.HighPart |= GetCurrentProcessId();
+    p = passwd;
+    while (num.li.QuadPart) {
+        u = (unsigned)(num.li.QuadPart % 95);
+        num.li.QuadPart -= u;
+        num.li.QuadPart /= 95;
+        *p = (char)(u+32);
+        p++;
+    }
+}
+
+static void add_control(unsigned char **mem, DLGTEMPLATE *dia, WORD type,
+                        DWORD id, DWORD style, WORD x, WORD y,
+                        WORD cx, WORD cy, const char *caption);
+
+static int get_password(const char * user, const char * realm, char * passwd, unsigned passwd_len)
+{
+#define HEIGHT 15
+#define WIDTH 280
+#define LABEL_WIDTH 90
+
+    HWND hDlg = NULL;
+    unsigned char mem[4096], *p;
+    DLGTEMPLATE *dia = (DLGTEMPLATE *) mem;
+    int ok, y;
+    struct tstring_input_buf dlgprms = {passwd_len, passwd};
+
+    static struct {
+        DLGTEMPLATE template; /* 18 bytes */
+        WORD menu, class;
+        wchar_t caption[1];
+        WORD fontsiz;
+        wchar_t fontface[7];
+    } dialog_header = {{
+        WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE |
+            DS_SETFONT | WS_DLGFRAME, WS_EX_TOOLWINDOW, 0, 200, 200, WIDTH, 0
+    },
+    0, 0, L"", 8, L"Tahoma"
+    };
+
+    assert((user!=NULL) && (realm!=NULL) && (passwd!=NULL));
+
+    if (guard < 100) {
+        guard += 100;
+    } else {
+        return 0;
+    }
+
+    /* Create a password suggestion */
+    memset(passwd, 0, passwd_len);
+    suggest_passwd(passwd);
+
+    /* Create the dialog */
+    (void) memset(mem, 0, sizeof(mem));
+    (void) memcpy(mem, &dialog_header, sizeof(dialog_header));
+    p = mem + sizeof(dialog_header);
+
+    y = HEIGHT;
+    add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD,
+        10, y, LABEL_WIDTH, HEIGHT, "User:");
+    add_control(&p, dia, 0x81, ID_CONTROLS + 1,
+        WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_DISABLED,
+        15+LABEL_WIDTH, y, WIDTH - LABEL_WIDTH - 25, HEIGHT, user);
+
+    y += HEIGHT;
+    add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD,
+        10, y, LABEL_WIDTH, HEIGHT, "Realm:");
+    add_control(&p, dia, 0x81, ID_CONTROLS + 2,
+        WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_DISABLED,
+        15+LABEL_WIDTH, y, WIDTH - LABEL_WIDTH - 25, HEIGHT, realm);
+
+    y += HEIGHT;
+    add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD,
+        10, y, LABEL_WIDTH, HEIGHT, "Password:");
+    add_control(&p, dia, 0x81, ID_INPUT_LINE,
+        WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_TABSTOP,
+        15+LABEL_WIDTH, y, WIDTH - LABEL_WIDTH - 25, HEIGHT, "");
+
+    y += (WORD)(HEIGHT * 2);
+    add_control(&p, dia, 0x80, IDOK,
+        WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
+        80, y, 55, 12, "Ok");
+    add_control(&p, dia, 0x80, IDCANCEL,
+        WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
+        140, y, 55, 12, "Cancel");
+
+    assert((int)p - (int)mem < sizeof(mem));
+
+    dia->cy = y + (WORD)(HEIGHT * 1.5);
+
+    ok = (IDOK == DialogBoxIndirectParam(NULL, dia, NULL, InputDlgProc, (LPARAM) &dlgprms));
+
+    guard -= 100;
+
+    return ok;
+
+#undef HEIGHT
+#undef WIDTH
+#undef LABEL_WIDTH
+}
+
+static BOOL CALLBACK PasswordDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP)
+{
+    static const char *passfile = 0;
+    char domain[256], user[256], password[256];
+    WORD ctrlId;
+
+    switch (msg) {
+    case WM_CLOSE:
+        passfile = 0;
+        DestroyWindow(hDlg);
+        break;
+
+    case WM_COMMAND:
+        ctrlId = LOWORD(wParam);
+        if (ctrlId == ID_ADD_USER) {
+            /* Add user */
+            GetWindowText(GetDlgItem(hDlg, ID_ADD_USER_NAME), user, sizeof(user));
+            GetWindowText(GetDlgItem(hDlg, ID_ADD_USER_REALM), domain, sizeof(domain));
+            if (get_password(user, domain, password, sizeof(password))) {
+                mg_modify_passwords_file(passfile, domain, user, password);
+                EndDialog(hDlg, IDOK);
+            }
+        } else if ((ctrlId>=(ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 3)) &&
+                   (ctrlId<(ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 4))) {
+            /* Modify password */
+            GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 3), user, sizeof(user));
+            GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 2), domain, sizeof(domain));
+            if (get_password(user, domain, password, sizeof(password))) {
+                mg_modify_passwords_file(passfile, domain, user, password);
+                EndDialog(hDlg, IDOK);
+            }
+        } else if ((ctrlId>=(ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 2)) &&
+                   (ctrlId<(ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 3))) {
+            /* Remove user */
+            GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 2), user, sizeof(user));
+            GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA), domain, sizeof(domain));
+            mg_modify_passwords_file(passfile, domain, user, NULL);
+            EndDialog(hDlg, IDOK);
+        }
+        break;
+
+    case WM_INITDIALOG:
+        passfile = (const char *)lP;
+        SendMessage(hDlg, WM_SETICON, (WPARAM) ICON_SMALL, (LPARAM) hIcon);
+        SendMessage(hDlg, WM_SETICON, (WPARAM) ICON_BIG, (LPARAM) hIcon);
+        SetWindowText(hDlg, passfile);
+        SetFocus(GetDlgItem(hDlg, ID_ADD_USER_NAME));
+        break;
+
     default:
         break;
     }
@@ -855,7 +1070,6 @@ static void show_settings_dialog()
     DWORD style;
     DLGTEMPLATE *dia = (DLGTEMPLATE *) mem;
     WORD i, cl, x, y, width, nelems = 0;
-    static int guard = 0; /* test if dialog is already open */
 
     static struct {
         DLGTEMPLATE template; /* 18 bytes */
@@ -939,8 +1153,139 @@ static void show_settings_dialog()
     assert((int)p - (int)mem < sizeof(mem));
 
     dia->cy = ((nelems + 1) / 2 + 1) * HEIGHT + 30;
-    DialogBoxIndirectParam(NULL, dia, NULL, DlgProc, (LPARAM) NULL);
+    DialogBoxIndirectParam(NULL, dia, NULL, SettingsDlgProc, (LPARAM) NULL);
+    guard--;
+
+#undef HEIGHT
+#undef WIDTH
+#undef LABEL_WIDTH
+}
+
+static void change_password_file()
+{
+#define HEIGHT 15
+#define WIDTH 320
+#define LABEL_WIDTH 90
+
+    OPENFILENAME of;
+    char path[PATH_MAX] = PASSWORDS_FILE_NAME;
+    char strbuf[256], u[256], d[256];
+    HWND hDlg = NULL;
+    FILE * f;
+    int y, nelems;
+    unsigned char mem[4096], *p;
+    DLGTEMPLATE *dia = (DLGTEMPLATE *) mem;
+    const char * domain = mg_get_option(ctx, "authentication_domain");
+
+    static struct {
+        DLGTEMPLATE template; /* 18 bytes */
+        WORD menu, class;
+        wchar_t caption[1];
+        WORD fontsiz;
+        wchar_t fontface[7];
+    } dialog_header = {{
+            WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE |
+            DS_SETFONT | WS_DLGFRAME, WS_EX_TOOLWINDOW, 0, 200, 200, WIDTH, 0
+        },
+        0, 0, L"", 8, L"Tahoma"
+    };
+
+    if (guard == 0) {
+        guard++;
+    } else {
+        return;
+    }
+
+    memset(&of, 0, sizeof(of));
+    of.lStructSize = sizeof(of);
+    of.hwndOwner = (HWND) hDlg;
+    of.lpstrFile = path;
+    of.nMaxFile = sizeof(path);
+    of.lpstrInitialDir = mg_get_option(ctx, "document_root");
+    of.Flags = OFN_CREATEPROMPT | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
+
+    if (IDOK != GetSaveFileName(&of)) {
+        guard--;
+        return;
+    }
+
+    f = fopen(path, "a+");
+    if (f) {
+        fclose(f);
+    } else {
+        MessageBox(NULL, path, "Can not open file", MB_ICONERROR);
+        guard--;
+        return;
+    }
+
+    do {
+        (void) memset(mem, 0, sizeof(mem));
+        (void) memcpy(mem, &dialog_header, sizeof(dialog_header));
+        p = mem + sizeof(dialog_header);
+
+        f = fopen(path, "r+");
+        if (!f) {
+            MessageBox(NULL, path, "Can not open file", MB_ICONERROR);
+            guard--;
+            return;
+        }
+
+        nelems = 0;
+        while (fgets(strbuf, sizeof(strbuf), f)) {
+            if (sscanf(strbuf, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
+                continue;
+            }
+            u[255]=0;
+            d[255]=0;
+            y = (nelems + 1) * HEIGHT + 5;
+            add_control(&p, dia, 0x80, ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA * 3,
+                WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
+                10, y, 65, 12, "Modify password");
+            add_control(&p, dia, 0x80, ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA * 2,
+                WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
+                80, y, 55, 12, "Remove user");
+            add_control(&p, dia, 0x81, ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA,
+                WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_DISABLED,
+                245, y, 60, 12, d);
+            add_control(&p, dia, 0x81, ID_CONTROLS + nelems,
+                WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_DISABLED,
+                140, y, 100, 12, u);
+
+            nelems++;
+            assert((int)p - (int)mem < sizeof(mem));
+        }
+        fclose(f);
+
+        y = (WORD) ((nelems + 1) * HEIGHT + 10);
+        add_control(&p, dia, 0x80, ID_ADD_USER,
+            WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
+            80, y, 55, 12, "Add user");
+        add_control(&p, dia, 0x81, ID_ADD_USER_NAME,
+            WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_TABSTOP,
+            140, y, 100, 12, "");
+        add_control(&p, dia, 0x81, ID_ADD_USER_REALM,
+            WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_TABSTOP,
+            245, y, 60, 12, domain);
+
+        y = (WORD) ((nelems + 2) * HEIGHT + 10);
+        add_control(&p, dia, 0x80, ID_GROUP, WS_CHILD | WS_VISIBLE |
+            BS_GROUPBOX, 5, 5, WIDTH - 10, y, " Users ");
+
+        y += HEIGHT;
+        add_control(&p, dia, 0x82, ID_STATIC,
+            WS_CHILD | WS_VISIBLE | WS_DISABLED,
+            5, y, 100, 12, server_base_name);
+
+        assert((int)p - (int)mem < sizeof(mem));
+
+        dia->cy = y + 20;
+    } while ((IDOK == DialogBoxIndirectParam(NULL, dia, NULL, PasswordDlgProc, (LPARAM) path)) && (!exit_flag));
+
     guard--;
+
+#undef HEIGHT
+#undef WIDTH
+#undef LABEL_WIDTH
 }
 
 static int manage_service(int action)
@@ -1017,11 +1362,15 @@ static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam,
         case ID_QUIT:
             mg_stop(ctx);
             Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
+            exit_flag = 1;
             PostQuitMessage(0);
             return 0;
         case ID_SETTINGS:
             show_settings_dialog();
             break;
+        case ID_PASSWORD:
+            change_password_file();
+            break;
         case ID_INSTALL_SERVICE:
         case ID_REMOVE_SERVICE:
             manage_service(LOWORD(wParam));
@@ -1053,6 +1402,7 @@ static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam,
             AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
             AppendMenu(hMenu, MF_STRING, ID_CONNECT, "Start browser");
             AppendMenu(hMenu, MF_STRING, ID_SETTINGS, "Edit settings");
+            AppendMenu(hMenu, MF_STRING, ID_PASSWORD, "Modify password file");
             AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
             AppendMenu(hMenu, MF_STRING, ID_QUIT, "Exit");
             GetCursorPos(&pt);
@@ -1066,6 +1416,7 @@ static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam,
     case WM_CLOSE:
         mg_stop(ctx);
         Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
+        exit_flag = 1;
         PostQuitMessage(0);
         return 0;/* We've just sent our own quit message, with proper hwnd. */
     default:
@@ -1076,6 +1427,27 @@ static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam,
     return DefWindowProc(hWnd, msg, wParam, lParam);
 }
 
+static int MakeConsole() {
+    DWORD err;
+    int ok = (GetConsoleWindow() != NULL);
+    if (!ok) {
+        if (!AttachConsole(ATTACH_PARENT_PROCESS)) {
+            FreeConsole();
+            if (!AllocConsole()) {
+                err = GetLastError();
+                if (err==ERROR_ACCESS_DENIED) {
+                    MessageBox(NULL, "Insufficient rights to create a console window", "Error", MB_ICONERROR);
+                }
+            }
+            AttachConsole(GetCurrentProcessId());
+        }
+        freopen("CON", "a", stdout);
+        freopen("CON", "a", stderr);
+        ok = (GetConsoleWindow() != NULL);
+    }
+    return ok;
+}
+
 int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show)
 {
     WNDCLASS cls;

+ 5 - 0
src/mod_lua.inl

@@ -784,6 +784,11 @@ static void prepare_lua_environment(struct mg_connection *conn, lua_State *L, co
     reg_boolean(L, "https", conn->ssl != NULL);
     reg_string(L, "script_name", script_name);
 
+    if (conn->status_code > 0) {
+        /* Lua error handler should show the status code */
+        reg_int(L, "status", conn->status_code);
+    }
+
     lua_rawset(L, -3);
     lua_setglobal(L, "mg");
 

+ 12 - 0
test/error.lua

@@ -0,0 +1,12 @@
+mg.write("HTTP/1.0 200 OK\r\n")
+mg.write("Content-Type: text/html\r\n")
+mg.write("\r\n")
+mg.write([[<html><body>
+  <p>Lua error handler:</p>
+  <p>Status code: ]])
+
+mg.write(tostring(mg.request_info.status))
+
+mg.write([[</p>
+</body></html>
+]])

+ 10 - 0
test/error4xx.htm

@@ -0,0 +1,10 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
+   "http://www.w3.org/TR/html4/frameset.dtd">
+<HTML>
+<HEAD>
+<TITLE>Error</TITLE>
+</HEAD>
+<BODY>
+Custom error page
+</BODY>
+</HTML>

+ 42 - 0
test/unit_test.c

@@ -806,6 +806,47 @@ static void test_parse_port_string(void) {
     }
 }
 
+static void test_md5(void) {
+
+    md5_state_t md5_state;
+    unsigned char md5_val[16+1];
+    char md5_str[32+1];
+    const char *test_str = "The quick brown fox jumps over the lazy dog";
+
+    md5_val[16]=0;
+    md5_init(&md5_state);
+    md5_finish(&md5_state, md5_val);
+    ASSERT(strcmp(md5_val, "\xd4\x1d\x8c\xd9\x8f\x00\xb2\x04\xe9\x80\x09\x98\xec\xf8\x42\x7e")==0);
+    sprintf(md5_str, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
+        md5_val[0], md5_val[1], md5_val[2], md5_val[3],
+        md5_val[4], md5_val[5], md5_val[6], md5_val[7],
+        md5_val[8], md5_val[9], md5_val[10], md5_val[11],
+        md5_val[12], md5_val[13], md5_val[14], md5_val[15]);
+    ASSERT(strcmp(md5_str, "d41d8cd98f00b204e9800998ecf8427e")==0);
+
+    mg_md5(md5_str, "", NULL);
+    ASSERT(strcmp(md5_str, "d41d8cd98f00b204e9800998ecf8427e")==0);
+
+    md5_init(&md5_state);
+    md5_append(&md5_state, test_str, strlen(test_str));
+    md5_finish(&md5_state, md5_val);
+    sprintf(md5_str, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
+        md5_val[0], md5_val[1], md5_val[2], md5_val[3],
+        md5_val[4], md5_val[5], md5_val[6], md5_val[7],
+        md5_val[8], md5_val[9], md5_val[10], md5_val[11],
+        md5_val[12], md5_val[13], md5_val[14], md5_val[15]);
+    ASSERT(strcmp(md5_str, "9e107d9d372bb6826bd81d3542a419d6")==0);
+
+    mg_md5(md5_str, test_str, NULL);
+    ASSERT(strcmp(md5_str, "9e107d9d372bb6826bd81d3542a419d6")==0);
+
+    mg_md5(md5_str, "The", " ", "quick brown fox", "", " jumps ", "over the lazy dog", "", "", NULL);
+    ASSERT(strcmp(md5_str, "9e107d9d372bb6826bd81d3542a419d6")==0);
+
+    mg_md5(md5_str, "civetweb", NULL);
+    ASSERT(strcmp(md5_str, "95c098bd85b619b24a83d9cea5e8ba54")==0);
+}
+
 int __cdecl main(void) {
 
     char buffer[512];
@@ -850,6 +891,7 @@ int __cdecl main(void) {
     test_url_decode();
     test_mg_get_cookie();
     test_strtoll();
+    test_md5();
 
     /* start stop server */
     ctx = mg_start(NULL, NULL, OPTIONS);