+
+
+
diff --git a/src/civetweb/test/README.md b/src/civetweb/test/README.md
new file mode 100644
index 00000000..49f2245d
--- /dev/null
+++ b/src/civetweb/test/README.md
@@ -0,0 +1,25 @@
+Testing
+=======
+
+C API
+-----
+
+The unit tests leverage the CTest and Check frameworks to provide a easy
+environment to build up unit tests. They are split into Public and Private
+test suites reflecting the public and internal API functions of civetweb.
+
+When adding new functionality to civetweb tests should be written so that the
+new functionality will be tested across the continuous build servers. There
+are various levels of the unit tests:
+
+ * Tests are included in
+ * Test Cases which are there are multiple in
+ * Test Suites which are ran by the check framework by
+ * `civetweb-unit-tests` which is driven using the `--suite` and
+ `--test-case` arguments by
+ * CTest via `add_test` in `CMakeLists.txt`
+
+Each test suite and test case is ran individually by CTest so that it provides
+good feedback to the continuous integration servers and also CMake. Adding a
+new test case or suite will require the corresponding `add_test` driver to be
+added to `CMakeLists.txt`
diff --git a/src/civetweb/test/ajax/echo.cgi b/src/civetweb/test/ajax/echo.cgi
new file mode 100644
index 00000000..577c4bd5
--- /dev/null
+++ b/src/civetweb/test/ajax/echo.cgi
@@ -0,0 +1,8 @@
+#!/bin/sh
+
+echo "Content-Type: text/plain; charset=utf-8"
+echo "Connection: close"
+echo "Cache-Control: no-cache"
+echo ""
+
+echo "{}"
diff --git a/src/civetweb/test/ajax/echo.cgi.old b/src/civetweb/test/ajax/echo.cgi.old
new file mode 100644
index 00000000..3f4eeebc
--- /dev/null
+++ b/src/civetweb/test/ajax/echo.cgi.old
@@ -0,0 +1,73 @@
+#!/usr/bin/lua5.1
+
+-- Every CGI script that returns any valid JSON object will work in the test.
+-- In case you do not have not yet used CGI, you may want to use this script which is written in Lua.
+-- You may download an interpreter from http://luabinaries.sourceforge.net/download.html, extract it
+-- to some folder in your search path (the path of the webserver or /usr/bin on Linux), and add the
+-- following lines to your .conf file.
+-- cgi_interpreter c:\somewhere\lua5.1.exe
+-- enable_keep_alive yes
+
+resp = "{";
+
+method = os.getenv("REQUEST_METHOD")
+uri = os.getenv("REQUEST_URI");
+query = os.getenv("QUERY_STRING");
+datalen = os.getenv("CONTENT_LENGTH");
+
+if method then
+ resp = resp .. '"method" : "' .. method .. '", ';
+end
+if uri then
+ resp = resp .. '"uri" : "' .. uri .. '", ';
+end
+if query then
+ resp = resp .. '"query" : "' .. query .. '", ';
+end
+if datalen then
+ resp = resp .. '"datalen" : "' .. datalen .. '", ';
+end
+
+resp = resp .. '"time" : "' .. os.date() .. '" ';
+
+resp = resp .. "}";
+
+
+
+
+print "Status: 200 OK"
+print "Connection: close"
+--print "Connection: keep-alive"
+print "Content-Type: text/html; charset=utf-8"
+print "Cache-Control: no-cache"
+--print ("Content-Length: " .. resp:len())
+print ""
+
+print (resp)
+
+
+doLogging = false
+
+if (doLogging) then
+ -- Store the POST data to a file
+ if (method == "POST") then
+ myFile = io.open("data" .. query:sub(4) .. ".txt", "wb");
+ myFile:write(resp)
+ myFile:write("\r\n\r\n")
+ if datalen then
+ datalen = tonumber(datalen)
+ myFile:write("<<< " .. datalen .. " bytes of data >>>\r\n")
+
+ data = io.stdin:read(datalen)
+ myFile:write(data)
+
+ myFile:write("\r\n<<< end >>>\r\n")
+ else
+ myFile:write("<<< no data >>>\r\n")
+ end
+ myFile:close()
+ end
+end
+
+
+
diff --git a/src/civetweb/test/ajax/echo.lp b/src/civetweb/test/ajax/echo.lp
new file mode 100644
index 00000000..7276f813
--- /dev/null
+++ b/src/civetweb/test/ajax/echo.lp
@@ -0,0 +1,9 @@
+
+-- This *.lp file simply runs the *.lua file in the same directory.
+n = string.match(mg.request_info.uri, "^(.*)%.lp$")
+if mg.system:find("Windows") then
+ n = string.gsub(n, [[/]], [[\]])
+end
+n = mg.document_root .. n .. ".lua"
+dofile(n)
+?>
\ No newline at end of file
diff --git a/src/civetweb/test/ajax/echo.lua b/src/civetweb/test/ajax/echo.lua
new file mode 100644
index 00000000..13175162
--- /dev/null
+++ b/src/civetweb/test/ajax/echo.lua
@@ -0,0 +1,35 @@
+resp = "{";
+
+method = mg.request_info.request_method
+uri = mg.request_info.uri
+query = mg.request_info.query_string
+datalen = nil -- TODO: "CONTENT_LENGTH" !
+
+if method then
+ resp = resp .. '"method" : "' .. method .. '", ';
+end
+if uri then
+ resp = resp .. '"uri" : "' .. uri .. '", ';
+end
+if query then
+ resp = resp .. '"query" : "' .. query .. '", ';
+end
+if datalen then
+ resp = resp .. '"datalen" : "' .. datalen .. '", ';
+end
+
+resp = resp .. '"time" : "' .. os.date() .. '" ';
+
+resp = resp .. "}";
+
+
+
+mg.write("HTTP/1.1 200 OK\r\n")
+mg.write("Connection: close\r\n")
+mg.write("Content-Type: text/html\r\n")
+mg.write("Cache-Control: no-cache\r\n")
+--mg.write("Content-Length: " .. resp:len() .. "\n")
+mg.write("\r\n")
+
+mg.write(resp)
+
diff --git a/src/civetweb/test/ajax/jquery.js b/src/civetweb/test/ajax/jquery.js
new file mode 100644
index 00000000..198b3ff0
--- /dev/null
+++ b/src/civetweb/test/ajax/jquery.js
@@ -0,0 +1,4 @@
+/*! jQuery v1.7.1 jquery.com | jquery.org/license */
+(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cv(a){if(!ck[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cl||(cl=c.createElement("iframe"),cl.frameBorder=cl.width=cl.height=0),b.appendChild(cl);if(!cm||!cl.createElement)cm=(cl.contentWindow||cl.contentDocument).document,cm.write((c.compatMode==="CSS1Compat"?"":"")+""),cm.close();d=cm.createElement(a),cm.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cl)}ck[a]=e}return ck[a]}function cu(a,b){var c={};f.each(cq.concat.apply([],cq.slice(0,b)),function(){c[this]=a});return c}function ct(){cr=b}function cs(){setTimeout(ct,0);return cr=f.now()}function cj(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ci(){try{return new a.XMLHttpRequest}catch(b){}}function cc(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g0){if(c!=="border")for(;g=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.1",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c
a",d=q.getElementsByTagName("*"),e=q.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=q.getElementsByTagName("input")[0],b={leadingWhitespace:q.firstChild.nodeType===3,tbody:!q.getElementsByTagName("tbody").length,htmlSerialize:!!q.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:q.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete q.test}catch(s){b.deleteExpando=!1}!q.addEventListener&&q.attachEvent&&q.fireEvent&&(q.attachEvent("onclick",function(){b.noCloneEvent=!1}),q.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),q.appendChild(i),k=c.createDocumentFragment(),k.appendChild(q.lastChild),b.checkClone=k.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,k.removeChild(i),k.appendChild(q),q.innerHTML="",a.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",q.style.width="2px",q.appendChild(j),b.reliableMarginRight=(parseInt((a.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(q.attachEvent)for(o in{submit:1,change:1,focusin:1})n="on"+o,p=n in q,p||(q.setAttribute(n,"return;"),p=typeof q[n]=="function"),b[o+"Bubbles"]=p;k.removeChild(q),k=g=h=j=q=i=null,f(function(){var a,d,e,g,h,i,j,k,m,n,o,r=c.getElementsByTagName("body")[0];!r||(j=1,k="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",m="visibility:hidden;border:0;",n="style='"+k+"border:5px solid #000;padding:0;'",o="
+
+
+
diff --git a/src/civetweb/test/civetweb_check.h b/src/civetweb/test/civetweb_check.h
new file mode 100644
index 00000000..4701f225
--- /dev/null
+++ b/src/civetweb/test/civetweb_check.h
@@ -0,0 +1,96 @@
+/* Copyright (c) 2015-2017 the Civetweb developers
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+#ifndef TEST_CIVETWEB_CHECK_H_
+#define TEST_CIVETWEB_CHECK_H_
+
+#ifdef __clang__
+#pragma clang diagnostic push
+// FIXME: check uses GCC specific variadic macros that are non-standard
+#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
+#endif
+
+#if defined(__MINGW__) || defined(__GNUC__)
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wall"
+/* Disable warnings for defining _CRT_SECURE_NO_* (here) and
+ * _CHECK_CHECK_STDINT_H (in check.h)
+ */
+/* Disable until Warning returns to Travis CI or AppVeyor
+#pragma GCC diagnostic ignored "-Wunknown-pragmas"
+#pragma GCC diagnostic ignored "-Wno-variadic-macros"
+#pragma GCC diagnostic ignored "-Wreserved-id-macro"
+*/
+#endif
+
+#ifdef _MSC_VER
+#undef pid_t
+#define pid_t int
+/* Unreferenced formal parameter. START_TEST has _i */
+#pragma warning(disable : 4100)
+/* conditional expression is constant . asserts use while(0) */
+#pragma warning(disable : 4127)
+#endif
+#include
+
+/* All unit tests use the "check" framework.
+ * Download from https://libcheck.github.io/check/
+ */
+#include "check.h"
+
+#if (CHECK_MINOR_VERSION < 11)
+#ifndef LOCAL_TEST
+#error "CivetWeb unit tests require at least check 0.11.0"
+#endif
+#endif
+
+#ifdef __clang__
+#pragma clang diagnostic pop
+#endif
+
+#if !defined(_CRT_SECURE_NO_WARNINGS)
+#define _CRT_SECURE_NO_WARNINGS
+#endif
+#if !defined(_CRT_SECURE_NO_DEPRECATE)
+#define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#if defined(__MINGW__) || defined(__GNUC__)
+#pragma GCC diagnostic pop
+#endif
+
+#ifdef __clang__
+/* When using -Weverything, clang does not accept it's own headers
+ * in a release build configuration. Disable what is too much in
+ * -Weverything. */
+#pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
+#endif
+
+/* A minimal timeout used for all tests with the "check" framework. */
+#define civetweb_min_test_timeout (30)
+
+/* A minimal timeout for all tests starting a server. */
+#define civetweb_min_server_test_timeout (civetweb_min_test_timeout + 30)
+
+/* A default timeout for all tests running multiple requests to a server. */
+#define civetweb_mid_server_test_timeout \
+ (civetweb_min_server_test_timeout + 180)
+
+#endif /* TEST_CIVETWEB_CHECK_H_ */
diff --git a/src/civetweb/test/cors.html b/src/civetweb/test/cors.html
new file mode 100644
index 00000000..10fb99ac
--- /dev/null
+++ b/src/civetweb/test/cors.html
@@ -0,0 +1,75 @@
+
+
+
+CORS test
+
+
+
+
+
+
+
Cross-origin resource sharing test
+
*** Error: Javascript is not activated. This test will not work. ***
This is another example of a Lua server page, served by
+CivetWeb web server.
+
+The following features are available:
+
+
+ mg.write("
" .. _VERSION .. " server pages
")
+ if sqlite3 then
+ mg.write("
sqlite3 binding
")
+ end
+ if lfs then
+ mg.write("
lua file system
")
+ end
+?>
+
+
Today is mg.write(os.date("%A")) ?>
+
URI is mg.write(mg.request_info.uri) ?>
+
URI is =mg.request_info.uri?>
+
+
Database example:
+
+
+ -- Open database
+ local db = sqlite3.open('requests.db')
+ -- Note that the data base is located in the current working directory
+ -- of the process if no other path is given here.
+
+ -- Setup a trace callback, to show SQL statements we'll be executing.
+ -- db:trace(function(data, sql) mg.write('Executing: ', sql: '\n') end, nil)
+
+ -- Create a table if it is not created already
+ db:exec([[
+ CREATE TABLE IF NOT EXISTS requests (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ timestamp NOT NULL,
+ method NOT NULL,
+ uri NOT NULL,
+ addr
+ );
+ ]])
+
+ -- Add entry about this request
+ local stmt = db:prepare(
+ 'INSERT INTO requests VALUES(NULL, datetime("now"), ?, ?, ?);');
+ stmt:bind_values(mg.request_info.request_method,
+ mg.request_info.uri,
+ mg.request_info.remote_port)
+ stmt:step()
+ stmt:finalize()
+
+ -- Show all previous records
+ mg.write('Previous requests:\n')
+ stmt = db:prepare('SELECT * FROM requests ORDER BY id DESC;')
+ while stmt:step() == sqlite3.ROW do
+ local v = stmt:get_values()
+ mg.write(v[1] .. ' ' .. v[2] .. ' ' .. v[3] .. ' '
+ .. v[4] .. ' ' .. v[5] .. '\n')
+ end
+
+ -- Close database
+ db:close()
+?>
+
This is another example of a Lua script, creating a web page served by the
+CivetWeb web server.
+
+The following features are available:
+
+]])
+
+ mg.write("
" .. _VERSION .. " server pages
")
+ if sqlite3 then
+ mg.write("
sqlite3 binding
")
+ end
+ if lfs then
+ mg.write("
lua file system
")
+ end
+
+
+mg.write("
\r\n")
+mg.write("
Today is " .. os.date("%A") .. "
\r\n")
+mg.write("
URI is " .. mg.request_info.uri .. "
\r\n")
+
+mg.write("
Database example:\r\n
\r\n")
+
+ -- Open database
+ local db = sqlite3.open('requests.db')
+ -- Note that the data base is located in the current working directory
+ -- of the process if no other path is given here.
+
+ -- Setup a trace callback, to show SQL statements we'll be executing.
+ -- db:trace(function(data, sql) mg.write('Executing: ', sql: '\n') end, nil)
+
+ -- Create a table if it is not created already
+ db:exec([[
+ CREATE TABLE IF NOT EXISTS requests (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ timestamp NOT NULL,
+ method NOT NULL,
+ uri NOT NULL,
+ addr
+ );
+ ]])
+
+ -- Add entry about this request
+ local stmt = db:prepare(
+ 'INSERT INTO requests VALUES(NULL, datetime("now"), ?, ?, ?);');
+ stmt:bind_values(mg.request_info.request_method,
+ mg.request_info.uri,
+ mg.request_info.remote_port)
+ stmt:step()
+ stmt:finalize()
+
+ -- Show all previous records
+ mg.write('Previous requests:\n')
+ stmt = db:prepare('SELECT * FROM requests ORDER BY id DESC;')
+ while stmt:step() == sqlite3.ROW do
+ local v = stmt:get_values()
+ mg.write(v[1] .. ' ' .. v[2] .. ' ' .. v[3] .. ' '
+ .. v[4] .. ' ' .. v[5] .. '\n')
+ end
+
+ -- Close database
+ db:close()
+
+mg.write([[
+
+
+]])
diff --git a/src/civetweb/test/page6.lua b/src/civetweb/test/page6.lua
new file mode 100644
index 00000000..dc304397
--- /dev/null
+++ b/src/civetweb/test/page6.lua
@@ -0,0 +1,16 @@
+mg.write("HTTP/1.0 200 OK\r\n")
+mg.write("Content-Type: text/plain\r\n")
+mg.write("\r\n")
+mg.write(mg.request_info.request_method .. " " .. mg.request_info.request_uri .. " HTTP/" .. mg.request_info.http_version .. "\r\n")
+for k,v in pairs(mg.request_info.http_headers) do
+ mg.write(k .. ": " .. v .. "\r\n")
+end
+mg.write("\r\n")
+
+repeat
+ local r = mg.read()
+ if (r) then
+ mg.write(r)
+ end
+until not r
+
diff --git a/src/civetweb/test/page_keep_alive.lua b/src/civetweb/test/page_keep_alive.lua
new file mode 100644
index 00000000..d869ce46
--- /dev/null
+++ b/src/civetweb/test/page_keep_alive.lua
@@ -0,0 +1,34 @@
+-- Set keep_alive. The return value specifies if this is possible at all.
+canKeepAlive = mg.keep_alive(true)
+
+if canKeepAlive then
+ -- Create the entire response in a string variable first. Content-Length will be set to the length of this string.
+ reply = [[
+
+
This is a Lua script supporting html keep-alive with the
+ CivetWeb web server.
+
+
It works by setting the Content-Length header field properly.
+
+ ]]
+else
+ reply = "
Keep alive not possible!"
+end
+
+-- First send the http headers
+mg.write("HTTP/1.1 200 OK\r\n")
+mg.write("Content-Type: text/html\r\n")
+mg.write("Date: " .. os.date("!%a, %d %b %Y %H:%M:%S") .. " GMT\r\n")
+mg.write("Cache-Control: no-cache\r\n")
+
+if canKeepAlive then
+ mg.write("Content-Length: " .. tostring(string.len(reply)) .. "\r\n")
+ mg.write("Connection: keep-alive\r\n")
+else
+ mg.write("Connection: close\r\n")
+end
+mg.write("\r\n")
+
+-- Finally send the content
+mg.write(reply)
+
diff --git a/src/civetweb/test/page_keep_alive_chunked.lua b/src/civetweb/test/page_keep_alive_chunked.lua
new file mode 100644
index 00000000..28ac7d12
--- /dev/null
+++ b/src/civetweb/test/page_keep_alive_chunked.lua
@@ -0,0 +1,66 @@
+-- Set keep_alive. The return value specifies if this is possible at all.
+canKeepAlive = mg.keep_alive(true)
+now = os.date("!%a, %d %b %Y %H:%M:%S")
+
+-- First send the http headers
+mg.write("HTTP/1.1 200 OK\r\n")
+mg.write("Content-Type: text/html\r\n")
+mg.write("Date: " .. now .. " GMT\r\n")
+mg.write("Cache-Control: no-cache\r\n")
+mg.write("Last-Modified: " .. now .. " GMT\r\n")
+if not canKeepAlive then
+ mg.write("Connection: close\r\n")
+ mg.write("\r\n")
+ mg.write("Keep alive not possible!")
+ return
+end
+if mg.request_info.http_version ~= "1.1" then
+ -- wget will use HTTP/1.0 and Connection: keep-alive, so chunked transfer is not possible
+ mg.write("Connection: close\r\n")
+ mg.write("\r\n")
+ mg.write("Chunked transfer is only possible for HTTP/1.1 requests!")
+ mg.keep_alive(false)
+ return
+end
+
+-- use chunked encoding (http://www.jmarshall.com/easy/http/#http1.1c2)
+mg.write("Cache-Control: max-age=0, must-revalidate\r\n")
+--mg.write("Cache-Control: no-cache\r\n")
+--mg.write("Cache-Control: no-store\r\n")
+mg.write("Connection: keep-alive\r\n")
+mg.write("Transfer-Encoding: chunked\r\n")
+mg.write("\r\n")
+
+-- function to send a chunk
+function send(str)
+ local len = string.len(str)
+ mg.write(string.format("%x\r\n", len))
+ mg.write(str.."\r\n")
+end
+
+-- send the chunks
+send("")
+send("Civetweb Lua script chunked transfer test page")
+send("\n")
+
+fileCnt = 0
+if lfs then
+ send("Files in " .. lfs.currentdir())
+ send('\n
\n')
+ send('
name
type
size
\n')
+ for f in lfs.dir(".") do
+ local at = lfs.attributes(f);
+ if at then
+ send('
' .. f .. '
' .. at.mode .. '
' .. at.size .. '
\n')
+ end
+ fileCnt = fileCnt + 1
+ end
+ send("
\n")
+end
+
+send(fileCnt .. " entries (" .. now .. " GMT)\n")
+send("")
+send("")
+
+-- end
+send("")
diff --git a/src/civetweb/test/page_status.lua b/src/civetweb/test/page_status.lua
new file mode 100644
index 00000000..3c9b0eb7
--- /dev/null
+++ b/src/civetweb/test/page_status.lua
@@ -0,0 +1,38 @@
+mg.write("HTTP/1.0 200 OK\r\n")
+
+-- MIME type: https://www.ietf.org/rfc/rfc4627.txt, chapter 6
+mg.write("Content-Type: application/json\r\n")
+
+mg.write("\r\n")
+
+num_threads = mg.get_option("num_threads")
+num_threads = tonumber(num_threads)
+
+
+function n(s)
+ if ((type(s) == "string") and (#s > 0)) then
+ return s
+ else
+ return "null"
+ end
+end
+
+
+mg.write("{\r\n\"system\" :\r\n")
+
+mg.write(n(mg.get_info("system")))
+
+mg.write(",\r\n\"summary\" :\r\n")
+mg.write(n(mg.get_info("context")))
+mg.write(",\r\n\"common\" :\r\n")
+mg.write(n(mg.get_info("common")))
+mg.write(",\r\n\"connections\" :\r\n[\r\n")
+
+ mg.write(n(mg.get_info("connection", 1)))
+
+for i=2,num_threads do
+ mg.write(",\r\n")
+ mg.write(n(mg.get_info("connection", i)))
+end
+mg.write("]\r\n}\r\n")
+
diff --git a/src/civetweb/test/passfile b/src/civetweb/test/passfile
new file mode 100644
index 00000000..58c313a7
--- /dev/null
+++ b/src/civetweb/test/passfile
@@ -0,0 +1,3 @@
+guest:mydomain.com:485264dcc977a1925370b89d516a1477
+Administrator:mydomain.com:e32daa3028eba04dc53e2d781e6fc983
+
diff --git a/src/civetweb/test/prime.ssjs b/src/civetweb/test/prime.ssjs
new file mode 100644
index 00000000..6dc3243a
--- /dev/null
+++ b/src/civetweb/test/prime.ssjs
@@ -0,0 +1,36 @@
+// prime.js
+
+// Pure Ecmascript version of low level helper
+function primeCheckEcmascript(val, limit) {
+ for (var i = 2; i <= limit; i++) {
+ if ((val % i) == 0) { return false; }
+ }
+ return true;
+}
+
+// Select available helper at load time
+var primeCheckHelper = (this.primeCheckNative || primeCheckEcmascript);
+
+// Check 'val' for primality
+function primeCheck(val) {
+ if (val == 1 || val == 2) { return true; }
+ var limit = Math.ceil(Math.sqrt(val));
+ while (limit * limit < val) { limit += 1; }
+ return primeCheckHelper(val, limit);
+}
+
+function primeTest() {
+ var res = [];
+
+ print('Have native helper: ' + (primeCheckHelper !== primeCheckEcmascript) + '\n');
+ for (var i = 2; i <= 1000; i++) {
+ if (primeCheck(i)) { res.push(i); }
+ }
+ print(res.join(' '));
+}
+
+print = this.send || conn.write
+
+print('HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n');
+
+primeTest();
diff --git a/src/civetweb/test/private.c b/src/civetweb/test/private.c
new file mode 100644
index 00000000..9b34f595
--- /dev/null
+++ b/src/civetweb/test/private.c
@@ -0,0 +1,1018 @@
+/* Copyright (c) 2015-2017 the Civetweb developers
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+/**
+ * We include the source file so that we have access to the internal private
+ * static functions
+ */
+#ifdef _MSC_VER
+#ifndef _CRT_SECURE_NO_WARNINGS
+#define _CRT_SECURE_NO_WARNINGS
+#endif
+#define CIVETWEB_API static
+#endif
+
+#ifdef REPLACE_CHECK_FOR_LOCAL_DEBUGGING
+#undef MEMORY_DEBUGGING
+#endif
+
+#include "../src/civetweb.c"
+
+#include
+#include
+
+#include "private.h"
+
+
+/* This unit test file uses the excellent Check unit testing library.
+ * The API documentation is available here:
+ * http://check.sourceforge.net/doc/check_html/index.html
+ */
+
+static char tmp_parse_buffer[1024];
+
+static int
+test_parse_http_response(char *buf, int len, struct mg_response_info *ri)
+{
+ ck_assert_int_lt(len, (int)sizeof(tmp_parse_buffer));
+ memcpy(tmp_parse_buffer, buf, (size_t)len);
+ return parse_http_response(tmp_parse_buffer, len, ri);
+}
+
+static int
+test_parse_http_request(char *buf, int len, struct mg_request_info *ri)
+{
+ ck_assert_int_lt(len, (int)sizeof(tmp_parse_buffer));
+ memcpy(tmp_parse_buffer, buf, (size_t)len);
+ return parse_http_request(tmp_parse_buffer, len, ri);
+}
+
+
+START_TEST(test_parse_http_message)
+{
+ /* Adapted from unit_test.c */
+ /* Copyright (c) 2013-2015 the Civetweb developers */
+ /* Copyright (c) 2004-2013 Sergey Lyubka */
+ struct mg_request_info ri;
+ struct mg_response_info respi;
+ char empty[] = "";
+ char space[] = " \x00";
+ char req1[] = "GET / HTTP/1.1\r\n\r\n";
+ char req2[] = "BLAH / HTTP/1.1\r\n\r\n";
+ char req3[] = "GET / HTTP/1.1\nKey: Val\n\n";
+ char req4[] =
+ "GET / HTTP/1.1\r\nA: foo bar\r\nB: bar\r\nskip\r\nbaz:\r\n\r\n";
+ char req5[] = "GET / HTTP/1.0\n\n";
+ char req6[] = "G";
+ char req7[] = " blah ";
+ char req8[] = "HTTP/1.0 404 Not Found\n\n";
+ char req9[] = "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n";
+
+ char req10[] = "GET / HTTP/1.1\r\nA: foo bar\r\nB: bar\r\n\r\n";
+
+ char req11[] = "GET /\r\nError: X\r\n\r\n";
+
+ char req12[] =
+ "POST /a/b/c.d?e=f&g HTTP/1.1\r\nKey1: val1\r\nKey2: val2\r\n\r\nBODY";
+
+
+ int lenreq1 = (int)strlen(req1);
+ int lenreq2 = (int)strlen(req2);
+ int lenreq3 = (int)strlen(req3);
+ int lenreq4 = (int)strlen(req4);
+ int lenreq5 = (int)strlen(req5);
+ int lenreq6 = (int)strlen(req6);
+ int lenreq7 = (int)strlen(req7);
+ int lenreq8 = (int)strlen(req8);
+ int lenreq9 = (int)strlen(req9);
+ int lenreq10 = (int)strlen(req10);
+ int lenreq11 = (int)strlen(req11);
+ int lenreq12 = (int)strlen(req12);
+ int lenhdr12 = lenreq12 - 4; /* length without body */
+
+ mark_point();
+
+ /* An empty string is neither a complete request nor a complete
+ * response, so it must return 0 */
+ ck_assert_int_eq(0, get_http_header_len(empty, 0));
+ ck_assert_int_eq(0, test_parse_http_request(empty, 0, &ri));
+ ck_assert_int_eq(0, test_parse_http_response(empty, 0, &respi));
+
+ /* Same is true for a leading space */
+ ck_assert_int_eq(0, get_http_header_len(space, 1));
+ ck_assert_int_eq(0, test_parse_http_request(space, 1, &ri));
+ ck_assert_int_eq(0, test_parse_http_response(space, 1, &respi));
+
+ /* But a control character (like 0) makes it invalid */
+ ck_assert_int_eq(-1, get_http_header_len(space, 2));
+ ck_assert_int_eq(-1, test_parse_http_request(space, 2, &ri));
+ ck_assert_int_eq(-1, test_parse_http_response(space, 2, &respi));
+
+
+ /* req1 minus 1 byte at the end is incomplete */
+ ck_assert_int_eq(0, get_http_header_len(req1, lenreq1 - 1));
+
+
+ /* req1 minus 1 byte at the start is complete but invalid */
+ ck_assert_int_eq(lenreq1 - 1, get_http_header_len(req1 + 1, lenreq1 - 1));
+ ck_assert_int_eq(-1, test_parse_http_request(req1 + 1, lenreq1 - 1, &ri));
+
+
+ /* req1 is a valid request */
+ ck_assert_int_eq(lenreq1, get_http_header_len(req1, lenreq1));
+ ck_assert_int_eq(-1, test_parse_http_response(req1, lenreq1, &respi));
+ ck_assert_int_eq(lenreq1, test_parse_http_request(req1, lenreq1, &ri));
+ ck_assert_str_eq("1.1", ri.http_version);
+ ck_assert_int_eq(0, ri.num_headers);
+
+
+ /* req2 is a complete, but invalid request */
+ ck_assert_int_eq(lenreq2, get_http_header_len(req2, lenreq2));
+ ck_assert_int_eq(-1, test_parse_http_request(req2, lenreq2, &ri));
+
+
+ /* req3 is a complete and valid request */
+ ck_assert_int_eq(lenreq3, get_http_header_len(req3, lenreq3));
+ ck_assert_int_eq(lenreq3, test_parse_http_request(req3, lenreq3, &ri));
+ ck_assert_int_eq(-1, test_parse_http_response(req3, lenreq3, &respi));
+
+
+ /* Multiline header are obsolete, so return an error
+ * (https://tools.ietf.org/html/rfc7230#section-3.2.4). */
+ ck_assert_int_eq(-1, test_parse_http_request(req4, lenreq4, &ri));
+
+
+ /* req5 is a complete and valid request (also somewhat malformed,
+ * since it uses \n\n instead of \r\n\r\n) */
+ ck_assert_int_eq(lenreq5, get_http_header_len(req5, lenreq5));
+ ck_assert_int_eq(-1, test_parse_http_response(req5, lenreq5, &respi));
+ ck_assert_int_eq(lenreq5, test_parse_http_request(req5, lenreq5, &ri));
+ ck_assert_str_eq("GET", ri.request_method);
+ ck_assert_str_eq("1.0", ri.http_version);
+
+
+ /* req6 is incomplete */
+ ck_assert_int_eq(0, get_http_header_len(req6, lenreq6));
+ ck_assert_int_eq(0, test_parse_http_request(req6, lenreq6, &ri));
+
+
+ /* req7 is invalid, but not yet complete */
+ ck_assert_int_eq(0, get_http_header_len(req7, lenreq7));
+ ck_assert_int_eq(0, test_parse_http_request(req7, lenreq7, &ri));
+
+
+ /* req8 is a valid response */
+ ck_assert_int_eq(lenreq8, get_http_header_len(req8, lenreq8));
+ ck_assert_int_eq(-1, test_parse_http_request(req8, lenreq8, &ri));
+ ck_assert_int_eq(lenreq8, test_parse_http_response(req8, lenreq8, &respi));
+
+
+ /* req9 is a valid response */
+ ck_assert_int_eq(lenreq9, get_http_header_len(req9, lenreq9));
+ ck_assert_int_eq(-1, test_parse_http_request(req9, lenreq9, &ri));
+ ck_assert_int_eq(lenreq9, test_parse_http_response(req9, lenreq9, &respi));
+ ck_assert_int_eq(1, respi.num_headers);
+
+
+ /* req10 is a valid request */
+ ck_assert_int_eq(lenreq10, get_http_header_len(req10, lenreq10));
+ ck_assert_int_eq(lenreq10, test_parse_http_request(req10, lenreq10, &ri));
+ ck_assert_str_eq("1.1", ri.http_version);
+ ck_assert_int_eq(2, ri.num_headers);
+ ck_assert_str_eq("A", ri.http_headers[0].name);
+ ck_assert_str_eq("foo bar", ri.http_headers[0].value);
+ ck_assert_str_eq("B", ri.http_headers[1].name);
+ ck_assert_str_eq("bar", ri.http_headers[1].value);
+
+
+ /* req11 is a complete but valid request */
+ ck_assert_int_eq(-1, test_parse_http_request(req11, lenreq11, &ri));
+
+
+ /* req12 is a valid request with body data */
+ ck_assert_int_gt(lenreq12, lenhdr12);
+ ck_assert_int_eq(lenhdr12, get_http_header_len(req12, lenreq12));
+ ck_assert_int_eq(lenhdr12, test_parse_http_request(req12, lenreq12, &ri));
+}
+END_TEST
+
+
+START_TEST(test_should_keep_alive)
+{
+ /* Adapted from unit_test.c */
+ /* Copyright (c) 2013-2015 the Civetweb developers */
+ /* Copyright (c) 2004-2013 Sergey Lyubka */
+ struct mg_connection conn;
+ struct mg_context ctx;
+ char req1[] = "GET / HTTP/1.1\r\n\r\n";
+ char req2[] = "GET / HTTP/1.0\r\n\r\n";
+ char req3[] = "GET / HTTP/1.1\r\nConnection: close\r\n\r\n";
+ char req4[] = "GET / HTTP/1.1\r\nConnection: keep-alive\r\n\r\n";
+ char yes[] = "yes";
+ char no[] = "no";
+
+ int lenreq1 = (int)strlen(req1);
+ int lenreq2 = (int)strlen(req2);
+ int lenreq3 = (int)strlen(req3);
+ int lenreq4 = (int)strlen(req4);
+
+ mark_point();
+
+ memset(&ctx, 0, sizeof(ctx));
+ memset(&conn, 0, sizeof(conn));
+ conn.ctx = &ctx;
+ ck_assert_int_eq(test_parse_http_request(req1, lenreq1, &conn.request_info),
+ lenreq1);
+ conn.connection_type = 1; /* Valid request */
+ ck_assert_int_eq(conn.request_info.num_headers, 0);
+
+ ctx.config[ENABLE_KEEP_ALIVE] = no;
+ ck_assert_int_eq(should_keep_alive(&conn), 0);
+
+ ctx.config[ENABLE_KEEP_ALIVE] = yes;
+ ck_assert_int_eq(should_keep_alive(&conn), 1);
+
+ conn.must_close = 1;
+ ck_assert_int_eq(should_keep_alive(&conn), 0);
+
+ conn.must_close = 0;
+ test_parse_http_request(req2, lenreq2, &conn.request_info);
+ conn.connection_type = 1; /* Valid request */
+ ck_assert_int_eq(conn.request_info.num_headers, 0);
+ ck_assert_int_eq(should_keep_alive(&conn), 0);
+
+ test_parse_http_request(req3, lenreq3, &conn.request_info);
+ conn.connection_type = 1; /* Valid request */
+ ck_assert_int_eq(conn.request_info.num_headers, 1);
+ ck_assert_int_eq(should_keep_alive(&conn), 0);
+
+ test_parse_http_request(req4, lenreq4, &conn.request_info);
+ conn.connection_type = 1; /* Valid request */
+ ck_assert_int_eq(conn.request_info.num_headers, 1);
+ ck_assert_int_eq(should_keep_alive(&conn), 1);
+
+ conn.status_code = 200;
+ conn.must_close = 1;
+ ck_assert_int_eq(should_keep_alive(&conn), 0);
+
+ conn.status_code = 200;
+ conn.must_close = 0;
+ ck_assert_int_eq(should_keep_alive(&conn), 1);
+
+ conn.status_code = 200;
+ conn.must_close = 0;
+ conn.connection_type = 0; /* invalid */
+ ck_assert_int_eq(should_keep_alive(&conn), 0);
+}
+END_TEST
+
+
+START_TEST(test_match_prefix)
+{
+ /* Adapted from unit_test.c */
+ /* Copyright (c) 2013-2015 the Civetweb developers */
+ /* Copyright (c) 2004-2013 Sergey Lyubka */
+ ck_assert_int_eq(4, match_prefix("/api", 4, "/api"));
+ ck_assert_int_eq(3, match_prefix("/a/", 3, "/a/b/c"));
+ ck_assert_int_eq(-1, match_prefix("/a/", 3, "/ab/c"));
+ ck_assert_int_eq(4, match_prefix("/*/", 3, "/ab/c"));
+ ck_assert_int_eq(6, match_prefix("**", 2, "/a/b/c"));
+ ck_assert_int_eq(2, match_prefix("/*", 2, "/a/b/c"));
+ ck_assert_int_eq(2, match_prefix("*/*", 3, "/a/b/c"));
+ ck_assert_int_eq(5, match_prefix("**/", 3, "/a/b/c"));
+ ck_assert_int_eq(5, match_prefix("**.foo|**.bar", 13, "a.bar"));
+ ck_assert_int_eq(2, match_prefix("a|b|cd", 6, "cdef"));
+ ck_assert_int_eq(2, match_prefix("a|b|c?", 6, "cdef"));
+ ck_assert_int_eq(1, match_prefix("a|?|cd", 6, "cdef"));
+ ck_assert_int_eq(-1, match_prefix("/a/**.cgi", 9, "/foo/bar/x.cgi"));
+ ck_assert_int_eq(12, match_prefix("/a/**.cgi", 9, "/a/bar/x.cgi"));
+ ck_assert_int_eq(5, match_prefix("**/", 3, "/a/b/c"));
+ ck_assert_int_eq(-1, match_prefix("**/$", 4, "/a/b/c"));
+ ck_assert_int_eq(5, match_prefix("**/$", 4, "/a/b/"));
+ ck_assert_int_eq(0, match_prefix("$", 1, ""));
+ ck_assert_int_eq(-1, match_prefix("$", 1, "x"));
+ ck_assert_int_eq(1, match_prefix("*$", 2, "x"));
+ ck_assert_int_eq(1, match_prefix("/$", 2, "/"));
+ ck_assert_int_eq(-1, match_prefix("**/$", 4, "/a/b/c"));
+ ck_assert_int_eq(5, match_prefix("**/$", 4, "/a/b/"));
+ ck_assert_int_eq(0, match_prefix("*", 1, "/hello/"));
+ ck_assert_int_eq(-1, match_prefix("**.a$|**.b$", 11, "/a/b.b/"));
+ ck_assert_int_eq(6, match_prefix("**.a$|**.b$", 11, "/a/b.b"));
+ ck_assert_int_eq(6, match_prefix("**.a$|**.b$", 11, "/a/B.A"));
+ ck_assert_int_eq(5, match_prefix("**o$", 4, "HELLO"));
+}
+END_TEST
+
+
+START_TEST(test_remove_double_dots_and_double_slashes)
+{
+ /* Adapted from unit_test.c */
+ /* Copyright (c) 2013-2015 the Civetweb developers */
+ /* Copyright (c) 2004-2013 Sergey Lyubka */
+ struct {
+ char before[20], after[20];
+ } data[] = {
+ {"////a", "/a"},
+ {"/.....", "/."},
+ {"/......", "/"},
+ {"..", "."},
+ {"...", "."},
+ {"/...///", "/./"},
+ {"/a...///", "/a.../"},
+ {"/.x", "/.x"},
+ {"/\\", "/"},
+ {"/a\\", "/a\\"},
+ {"/a\\\\...", "/a\\."},
+ };
+ size_t i;
+
+ mark_point();
+
+ for (i = 0; i < ARRAY_SIZE(data); i++) {
+ remove_double_dots_and_double_slashes(data[i].before);
+ ck_assert_str_eq(data[i].before, data[i].after);
+ }
+}
+END_TEST
+
+
+START_TEST(test_is_valid_uri)
+{
+ /* is_valid_uri is superseeded by get_uri_type */
+ ck_assert_int_eq(2, get_uri_type("/api"));
+ ck_assert_int_eq(2, get_uri_type("/api/"));
+ ck_assert_int_eq(2,
+ get_uri_type("/some/long/path%20with%20space/file.xyz"));
+ ck_assert_int_eq(0, get_uri_type("api"));
+ ck_assert_int_eq(1, get_uri_type("*"));
+ ck_assert_int_eq(0, get_uri_type("*xy"));
+ ck_assert_int_eq(3, get_uri_type("http://somewhere/"));
+ ck_assert_int_eq(3, get_uri_type("https://somewhere/some/file.html"));
+ ck_assert_int_eq(4, get_uri_type("http://somewhere:8080/"));
+ ck_assert_int_eq(4, get_uri_type("https://somewhere:8080/some/file.html"));
+}
+END_TEST
+
+
+START_TEST(test_next_option)
+{
+ /* Adapted from unit_test.c */
+ /* Copyright (c) 2013-2015 the Civetweb developers */
+ /* Copyright (c) 2004-2013 Sergey Lyubka */
+ const char *p, *list = "x/8,/y**=1;2k,z";
+ struct vec a, b;
+ int i;
+
+ mark_point();
+
+ ck_assert(next_option(NULL, &a, &b) == NULL);
+ for (i = 0, p = list; (p = next_option(p, &a, &b)) != NULL; i++) {
+ ck_assert(i != 0 || (a.ptr == list && a.len == 3 && b.len == 0));
+ ck_assert(i != 1
+ || (a.ptr == list + 4 && a.len == 4 && b.ptr == list + 9
+ && b.len == 4));
+ ck_assert(i != 2 || (a.ptr == list + 14 && a.len == 1 && b.len == 0));
+ }
+}
+END_TEST
+
+
+START_TEST(test_skip_quoted)
+{
+ /* Adapted from unit_test.c */
+ /* Copyright (c) 2013-2015 the Civetweb developers */
+ /* Copyright (c) 2004-2013 Sergey Lyubka */
+ char x[] = "a=1, b=2, c='hi \' there', d='here\\, there'", *s = x, *p;
+
+ mark_point();
+
+ p = skip_quoted(&s, ", ", ", ", 0);
+ ck_assert(p != NULL && !strcmp(p, "a=1"));
+
+ p = skip_quoted(&s, ", ", ", ", 0);
+ ck_assert(p != NULL && !strcmp(p, "b=2"));
+
+ p = skip_quoted(&s, ",", " ", 0);
+ ck_assert(p != NULL && !strcmp(p, "c='hi \' there'"));
+
+ p = skip_quoted(&s, ",", " ", '\\');
+ ck_assert(p != NULL && !strcmp(p, "d='here, there'"));
+ ck_assert(*s == 0);
+}
+END_TEST
+
+
+static int
+alloc_printf(char **buf, size_t size, const char *fmt, ...)
+{
+ /* Test helper function - adapted from unit_test.c */
+ /* Copyright (c) 2013-2015 the Civetweb developers */
+ /* Copyright (c) 2004-2013 Sergey Lyubka */
+ va_list ap;
+ int ret = 0;
+
+ mark_point();
+
+ va_start(ap, fmt);
+ ret = alloc_vprintf(buf, *buf, size, fmt, ap);
+ va_end(ap);
+
+ return ret;
+}
+
+
+static int
+alloc_printf2(char **buf, const char *fmt, ...)
+{
+ /* Test alternative implementation */
+ va_list ap;
+ int ret = 0;
+
+ mark_point();
+
+ va_start(ap, fmt);
+ ret = alloc_vprintf2(buf, fmt, ap);
+ va_end(ap);
+
+ return ret;
+}
+
+
+START_TEST(test_alloc_vprintf)
+{
+ /* Adapted from unit_test.c */
+ /* Copyright (c) 2013-2015 the Civetweb developers */
+ /* Copyright (c) 2004-2013 Sergey Lyubka */
+ char buf[MG_BUF_LEN], *p = buf;
+ mark_point();
+
+ ck_assert(alloc_printf(&p, sizeof(buf), "%s", "hi") == 2);
+ ck_assert(p == buf);
+
+ ck_assert(alloc_printf(&p, sizeof(buf), "%s", "") == 0);
+ ck_assert(p == buf);
+
+ ck_assert(alloc_printf(&p, sizeof(buf), "") == 0);
+ ck_assert(p == buf);
+
+ /* Pass small buffer, make sure alloc_printf allocates */
+ ck_assert(alloc_printf(&p, 1, "%s", "hello") == 5);
+ ck_assert(p != buf);
+ mg_free(p);
+ p = buf;
+
+ /* Test alternative implementation */
+ ck_assert(alloc_printf2(&p, "%s", "hello") == 5);
+ ck_assert(p != buf);
+ mg_free(p);
+ p = buf;
+}
+END_TEST
+
+
+START_TEST(test_mg_vsnprintf)
+{
+ char buf[16];
+ int is_trunc;
+
+#if defined(_WIN32)
+ /* If the string is truncated, mg_snprintf calls mg_cry.
+ * If DEBUG is defined, mg_cry calls DEBUG_TRACE.
+ * In DEBUG_TRACE_FUNC, flockfile(stdout) is called.
+ * For Windows, flockfile/funlockfile calls Enter-/
+ * LeaveCriticalSection(&global_log_file_lock).
+ * So, we need to initialize global_log_file_lock:
+ */
+ InitializeCriticalSection(&global_log_file_lock);
+#endif
+
+ memset(buf, 0, sizeof(buf));
+ mark_point();
+
+ is_trunc = 777;
+ mg_snprintf(NULL, &is_trunc, buf, 10, "%8i", 123);
+ ck_assert_str_eq(buf, " 123");
+ ck_assert_int_eq(is_trunc, 0);
+
+ is_trunc = 777;
+ mg_snprintf(NULL, &is_trunc, buf, 10, "%9i", 123);
+ ck_assert_str_eq(buf, " 123");
+ ck_assert_int_eq(is_trunc, 0);
+
+ is_trunc = 777;
+ mg_snprintf(NULL, &is_trunc, buf, 9, "%9i", 123);
+ ck_assert_str_eq(buf, " 12");
+ ck_assert_int_eq(is_trunc, 1);
+
+ is_trunc = 777;
+ mg_snprintf(NULL, &is_trunc, buf, 8, "%9i", 123);
+ ck_assert_str_eq(buf, " 1");
+ ck_assert_int_eq(is_trunc, 1);
+
+ is_trunc = 777;
+ mg_snprintf(NULL, &is_trunc, buf, 7, "%9i", 123);
+ ck_assert_str_eq(buf, " ");
+ ck_assert_int_eq(is_trunc, 1);
+
+ is_trunc = 777;
+ strcpy(buf, "1234567890");
+ mg_snprintf(NULL, &is_trunc, buf, 0, "%i", 543);
+ ck_assert_str_eq(buf, "1234567890");
+ ck_assert_int_eq(is_trunc, 1);
+}
+END_TEST
+
+
+START_TEST(test_mg_strcasestr)
+{
+ /* Adapted from unit_test.c */
+ /* Copyright (c) 2013-2015 the Civetweb developers */
+ /* Copyright (c) 2004-2013 Sergey Lyubka */
+ static const char *big1 = "abcdef";
+ mark_point();
+
+ ck_assert(mg_strcasestr("Y", "X") == NULL);
+ ck_assert(mg_strcasestr("Y", "y") != NULL);
+ ck_assert(mg_strcasestr(big1, "X") == NULL);
+ ck_assert(mg_strcasestr(big1, "CD") == big1 + 2);
+ ck_assert(mg_strcasestr("aa", "AAB") == NULL);
+}
+END_TEST
+
+
+START_TEST(test_parse_port_string)
+{
+ /* Adapted from unit_test.c */
+ /* Copyright (c) 2013-2015 the Civetweb developers */
+ /* Copyright (c) 2004-2013 Sergey Lyubka */
+ static const char *valid[] =
+ { "0",
+ "1",
+ "1s",
+ "1r",
+ "1.2.3.4:1",
+ "1.2.3.4:1s",
+ "1.2.3.4:1r",
+#if defined(USE_IPV6)
+ "[::1]:123",
+ "[::]:80",
+ "[3ffe:2a00:100:7031::1]:900",
+ "+80",
+#endif
+ NULL };
+ static const char *invalid[] = {
+ "99999", "1k", "1.2.3", "1.2.3.4:", "1.2.3.4:2p", NULL};
+ struct socket so;
+ struct vec vec;
+ int ip_family;
+ int i;
+
+ mark_point();
+
+ for (i = 0; valid[i] != NULL; i++) {
+ vec.ptr = valid[i];
+ vec.len = strlen(vec.ptr);
+ ip_family = 123;
+ ck_assert_int_ne(parse_port_string(&vec, &so, &ip_family), 0);
+ if (i < 7) {
+ ck_assert_int_eq(ip_family, 4);
+ } else if (i < 10) {
+ ck_assert_int_eq(ip_family, 6);
+ } else {
+ ck_assert_int_eq(ip_family, 4 + 6);
+ }
+ }
+
+ for (i = 0; invalid[i] != NULL; i++) {
+ vec.ptr = invalid[i];
+ vec.len = strlen(vec.ptr);
+ ip_family = 123;
+ ck_assert_int_eq(parse_port_string(&vec, &so, &ip_family), 0);
+ ck_assert_int_eq(ip_family, 0);
+ }
+}
+END_TEST
+
+
+START_TEST(test_encode_decode)
+{
+ char buf[128];
+ const char *alpha = "abcdefghijklmnopqrstuvwxyz";
+ const char *nonalpha = " !\"#$%&'()*+,-./0123456789:;<=>?@";
+ const char *nonalpha_url_enc1 =
+ "%20%21%22%23$%25%26%27()%2a%2b,-.%2f0123456789%3a;%3c%3d%3e%3f%40";
+ const char *nonalpha_url_enc2 =
+ "%20!%22%23%24%25%26'()*%2B%2C-.%2F0123456789%3A%3B%3C%3D%3E%3F%40";
+ int ret;
+ size_t len;
+
+#if defined(USE_WEBSOCKET) || defined(USE_LUA)
+ const char *alpha_b64_enc = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=";
+ const char *nonalpha_b64_enc =
+ "ICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9A";
+
+ mark_point();
+
+ memset(buf, 77, sizeof(buf));
+ base64_encode((unsigned char *)"a", 1, buf);
+ ck_assert_str_eq(buf, "YQ==");
+
+ memset(buf, 77, sizeof(buf));
+ base64_encode((unsigned char *)"ab", 1, buf);
+ ck_assert_str_eq(buf, "YQ==");
+
+ memset(buf, 77, sizeof(buf));
+ base64_encode((unsigned char *)"ab", 2, buf);
+ ck_assert_str_eq(buf, "YWI=");
+
+ memset(buf, 77, sizeof(buf));
+ base64_encode((unsigned char *)alpha, 3, buf);
+ ck_assert_str_eq(buf, "YWJj");
+
+ memset(buf, 77, sizeof(buf));
+ base64_encode((unsigned char *)alpha, 4, buf);
+ ck_assert_str_eq(buf, "YWJjZA==");
+
+ memset(buf, 77, sizeof(buf));
+ base64_encode((unsigned char *)alpha, 5, buf);
+ ck_assert_str_eq(buf, "YWJjZGU=");
+
+ memset(buf, 77, sizeof(buf));
+ base64_encode((unsigned char *)alpha, 6, buf);
+ ck_assert_str_eq(buf, "YWJjZGVm");
+
+ memset(buf, 77, sizeof(buf));
+ base64_encode((unsigned char *)alpha, (int)strlen(alpha), buf);
+ ck_assert_str_eq(buf, alpha_b64_enc);
+
+ memset(buf, 77, sizeof(buf));
+ base64_encode((unsigned char *)nonalpha, (int)strlen(nonalpha), buf);
+ ck_assert_str_eq(buf, nonalpha_b64_enc);
+#endif
+
+#if defined(USE_LUA)
+ memset(buf, 77, sizeof(buf));
+ len = 9999;
+ ret = base64_decode((unsigned char *)alpha_b64_enc,
+ (int)strlen(alpha_b64_enc),
+ buf,
+ &len);
+ ck_assert_int_eq(ret, -1);
+ ck_assert_uint_eq((unsigned int)len, (unsigned int)strlen(alpha));
+ ck_assert_str_eq(buf, alpha);
+
+ memset(buf, 77, sizeof(buf));
+ len = 9999;
+ ret = base64_decode((unsigned char *)"AAA*AAA", 7, buf, &len);
+ ck_assert_int_eq(ret, 3);
+#endif
+
+ memset(buf, 77, sizeof(buf));
+ ret = mg_url_encode(alpha, buf, sizeof(buf));
+ ck_assert_int_eq(ret, (int)strlen(buf));
+ ck_assert_int_eq(ret, (int)strlen(alpha));
+ ck_assert_str_eq(buf, alpha);
+
+ memset(buf, 77, sizeof(buf));
+ ret = mg_url_encode(nonalpha, buf, sizeof(buf));
+ ck_assert_int_eq(ret, (int)strlen(buf));
+ ck_assert_int_eq(ret, (int)strlen(nonalpha_url_enc1));
+ ck_assert_str_eq(buf, nonalpha_url_enc1);
+
+ memset(buf, 77, sizeof(buf));
+ ret = mg_url_decode(alpha, (int)strlen(alpha), buf, sizeof(buf), 0);
+ ck_assert_int_eq(ret, (int)strlen(buf));
+ ck_assert_int_eq(ret, (int)strlen(alpha));
+ ck_assert_str_eq(buf, alpha);
+
+ memset(buf, 77, sizeof(buf));
+ ret = mg_url_decode(
+ nonalpha_url_enc1, (int)strlen(nonalpha_url_enc1), buf, sizeof(buf), 0);
+ ck_assert_int_eq(ret, (int)strlen(buf));
+ ck_assert_int_eq(ret, (int)strlen(nonalpha));
+ ck_assert_str_eq(buf, nonalpha);
+
+ memset(buf, 77, sizeof(buf));
+ ret = mg_url_decode(
+ nonalpha_url_enc2, (int)strlen(nonalpha_url_enc2), buf, sizeof(buf), 0);
+ ck_assert_int_eq(ret, (int)strlen(buf));
+ ck_assert_int_eq(ret, (int)strlen(nonalpha));
+ ck_assert_str_eq(buf, nonalpha);
+
+ /* len could be unused, if base64_decode is not tested because USE_LUA is
+ * not defined */
+ (void)len;
+}
+END_TEST
+
+
+START_TEST(test_mask_data)
+{
+#if defined(USE_WEBSOCKET)
+ char in[1024];
+ char out[1024];
+ int i;
+#endif
+
+ uint32_t mask = 0x61626364;
+ /* TODO: adapt test for big endian */
+ ck_assert((*(unsigned char *)&mask) == 0x64u);
+
+#if defined(USE_WEBSOCKET)
+ memset(in, 0, sizeof(in));
+ memset(out, 99, sizeof(out));
+
+ mask_data(in, sizeof(out), 0, out);
+ ck_assert(!memcmp(out, in, sizeof(out)));
+
+ for (i = 0; i < 1024; i++) {
+ in[i] = (char)((unsigned char)i);
+ }
+ mask_data(in, 107, 0, out);
+ ck_assert(!memcmp(out, in, 107));
+
+ mask_data(in, 256, 0x01010101, out);
+ for (i = 0; i < 256; i++) {
+ ck_assert_int_eq((int)((unsigned char)out[i]),
+ (int)(((unsigned char)in[i]) ^ (char)1u));
+ }
+ for (i = 256; i < (int)sizeof(out); i++) {
+ ck_assert_int_eq((int)((unsigned char)out[i]), (int)0);
+ }
+
+ /* TODO: check this for big endian */
+ mask_data(in, 5, 0x01020304, out);
+ ck_assert_uint_eq((unsigned char)out[0], 0u ^ 4u);
+ ck_assert_uint_eq((unsigned char)out[1], 1u ^ 3u);
+ ck_assert_uint_eq((unsigned char)out[2], 2u ^ 2u);
+ ck_assert_uint_eq((unsigned char)out[3], 3u ^ 1u);
+ ck_assert_uint_eq((unsigned char)out[4], 4u ^ 4u);
+#endif
+}
+END_TEST
+
+
+START_TEST(test_parse_date_string)
+{
+#if !defined(NO_CACHING)
+ time_t now = time(0);
+ struct tm *tm = gmtime(&now);
+ char date[64] = {0};
+ unsigned long i;
+
+ ck_assert_uint_eq((unsigned long)parse_date_string("1/Jan/1970 00:01:02"),
+ 62ul);
+ ck_assert_uint_eq((unsigned long)parse_date_string("1 Jan 1970 00:02:03"),
+ 123ul);
+ ck_assert_uint_eq((unsigned long)parse_date_string("1-Jan-1970 00:03:04"),
+ 184ul);
+ ck_assert_uint_eq((unsigned long)parse_date_string(
+ "Xyz, 1 Jan 1970 00:04:05"),
+ 245ul);
+
+ gmt_time_string(date, sizeof(date), &now);
+ ck_assert_uint_eq((uintmax_t)parse_date_string(date), (uintmax_t)now);
+
+ sprintf(date,
+ "%02u %s %04u %02u:%02u:%02u",
+ tm->tm_mday,
+ month_names[tm->tm_mon],
+ tm->tm_year + 1900,
+ tm->tm_hour,
+ tm->tm_min,
+ tm->tm_sec);
+ ck_assert_uint_eq((uintmax_t)parse_date_string(date), (uintmax_t)now);
+
+ gmt_time_string(date, 1, NULL);
+ ck_assert_str_eq(date, "");
+ gmt_time_string(date, 6, NULL);
+ ck_assert_str_eq(date,
+ "Thu, "); /* part of "Thu, 01 Jan 1970 00:00:00 GMT" */
+ gmt_time_string(date, sizeof(date), NULL);
+ ck_assert_str_eq(date, "Thu, 01 Jan 1970 00:00:00 GMT");
+
+ for (i = 2ul; i < 0x8000000ul; i += i / 2) {
+ now = (time_t)i;
+
+ gmt_time_string(date, sizeof(date), &now);
+ ck_assert_uint_eq((uintmax_t)parse_date_string(date), (uintmax_t)now);
+
+ tm = gmtime(&now);
+ sprintf(date,
+ "%02u-%s-%04u %02u:%02u:%02u",
+ tm->tm_mday,
+ month_names[tm->tm_mon],
+ tm->tm_year + 1900,
+ tm->tm_hour,
+ tm->tm_min,
+ tm->tm_sec);
+ ck_assert_uint_eq((uintmax_t)parse_date_string(date), (uintmax_t)now);
+ }
+#endif
+}
+END_TEST
+
+
+START_TEST(test_sha1)
+{
+#ifdef SHA1_DIGEST_SIZE
+ SHA_CTX sha_ctx;
+ uint8_t digest[SHA1_DIGEST_SIZE] = {0};
+ char str[48] = {0};
+ int i;
+ const char *test_str;
+
+ ck_assert_uint_eq(sizeof(digest), 20);
+ ck_assert_uint_gt(sizeof(str), sizeof(digest) * 2 + 1);
+
+ /* empty string */
+ SHA1_Init(&sha_ctx);
+ SHA1_Final(digest, &sha_ctx);
+ bin2str(str, digest, sizeof(digest));
+ ck_assert_uint_eq(strlen(str), 40);
+ ck_assert_str_eq(str, "da39a3ee5e6b4b0d3255bfef95601890afd80709");
+
+ /* empty string */
+ SHA1_Init(&sha_ctx);
+ SHA1_Update(&sha_ctx, (uint8_t *)"abc", 0);
+ SHA1_Final(digest, &sha_ctx);
+ bin2str(str, digest, sizeof(digest));
+ ck_assert_uint_eq(strlen(str), 40);
+ ck_assert_str_eq(str, "da39a3ee5e6b4b0d3255bfef95601890afd80709");
+
+ /* "abc" */
+ SHA1_Init(&sha_ctx);
+ SHA1_Update(&sha_ctx, (uint8_t *)"abc", 3);
+ SHA1_Final(digest, &sha_ctx);
+ bin2str(str, digest, sizeof(digest));
+ ck_assert_uint_eq(strlen(str), 40);
+ ck_assert_str_eq(str, "a9993e364706816aba3e25717850c26c9cd0d89d");
+
+ /* "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" */
+ test_str = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
+ SHA1_Init(&sha_ctx);
+ SHA1_Update(&sha_ctx, (uint8_t *)test_str, (uint32_t)strlen(test_str));
+ SHA1_Final(digest, &sha_ctx);
+ bin2str(str, digest, sizeof(digest));
+ ck_assert_uint_eq(strlen(str), 40);
+ ck_assert_str_eq(str, "84983e441c3bd26ebaae4aa1f95129e5e54670f1");
+
+ /* a million "a" */
+ SHA1_Init(&sha_ctx);
+ for (i = 0; i < 1000000; i++) {
+ SHA1_Update(&sha_ctx, (uint8_t *)"a", 1);
+ }
+ SHA1_Final(digest, &sha_ctx);
+ bin2str(str, digest, sizeof(digest));
+ ck_assert_uint_eq(strlen(str), 40);
+ ck_assert_str_eq(str, "34aa973cd4c4daa4f61eeb2bdbad27316534016f");
+
+ /* a million "a" in blocks of 10 */
+ SHA1_Init(&sha_ctx);
+ for (i = 0; i < 100000; i++) {
+ SHA1_Update(&sha_ctx, (uint8_t *)"aaaaaaaaaa", 10);
+ }
+ SHA1_Final(digest, &sha_ctx);
+ bin2str(str, digest, sizeof(digest));
+ ck_assert_uint_eq(strlen(str), 40);
+ ck_assert_str_eq(str, "34aa973cd4c4daa4f61eeb2bdbad27316534016f");
+#else
+ /* Can not test, if SHA1 is not included */
+ ck_assert(1);
+#endif
+}
+END_TEST
+
+
+#if !defined(REPLACE_CHECK_FOR_LOCAL_DEBUGGING)
+Suite *
+make_private_suite(void)
+{
+ Suite *const suite = suite_create("Private");
+
+ TCase *const tcase_http_message = tcase_create("HTTP Message");
+ TCase *const tcase_http_keep_alive = tcase_create("HTTP Keep Alive");
+ TCase *const tcase_url_parsing_1 = tcase_create("URL Parsing 1");
+ TCase *const tcase_url_parsing_2 = tcase_create("URL Parsing 2");
+ TCase *const tcase_url_parsing_3 = tcase_create("URL Parsing 3");
+ TCase *const tcase_internal_parse_1 = tcase_create("Internal Parsing 1");
+ TCase *const tcase_internal_parse_2 = tcase_create("Internal Parsing 2");
+ TCase *const tcase_internal_parse_3 = tcase_create("Internal Parsing 3");
+ TCase *const tcase_internal_parse_4 = tcase_create("Internal Parsing 4");
+ TCase *const tcase_internal_parse_5 = tcase_create("Internal Parsing 5");
+ TCase *const tcase_internal_parse_6 = tcase_create("Internal Parsing 6");
+ TCase *const tcase_encode_decode = tcase_create("Encode Decode");
+ TCase *const tcase_mask_data = tcase_create("Mask Data");
+ TCase *const tcase_parse_date_string = tcase_create("Date Parsing");
+ TCase *const tcase_sha1 = tcase_create("SHA1");
+
+ tcase_add_test(tcase_http_message, test_parse_http_message);
+ tcase_set_timeout(tcase_http_message, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_http_message);
+
+ tcase_add_test(tcase_http_keep_alive, test_should_keep_alive);
+ tcase_set_timeout(tcase_http_keep_alive, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_http_keep_alive);
+
+ tcase_add_test(tcase_url_parsing_1, test_match_prefix);
+ tcase_set_timeout(tcase_url_parsing_1, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_url_parsing_1);
+
+ tcase_add_test(tcase_url_parsing_2,
+ test_remove_double_dots_and_double_slashes);
+ tcase_set_timeout(tcase_url_parsing_2, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_url_parsing_2);
+
+ tcase_add_test(tcase_url_parsing_3, test_is_valid_uri);
+ tcase_set_timeout(tcase_url_parsing_3, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_url_parsing_3);
+
+ tcase_add_test(tcase_internal_parse_1, test_next_option);
+ tcase_set_timeout(tcase_internal_parse_1, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_internal_parse_1);
+
+ tcase_add_test(tcase_internal_parse_2, test_skip_quoted);
+ tcase_set_timeout(tcase_internal_parse_2, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_internal_parse_2);
+
+ tcase_add_test(tcase_internal_parse_3, test_mg_strcasestr);
+ tcase_set_timeout(tcase_internal_parse_3, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_internal_parse_3);
+
+ tcase_add_test(tcase_internal_parse_4, test_alloc_vprintf);
+ tcase_set_timeout(tcase_internal_parse_4, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_internal_parse_4);
+
+ tcase_add_test(tcase_internal_parse_5, test_mg_vsnprintf);
+ tcase_set_timeout(tcase_internal_parse_5, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_internal_parse_5);
+
+ tcase_add_test(tcase_internal_parse_6, test_parse_port_string);
+ tcase_set_timeout(tcase_internal_parse_6, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_internal_parse_6);
+
+ tcase_add_test(tcase_encode_decode, test_encode_decode);
+ tcase_set_timeout(tcase_encode_decode, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_encode_decode);
+
+ tcase_add_test(tcase_mask_data, test_mask_data);
+ tcase_set_timeout(tcase_mask_data, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_mask_data);
+
+ tcase_add_test(tcase_parse_date_string, test_parse_date_string);
+ tcase_set_timeout(tcase_parse_date_string, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_parse_date_string);
+
+ tcase_add_test(tcase_sha1, test_sha1);
+ tcase_set_timeout(tcase_sha1, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_sha1);
+
+ return suite;
+}
+#endif
+
+
+#ifdef REPLACE_CHECK_FOR_LOCAL_DEBUGGING
+/* Used to debug test cases without using the check framework */
+
+void
+MAIN_PRIVATE(void)
+{
+#if defined(_WIN32)
+ /* test_parse_port_string requires WSAStartup for IPv6 */
+ WSADATA data;
+ WSAStartup(MAKEWORD(2, 2), &data);
+#endif
+
+ test_alloc_vprintf(0);
+ test_mg_vsnprintf(0);
+ test_remove_double_dots_and_double_slashes(0);
+ test_parse_date_string(0);
+ test_parse_port_string(0);
+ test_parse_http_message(0);
+ test_sha1(0);
+
+#if defined(_WIN32)
+ WSACleanup();
+#endif
+}
+
+#endif
diff --git a/src/civetweb/test/private.h b/src/civetweb/test/private.h
new file mode 100644
index 00000000..670b6659
--- /dev/null
+++ b/src/civetweb/test/private.h
@@ -0,0 +1,28 @@
+/* Copyright (c) 2015-2017 the Civetweb developers
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+#ifndef TEST_PRIVATE_H_
+#define TEST_PRIVATE_H_
+
+#include "civetweb_check.h"
+
+Suite *make_private_suite(void);
+
+#endif /* TEST_PRIVATE_H_ */
diff --git a/src/civetweb/test/private_exe.c b/src/civetweb/test/private_exe.c
new file mode 100644
index 00000000..9131efff
--- /dev/null
+++ b/src/civetweb/test/private_exe.c
@@ -0,0 +1,82 @@
+/* Copyright (c) 2015-2017 the Civetweb developers
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+/**
+ * We include the source file so that we have access to the internal private
+ * static functions.
+ */
+#ifdef _MSC_VER
+#ifndef _CRT_SECURE_NO_WARNINGS
+#define _CRT_SECURE_NO_WARNINGS
+#endif
+#endif
+
+#include "private_exe.h"
+
+/* This is required for "realpath". According to
+ * http://man7.org/linux/man-pages/man3/realpath.3.html
+ * defining _XOPEN_SOURCE 600 should be enough, but in
+ * practice this does not work. */
+extern char *realpath(const char *path, char *resolved_path);
+
+/* main is already used in the test suite,
+ * so this define will rename main in main.c */
+#define main exe_main
+
+#include "../src/main.c"
+
+#include
+
+/* This unit test file uses the excellent Check unit testing library.
+ * The API documentation is available here:
+ * http://check.sourceforge.net/doc/check_html/index.html
+ */
+
+START_TEST(test_helper_funcs)
+{
+ const char *psrc = "test str";
+ char *pdst;
+
+ /* test sdup */
+ pdst = sdup(psrc);
+ ck_assert(pdst != NULL);
+ ck_assert_str_eq(pdst, psrc);
+ ck_assert_ptr_ne(pdst, psrc);
+ free(pdst);
+}
+END_TEST
+
+
+#if !defined(REPLACE_CHECK_FOR_LOCAL_DEBUGGING)
+Suite *
+make_private_exe_suite(void)
+{
+ Suite *const suite = suite_create("EXE");
+
+ TCase *const tcase_helper_funcs = tcase_create("Helper funcs");
+
+ tcase_add_test(tcase_helper_funcs, test_helper_funcs);
+ tcase_set_timeout(tcase_helper_funcs, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_helper_funcs);
+
+ return suite;
+}
+#endif
diff --git a/src/civetweb/test/private_exe.h b/src/civetweb/test/private_exe.h
new file mode 100644
index 00000000..5e8e9bf6
--- /dev/null
+++ b/src/civetweb/test/private_exe.h
@@ -0,0 +1,31 @@
+/* Copyright (c) 2015-2017 the Civetweb developers
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+#ifndef TEST_PRIVATE_EXE_H_
+#define TEST_PRIVATE_EXE_H_
+
+#include "civetweb_check.h"
+
+Suite *make_private_exe_suite(void);
+
+/* This is a redefine for "main" in main.c */
+int exe_main(int argc, char *argv[]);
+
+#endif /* TEST_PRIVATE_H_ */
diff --git a/src/civetweb/test/protected/.htpasswd b/src/civetweb/test/protected/.htpasswd
new file mode 100644
index 00000000..5686ad3d
--- /dev/null
+++ b/src/civetweb/test/protected/.htpasswd
@@ -0,0 +1 @@
+user:mydomain.com:1aeed57ec85c6126e335a54789c2ecfa
diff --git a/src/civetweb/test/protected/content.txt b/src/civetweb/test/protected/content.txt
new file mode 100644
index 00000000..0bcd51a0
--- /dev/null
+++ b/src/civetweb/test/protected/content.txt
@@ -0,0 +1,5 @@
+Protected directory.
+
+username: user
+password: pass
+
diff --git a/src/civetweb/test/public_func.c b/src/civetweb/test/public_func.c
new file mode 100644
index 00000000..deb3dd5a
--- /dev/null
+++ b/src/civetweb/test/public_func.c
@@ -0,0 +1,546 @@
+/* Copyright (c) 2015-2017 the Civetweb developers
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#ifdef _MSC_VER
+#ifndef _CRT_SECURE_NO_WARNINGS
+#define _CRT_SECURE_NO_WARNINGS
+#endif
+#endif
+
+#include
+#include
+
+#include "public_func.h"
+#include
+
+/* This unit test file uses the excellent Check unit testing library.
+ * The API documentation is available here:
+ * http://check.sourceforge.net/doc/check_html/index.html
+ */
+
+START_TEST(test_mg_version)
+{
+ const char *ver = mg_version();
+ unsigned major = 0, minor = 0;
+ unsigned feature_files, feature_https, feature_cgi, feature_ipv6,
+ feature_websocket, feature_lua, feature_duktape, feature_caching;
+ unsigned expect_files = 0, expect_https = 0, expect_cgi = 0,
+ expect_ipv6 = 0, expect_websocket = 0, expect_lua = 0,
+ expect_duktape = 0, expect_caching = 0;
+ int ret, len;
+ char *buf;
+
+ ck_assert(ver != NULL);
+ ck_assert_str_eq(ver, CIVETWEB_VERSION);
+
+ /* check structure of version string */
+ ret = sscanf(ver, "%u.%u", &major, &minor);
+ ck_assert_int_eq(ret, 2);
+ ck_assert_uint_ge(major, 1);
+ if (major == 1) {
+ ck_assert_uint_ge(minor, 8); /* current version is 1.8 */
+ }
+
+ /* check feature */
+ feature_files = mg_check_feature(1);
+ feature_https = mg_check_feature(2);
+ feature_cgi = mg_check_feature(4);
+ feature_ipv6 = mg_check_feature(8);
+ feature_websocket = mg_check_feature(16);
+ feature_lua = mg_check_feature(32);
+ feature_duktape = mg_check_feature(64);
+ feature_caching = mg_check_feature(128);
+
+#if !defined(NO_FILES)
+ expect_files = 1;
+#endif
+#if !defined(NO_SSL)
+ expect_https = 1;
+#endif
+#if !defined(NO_CGI)
+ expect_cgi = 1;
+#endif
+#if defined(USE_IPV6)
+ expect_ipv6 = 1;
+#endif
+#if defined(USE_WEBSOCKET)
+ expect_websocket = 1;
+#endif
+#if defined(USE_LUA)
+ expect_lua = 1;
+#endif
+#if defined(USE_DUKTAPE)
+ expect_duktape = 1;
+#endif
+#if !defined(NO_CACHING)
+ expect_caching = 1;
+#endif
+
+ ck_assert_uint_eq(expect_files, !!feature_files);
+ ck_assert_uint_eq(expect_https, !!feature_https);
+ ck_assert_uint_eq(expect_cgi, !!feature_cgi);
+ ck_assert_uint_eq(expect_ipv6, !!feature_ipv6);
+ ck_assert_uint_eq(expect_websocket, !!feature_websocket);
+ ck_assert_uint_eq(expect_lua, !!feature_lua);
+ ck_assert_uint_eq(expect_duktape, !!feature_duktape);
+ ck_assert_uint_eq(expect_caching, !!feature_caching);
+
+ /* get system information */
+ len = mg_get_system_info(NULL, 0);
+ ck_assert_int_gt(len, 0);
+ buf = (char *)malloc((unsigned)len + 1);
+ ck_assert_ptr_ne(buf, NULL);
+ ret = mg_get_system_info(buf, len + 1);
+ ck_assert_int_eq(len, ret);
+ ret = (int)strlen(buf);
+ ck_assert_int_eq(len, ret);
+ free(buf);
+}
+END_TEST
+
+
+START_TEST(test_mg_get_valid_options)
+{
+ int i;
+ const struct mg_option *default_options = mg_get_valid_options();
+
+ ck_assert(default_options != NULL);
+
+ for (i = 0; default_options[i].name != NULL; i++) {
+ ck_assert(default_options[i].name != NULL);
+ ck_assert(strlen(default_options[i].name) > 0);
+ ck_assert(((int)default_options[i].type) > 0);
+ }
+
+ ck_assert(i > 0);
+}
+END_TEST
+
+
+START_TEST(test_mg_get_builtin_mime_type)
+{
+ ck_assert_str_eq(mg_get_builtin_mime_type("x.txt"), "text/plain");
+ ck_assert_str_eq(mg_get_builtin_mime_type("x.html"), "text/html");
+ ck_assert_str_eq(mg_get_builtin_mime_type("x.HTML"), "text/html");
+ ck_assert_str_eq(mg_get_builtin_mime_type("x.hTmL"), "text/html");
+ ck_assert_str_eq(mg_get_builtin_mime_type("/abc/def/ghi.htm"), "text/html");
+ ck_assert_str_eq(mg_get_builtin_mime_type("x.unknown_extention_xyz"),
+ "text/plain");
+}
+END_TEST
+
+
+START_TEST(test_mg_strncasecmp)
+{
+ ck_assert(mg_strncasecmp("abc", "abc", 3) == 0);
+ ck_assert(mg_strncasecmp("abc", "abcd", 3) == 0);
+ ck_assert(mg_strncasecmp("abc", "abcd", 4) != 0);
+ ck_assert(mg_strncasecmp("a", "A", 1) == 0);
+
+ ck_assert(mg_strncasecmp("A", "B", 1) < 0);
+ ck_assert(mg_strncasecmp("A", "b", 1) < 0);
+ ck_assert(mg_strncasecmp("a", "B", 1) < 0);
+ ck_assert(mg_strncasecmp("a", "b", 1) < 0);
+ ck_assert(mg_strncasecmp("b", "A", 1) > 0);
+ ck_assert(mg_strncasecmp("B", "A", 1) > 0);
+ ck_assert(mg_strncasecmp("b", "a", 1) > 0);
+ ck_assert(mg_strncasecmp("B", "a", 1) > 0);
+
+ ck_assert(mg_strncasecmp("xAx", "xBx", 3) < 0);
+ ck_assert(mg_strncasecmp("xAx", "xbx", 3) < 0);
+ ck_assert(mg_strncasecmp("xax", "xBx", 3) < 0);
+ ck_assert(mg_strncasecmp("xax", "xbx", 3) < 0);
+ ck_assert(mg_strncasecmp("xbx", "xAx", 3) > 0);
+ ck_assert(mg_strncasecmp("xBx", "xAx", 3) > 0);
+ ck_assert(mg_strncasecmp("xbx", "xax", 3) > 0);
+ ck_assert(mg_strncasecmp("xBx", "xax", 3) > 0);
+}
+END_TEST
+
+
+START_TEST(test_mg_get_cookie)
+{
+ char buf[32];
+ int ret;
+ const char *longcookie = "key1=1; key2=2; key3; key4=4; key5=; key6; "
+ "key7=this+is+it; key8=8; key9";
+
+ /* invalid result buffer */
+ ret = mg_get_cookie("", "notfound", NULL, 999);
+ ck_assert_int_eq(ret, -2);
+
+ /* zero size result buffer */
+ ret = mg_get_cookie("", "notfound", buf, 0);
+ ck_assert_int_eq(ret, -2);
+
+ /* too small result buffer */
+ ret = mg_get_cookie("key=toooooooooolong", "key", buf, 4);
+ ck_assert_int_eq(ret, -3);
+
+ /* key not found in string */
+ ret = mg_get_cookie("", "notfound", buf, sizeof(buf));
+ ck_assert_int_eq(ret, -1);
+
+ ret = mg_get_cookie(longcookie, "notfound", buf, sizeof(buf));
+ ck_assert_int_eq(ret, -1);
+
+ /* key not found in string */
+ ret = mg_get_cookie("key1=1; key2=2; key3=3", "notfound", buf, sizeof(buf));
+ ck_assert_int_eq(ret, -1);
+
+ /* keys are found as first, middle and last key */
+ memset(buf, 77, sizeof(buf));
+ ret = mg_get_cookie("key1=1; key2=2; key3=3", "key1", buf, sizeof(buf));
+ ck_assert_int_eq(ret, 1);
+ ck_assert_str_eq("1", buf);
+
+ memset(buf, 77, sizeof(buf));
+ ret = mg_get_cookie("key1=1; key2=2; key3=3", "key2", buf, sizeof(buf));
+ ck_assert_int_eq(ret, 1);
+ ck_assert_str_eq("2", buf);
+
+ memset(buf, 77, sizeof(buf));
+ ret = mg_get_cookie("key1=1; key2=2; key3=3", "key3", buf, sizeof(buf));
+ ck_assert_int_eq(ret, 1);
+ ck_assert_str_eq("3", buf);
+
+ /* longer value in the middle of a longer string */
+ memset(buf, 77, sizeof(buf));
+ ret = mg_get_cookie(longcookie, "key7", buf, sizeof(buf));
+ ck_assert_int_eq(ret, 10);
+ ck_assert_str_eq("this+is+it", buf);
+
+ /* key with = but without value in the middle of a longer string */
+ memset(buf, 77, sizeof(buf));
+ ret = mg_get_cookie(longcookie, "key5", buf, sizeof(buf));
+ ck_assert_int_eq(ret, 0);
+ ck_assert_str_eq("", buf);
+
+ /* key without = and without value in the middle of a longer string */
+ memset(buf, 77, sizeof(buf));
+ ret = mg_get_cookie(longcookie, "key6", buf, sizeof(buf));
+ ck_assert_int_eq(ret, -1);
+ /* TODO: mg_get_cookie and mg_get_var(2) should have the same behavior */
+}
+END_TEST
+
+
+START_TEST(test_mg_get_var)
+{
+ char buf[32];
+ int ret;
+ const char *shortquery = "key1=1&key2=2&key3=3";
+ const char *longquery = "key1=1&key2=2&key3&key4=4&key5=&key6&"
+ "key7=this+is+it&key8=8&key9&&key10=&&"
+ "key7=that+is+it&key12=12";
+
+ /* invalid result buffer */
+ ret = mg_get_var2("", 0, "notfound", NULL, 999, 0);
+ ck_assert_int_eq(ret, -2);
+
+ /* zero size result buffer */
+ ret = mg_get_var2("", 0, "notfound", buf, 0, 0);
+ ck_assert_int_eq(ret, -2);
+
+ /* too small result buffer */
+ ret = mg_get_var2("key=toooooooooolong", 19, "key", buf, 4, 0);
+ /* ck_assert_int_eq(ret, -3);
+ --> TODO: mg_get_cookie returns -3, mg_get_var -2. This should be
+ unified. */
+ ck_assert(ret < 0);
+
+ /* key not found in string */
+ ret = mg_get_var2("", 0, "notfound", buf, sizeof(buf), 0);
+ ck_assert_int_eq(ret, -1);
+
+ ret = mg_get_var2(
+ longquery, strlen(longquery), "notfound", buf, sizeof(buf), 0);
+ ck_assert_int_eq(ret, -1);
+
+ /* key not found in string */
+ ret = mg_get_var2(
+ shortquery, strlen(shortquery), "notfound", buf, sizeof(buf), 0);
+ ck_assert_int_eq(ret, -1);
+
+ /* key not found in string */
+ ret = mg_get_var2("key1=1&key2=2&key3=3¬found=here",
+ strlen(shortquery),
+ "notfound",
+ buf,
+ sizeof(buf),
+ 0);
+ ck_assert_int_eq(ret, -1);
+
+ /* key not found in string */
+ ret = mg_get_var2(
+ shortquery, strlen(shortquery), "key1", buf, sizeof(buf), 1);
+ ck_assert_int_eq(ret, -1);
+
+ /* keys are found as first, middle and last key */
+ memset(buf, 77, sizeof(buf));
+ ret = mg_get_var2(
+ shortquery, strlen(shortquery), "key1", buf, sizeof(buf), 0);
+ ck_assert_int_eq(ret, 1);
+ ck_assert_str_eq("1", buf);
+
+ memset(buf, 77, sizeof(buf));
+ ret = mg_get_var2(
+ shortquery, strlen(shortquery), "key2", buf, sizeof(buf), 0);
+ ck_assert_int_eq(ret, 1);
+ ck_assert_str_eq("2", buf);
+
+ memset(buf, 77, sizeof(buf));
+ ret = mg_get_var2(
+ shortquery, strlen(shortquery), "key3", buf, sizeof(buf), 0);
+ ck_assert_int_eq(ret, 1);
+ ck_assert_str_eq("3", buf);
+
+ /* mg_get_var call mg_get_var2 with last argument 0 */
+ memset(buf, 77, sizeof(buf));
+ ret = mg_get_var(shortquery, strlen(shortquery), "key1", buf, sizeof(buf));
+ ck_assert_int_eq(ret, 1);
+ ck_assert_str_eq("1", buf);
+
+ /* longer value in the middle of a longer string */
+ memset(buf, 77, sizeof(buf));
+ ret =
+ mg_get_var2(longquery, strlen(longquery), "key7", buf, sizeof(buf), 0);
+ ck_assert_int_eq(ret, 10);
+ ck_assert_str_eq("this is it", buf);
+
+ /* longer value in the middle of a longer string - seccond occurance of key
+ */
+ memset(buf, 77, sizeof(buf));
+ ret =
+ mg_get_var2(longquery, strlen(longquery), "key7", buf, sizeof(buf), 1);
+ ck_assert_int_eq(ret, 10);
+ ck_assert_str_eq("that is it", buf);
+
+ /* key with = but without value in the middle of a longer string */
+ memset(buf, 77, sizeof(buf));
+ ret =
+ mg_get_var2(longquery, strlen(longquery), "key5", buf, sizeof(buf), 0);
+ ck_assert_int_eq(ret, 0);
+ ck_assert_str_eq(buf, "");
+
+ /* key without = and without value in the middle of a longer string */
+ memset(buf, 77, sizeof(buf));
+ ret =
+ mg_get_var2(longquery, strlen(longquery), "key6", buf, sizeof(buf), 0);
+ ck_assert_int_eq(ret, -1);
+ ck_assert_str_eq(buf, "");
+ /* TODO: this is the same situation as with mg_get_value */
+}
+END_TEST
+
+
+START_TEST(test_mg_md5)
+{
+ char buf[33];
+ char *ret;
+ const char *long_str =
+ "_123456789A123456789B123456789C123456789D123456789E123456789F123456789"
+ "G123456789H123456789I123456789J123456789K123456789L123456789M123456789"
+ "N123456789O123456789P123456789Q123456789R123456789S123456789T123456789"
+ "U123456789V123456789W123456789X123456789Y123456789Z";
+
+ memset(buf, 77, sizeof(buf));
+ ret = mg_md5(buf, NULL);
+ ck_assert_str_eq(buf, "d41d8cd98f00b204e9800998ecf8427e");
+ ck_assert_str_eq(ret, "d41d8cd98f00b204e9800998ecf8427e");
+ ck_assert_ptr_eq(ret, buf);
+
+ memset(buf, 77, sizeof(buf));
+ ret = mg_md5(buf, "The quick brown fox jumps over the lazy dog.", NULL);
+ ck_assert_str_eq(buf, "e4d909c290d0fb1ca068ffaddf22cbd0");
+ ck_assert_str_eq(ret, "e4d909c290d0fb1ca068ffaddf22cbd0");
+ ck_assert_ptr_eq(ret, buf);
+
+ memset(buf, 77, sizeof(buf));
+ ret = mg_md5(buf,
+ "",
+ "The qu",
+ "ick bro",
+ "",
+ "wn fox ju",
+ "m",
+ "ps over the la",
+ "",
+ "",
+ "zy dog.",
+ "",
+ NULL);
+ ck_assert_str_eq(buf, "e4d909c290d0fb1ca068ffaddf22cbd0");
+ ck_assert_str_eq(ret, "e4d909c290d0fb1ca068ffaddf22cbd0");
+ ck_assert_ptr_eq(ret, buf);
+
+ memset(buf, 77, sizeof(buf));
+ ret = mg_md5(buf, long_str, NULL);
+ ck_assert_str_eq(buf, "1cb13cf9f16427807f081b2138241f08");
+ ck_assert_str_eq(ret, "1cb13cf9f16427807f081b2138241f08");
+ ck_assert_ptr_eq(ret, buf);
+
+ memset(buf, 77, sizeof(buf));
+ ret = mg_md5(buf, long_str + 1, NULL);
+ ck_assert_str_eq(buf, "cf62d3264334154f5779d3694cc5093f");
+ ck_assert_str_eq(ret, "cf62d3264334154f5779d3694cc5093f");
+ ck_assert_ptr_eq(ret, buf);
+}
+END_TEST
+
+
+START_TEST(test_mg_url_encode)
+{
+ char buf[20];
+ int ret;
+
+ memset(buf, 77, sizeof(buf));
+ ret = mg_url_encode("abc", buf, sizeof(buf));
+ ck_assert_int_eq(3, ret);
+ ck_assert_str_eq("abc", buf);
+
+ memset(buf, 77, sizeof(buf));
+ ret = mg_url_encode("a%b/c&d.e", buf, sizeof(buf));
+ ck_assert_int_eq(15, ret);
+ ck_assert_str_eq("a%25b%2fc%26d.e", buf);
+
+ memset(buf, 77, sizeof(buf));
+ ret = mg_url_encode("%%%", buf, 4);
+ ck_assert_int_eq(-1, ret);
+ ck_assert_str_eq("%25", buf);
+}
+END_TEST
+
+
+START_TEST(test_mg_url_decode)
+{
+ char buf[20];
+ int ret;
+
+ ret = mg_url_decode("abc", 3, buf, sizeof(buf), 0);
+ ck_assert_int_eq(ret, 3);
+ ck_assert_str_eq(buf, "abc");
+
+ ret = mg_url_decode("abcdef", 3, buf, sizeof(buf), 0);
+ ck_assert_int_eq(ret, 3);
+ ck_assert_str_eq(buf, "abc");
+
+ ret = mg_url_decode("x+y", 3, buf, sizeof(buf), 0);
+ ck_assert_int_eq(ret, 3);
+ ck_assert_str_eq(buf, "x+y");
+
+ ret = mg_url_decode("x+y", 3, buf, sizeof(buf), 1);
+ ck_assert_int_eq(ret, 3);
+ ck_assert_str_eq(buf, "x y");
+
+ ret = mg_url_decode("%25", 3, buf, sizeof(buf), 1);
+ ck_assert_int_eq(ret, 1);
+ ck_assert_str_eq(buf, "%");
+}
+END_TEST
+
+
+START_TEST(test_mg_get_response_code_text)
+{
+ int i;
+ size_t j, len;
+ const char *resp;
+
+ for (i = 100; i < 600; i++) {
+ resp = mg_get_response_code_text(NULL, i);
+ ck_assert_ptr_ne(resp, NULL);
+ len = strlen(resp);
+ ck_assert_uint_gt(len, 1);
+ ck_assert_uint_lt(len, 32);
+ for (j = 0; j < len; j++) {
+ if (resp[j] == ' ') {
+ /* space is valid */
+ } else if (resp[j] == '-') {
+ /* hyphen is valid */
+ } else if (resp[j] >= 'A' && resp[j] <= 'Z') {
+ /* A-Z is valid */
+ } else if (resp[j] >= 'a' && resp[j] <= 'z') {
+ /* a-z is valid */
+ } else {
+ ck_abort_msg("Found letter %c (%02xh) in %s",
+ resp[j],
+ resp[j],
+ resp);
+ }
+ }
+ }
+}
+END_TEST
+
+
+#if !defined(REPLACE_CHECK_FOR_LOCAL_DEBUGGING)
+Suite *
+make_public_func_suite(void)
+{
+ Suite *const suite = suite_create("PublicFunc");
+
+ TCase *const tcase_version = tcase_create("Version");
+ TCase *const tcase_get_valid_options = tcase_create("Options");
+ TCase *const tcase_get_builtin_mime_type = tcase_create("MIME types");
+ TCase *const tcase_strncasecmp = tcase_create("strcasecmp");
+ TCase *const tcase_urlencodingdecoding =
+ tcase_create("URL encoding decoding");
+ TCase *const tcase_cookies = tcase_create("Cookies and variables");
+ TCase *const tcase_md5 = tcase_create("MD5");
+ TCase *const tcase_aux = tcase_create("Aux functions");
+
+ tcase_add_test(tcase_version, test_mg_version);
+ tcase_set_timeout(tcase_version, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_version);
+
+ tcase_add_test(tcase_get_valid_options, test_mg_get_valid_options);
+ tcase_set_timeout(tcase_get_valid_options, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_get_valid_options);
+
+ tcase_add_test(tcase_get_builtin_mime_type, test_mg_get_builtin_mime_type);
+ tcase_set_timeout(tcase_get_builtin_mime_type, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_get_builtin_mime_type);
+
+ tcase_add_test(tcase_strncasecmp, test_mg_strncasecmp);
+ tcase_set_timeout(tcase_strncasecmp, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_strncasecmp);
+
+ tcase_add_test(tcase_urlencodingdecoding, test_mg_url_encode);
+ tcase_add_test(tcase_urlencodingdecoding, test_mg_url_decode);
+ tcase_set_timeout(tcase_urlencodingdecoding, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_urlencodingdecoding);
+
+ tcase_add_test(tcase_cookies, test_mg_get_cookie);
+ tcase_add_test(tcase_cookies, test_mg_get_var);
+ tcase_set_timeout(tcase_cookies, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_cookies);
+
+ tcase_add_test(tcase_md5, test_mg_md5);
+ tcase_set_timeout(tcase_md5, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_md5);
+
+ tcase_add_test(tcase_aux, test_mg_get_response_code_text);
+ tcase_set_timeout(tcase_aux, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_aux);
+
+ return suite;
+}
+#endif
diff --git a/src/civetweb/test/public_func.h b/src/civetweb/test/public_func.h
new file mode 100644
index 00000000..e2140832
--- /dev/null
+++ b/src/civetweb/test/public_func.h
@@ -0,0 +1,28 @@
+/* Copyright (c) 2015-2017 the Civetweb developers
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+#ifndef TEST_PUBLIC_FUNC_H_
+#define TEST_PUBLIC_FUNC_H_
+
+#include "civetweb_check.h"
+
+Suite *make_public_func_suite(void);
+
+#endif /* TEST_PUBLIC_H_ */
diff --git a/src/civetweb/test/public_server.c b/src/civetweb/test/public_server.c
new file mode 100644
index 00000000..b080ac26
--- /dev/null
+++ b/src/civetweb/test/public_server.c
@@ -0,0 +1,4953 @@
+/* Copyright (c) 2015-2017 the Civetweb developers
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#ifdef _MSC_VER
+#ifndef _CRT_SECURE_NO_WARNINGS
+#define _CRT_SECURE_NO_WARNINGS
+#endif
+#endif
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "public_server.h"
+#include
+
+#if defined(_WIN32)
+#include
+#define test_sleep(x) (Sleep((x)*1000))
+#else
+#include
+#define test_sleep(x) (sleep(x))
+#endif
+
+#define SLEEP_BEFORE_MG_START (1)
+#define SLEEP_AFTER_MG_START (3)
+#define SLEEP_BEFORE_MG_STOP (1)
+#define SLEEP_AFTER_MG_STOP (5)
+
+/* This unit test file uses the excellent Check unit testing library.
+ * The API documentation is available here:
+ * http://check.sourceforge.net/doc/check_html/index.html
+ */
+
+#if defined(__MINGW32__) || defined(__GNUC__)
+/* Return codes of the tested functions are evaluated. Checking all other
+ * functions, used only to prepare the test environment seems redundant.
+ * If they fail, the test fails anyway. */
+#pragma GCC diagnostic ignored "-Wunused-result"
+#endif
+
+static const char *
+locate_path(const char *a_path)
+{
+ static char r_path[256];
+
+#ifdef _WIN32
+#ifdef LOCAL_TEST
+ sprintf(r_path, "%s\\", a_path);
+#else
+ /* Appveyor */
+ sprintf(r_path, "..\\..\\..\\%s\\", a_path);
+/* TODO: the different paths
+ * used in the different test
+ * system is an unsolved
+ * problem. */
+#endif
+#else
+#ifdef LOCAL_TEST
+ sprintf(r_path, "%s/", a_path);
+#else
+ /* Travis */
+ sprintf(r_path,
+ "../../%s/",
+ a_path); // TODO: fix path in CI test environment
+#endif
+#endif
+
+ return r_path;
+}
+
+
+#define locate_resources() locate_path("resources")
+#define locate_test_exes() locate_path("output")
+
+
+static const char *
+locate_ssl_cert(void)
+{
+ static char cert_path[256];
+ const char *res = locate_resources();
+ size_t l;
+
+ ck_assert(res != NULL);
+ l = strlen(res);
+ ck_assert_uint_gt(l, 0);
+ ck_assert_uint_lt(l, 100); /* assume there is enough space left in our
+ typical 255 character string buffers */
+
+ strcpy(cert_path, res);
+ strcat(cert_path, "ssl_cert.pem");
+ return cert_path;
+}
+
+
+static int
+wait_not_null(void *volatile *data)
+{
+ int i;
+ for (i = 0; i < 100; i++) {
+ mark_point();
+ test_sleep(1);
+
+ if (*data != NULL) {
+ mark_point();
+ return 1;
+ }
+ }
+
+#if defined(__MINGW32__) || defined(__GNUC__)
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wunreachable-code"
+#pragma GCC diagnostic ignored "-Wunreachable-code-return"
+#endif
+
+ ck_abort_msg("wait_not_null failed (%i sec)", i);
+
+ return 0;
+
+#if defined(__MINGW32__) || defined(__GNUC__)
+#pragma GCC diagnostic pop
+#endif
+}
+
+
+START_TEST(test_the_test_environment)
+{
+ char wd[300];
+ char buf[500];
+ FILE *f;
+ struct stat st;
+ int ret;
+ const char *ssl_cert = locate_ssl_cert();
+
+ memset(wd, 0, sizeof(wd));
+ memset(buf, 0, sizeof(buf));
+
+/* Get the current working directory */
+#ifdef _WIN32
+ (void)GetCurrentDirectoryA(sizeof(wd), wd);
+ wd[sizeof(wd) - 1] = 0;
+#else
+ (void)getcwd(wd, sizeof(wd));
+ wd[sizeof(wd) - 1] = 0;
+#endif
+
+/* Check the pem file */
+#ifdef _WIN32
+ strcpy(buf, wd);
+ strcat(buf, "\\");
+ strcat(buf, ssl_cert);
+ f = fopen(buf, "rb");
+#else
+ strcpy(buf, wd);
+ strcat(buf, "/");
+ strcat(buf, ssl_cert);
+ f = fopen(buf, "r");
+#endif
+
+ if (f) {
+ fclose(f);
+ } else {
+ fprintf(stderr, "%s not found", buf);
+ }
+
+/* Check the test dir */
+#ifdef _WIN32
+ strcpy(buf, wd);
+ strcat(buf, "\\test");
+#else
+ strcpy(buf, wd);
+ strcat(buf, "/test");
+#endif
+
+ memset(&st, 0, sizeof(st));
+ ret = stat(buf, &st);
+
+ if (ret) {
+ fprintf(stderr, "%s not found", buf);
+ }
+
+
+#ifdef _WIN32
+/* Try to copy the files required for AppVeyor */
+#if defined(_WIN64) || defined(__MINGW64__)
+ (void)system("cmd /c copy C:\\OpenSSL-Win64\\libeay32.dll libeay32.dll");
+ (void)system("cmd /c copy C:\\OpenSSL-Win64\\libssl32.dll libssl32.dll");
+ (void)system("cmd /c copy C:\\OpenSSL-Win64\\ssleay32.dll ssleay32.dll");
+ (void)system("cmd /c copy C:\\OpenSSL-Win64\\libeay32.dll libeay64.dll");
+ (void)system("cmd /c copy C:\\OpenSSL-Win64\\libssl32.dll libssl64.dll");
+ (void)system("cmd /c copy C:\\OpenSSL-Win64\\ssleay32.dll ssleay64.dll");
+#else
+ (void)system("cmd /c copy C:\\OpenSSL-Win32\\libeay32.dll libeay32.dll");
+ (void)system("cmd /c copy C:\\OpenSSL-Win32\\libssl32.dll libssl32.dll");
+ (void)system("cmd /c copy C:\\OpenSSL-Win32\\ssleay32.dll ssleay32.dll");
+#endif
+#endif
+}
+END_TEST
+
+
+static void *threading_data = 0;
+
+static void *
+test_thread_func_t(void *param)
+{
+ ck_assert_ptr_eq(param, &threading_data);
+ ck_assert_ptr_eq(threading_data, NULL);
+ threading_data = &threading_data;
+ return NULL;
+}
+
+
+START_TEST(test_threading)
+{
+ int ok;
+
+ threading_data = NULL;
+ mark_point();
+
+ ok = mg_start_thread(test_thread_func_t, &threading_data);
+ ck_assert_int_eq(ok, 0);
+
+ wait_not_null(&threading_data);
+ ck_assert_ptr_eq(threading_data, &threading_data);
+}
+END_TEST
+
+
+static int
+log_msg_func(const struct mg_connection *conn, const char *message)
+{
+ struct mg_context *ctx;
+ char *ud;
+
+ ck_assert(conn != NULL);
+ ctx = mg_get_context(conn);
+ ck_assert(ctx != NULL);
+ ud = (char *)mg_get_user_data(ctx);
+
+ strncpy(ud, message, 255);
+ ud[255] = 0;
+ mark_point();
+
+ printf("LOG_MSG_FUNC: %s\n", message);
+ mark_point();
+
+ return 1; /* Return 1 means "already handled" */
+}
+
+
+static int
+test_log_message(const struct mg_connection *conn, const char *message)
+{
+ (void)conn;
+
+ printf("LOG_MESSAGE: %s\n", message);
+ mark_point();
+
+ return 0; /* Return 0 means "not yet handled" */
+}
+
+
+static struct mg_context *
+test_mg_start(const struct mg_callbacks *callbacks,
+ void *user_data,
+ const char **configuration_options)
+{
+ struct mg_context *ctx;
+ struct mg_callbacks cb;
+
+ if (callbacks) {
+ memcpy(&cb, callbacks, sizeof(cb));
+ } else {
+ memset(&cb, 0, sizeof(cb));
+ }
+
+ if (cb.log_message == NULL) {
+ cb.log_message = test_log_message;
+ }
+
+ mark_point();
+ test_sleep(SLEEP_BEFORE_MG_START);
+ mark_point();
+ ctx = mg_start(&cb, user_data, configuration_options);
+ mark_point();
+ if (ctx) {
+ /* Give the server some time to start in the test VM */
+ /* Don't need to do this if mg_start failed */
+ test_sleep(SLEEP_AFTER_MG_START);
+ }
+ mark_point();
+
+ return ctx;
+}
+
+
+static void
+test_mg_stop(struct mg_context *ctx)
+{
+#ifdef __MACH__
+ /* For unknown reasons, there are sporadic hands
+ * for OSX if mark_point is called here */
+ test_sleep(SLEEP_BEFORE_MG_STOP);
+ mg_stop(ctx);
+ test_sleep(SLEEP_AFTER_MG_STOP);
+#else
+ mark_point();
+ test_sleep(SLEEP_BEFORE_MG_STOP);
+ mark_point();
+ mg_stop(ctx);
+ mark_point();
+ test_sleep(SLEEP_AFTER_MG_STOP);
+ mark_point();
+#endif
+}
+
+
+static void
+test_mg_start_stop_http_server_impl(int ipv6)
+{
+ struct mg_context *ctx;
+ const char *OPTIONS[16];
+ int optcnt = 0;
+ const char *localhost_name = ((ipv6) ? "[::1]" : "127.0.0.1");
+
+#if defined(MG_LEGACY_INTERFACE)
+ size_t ports_cnt;
+ int ports[16];
+ int ssl[16];
+#endif
+ struct mg_callbacks callbacks;
+ char errmsg[256];
+
+ struct mg_connection *client_conn;
+ char client_err[256];
+ const struct mg_request_info *client_ri;
+ int client_res, ret;
+ struct mg_server_ports portinfo[8];
+
+ mark_point();
+
+#if !defined(NO_FILES)
+ OPTIONS[optcnt++] = "document_root";
+ OPTIONS[optcnt++] = ".";
+#endif
+ OPTIONS[optcnt++] = "listening_ports";
+ OPTIONS[optcnt++] = ((ipv6) ? "+8080" : "8080");
+ OPTIONS[optcnt] = 0;
+
+#if defined(MG_LEGACY_INTERFACE)
+ memset(ports, 0, sizeof(ports));
+ memset(ssl, 0, sizeof(ssl));
+#endif
+ memset(portinfo, 0, sizeof(portinfo));
+ memset(&callbacks, 0, sizeof(callbacks));
+ memset(errmsg, 0, sizeof(errmsg));
+
+ callbacks.log_message = log_msg_func;
+
+ ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS);
+
+ ck_assert_str_eq(errmsg, "");
+ ck_assert(ctx != NULL);
+
+#if defined(MG_LEGACY_INTERFACE)
+ ports_cnt = mg_get_ports(ctx, 16, ports, ssl);
+ ck_assert_uint_eq(ports_cnt, 1);
+ ck_assert_int_eq(ports[0], 8080);
+ ck_assert_int_eq(ssl[0], 0);
+ ck_assert_int_eq(ports[1], 0);
+ ck_assert_int_eq(ssl[1], 0);
+#endif
+
+ ret = mg_get_server_ports(ctx, 0, portinfo);
+ ck_assert_int_lt(ret, 0);
+ ck_assert_int_eq(portinfo[0].protocol, 0);
+ ck_assert_int_eq(portinfo[0].port, 0);
+ ck_assert_int_eq(portinfo[0].is_ssl, 0);
+ ck_assert_int_eq(portinfo[0].is_redirect, 0);
+ ck_assert_int_eq(portinfo[1].protocol, 0);
+ ck_assert_int_eq(portinfo[1].port, 0);
+ ck_assert_int_eq(portinfo[1].is_ssl, 0);
+ ck_assert_int_eq(portinfo[1].is_redirect, 0);
+
+ ret = mg_get_server_ports(ctx, 4, portinfo);
+ ck_assert_int_eq(ret, 1);
+ if (ipv6) {
+ ck_assert_int_eq(portinfo[0].protocol, 3);
+ } else {
+ ck_assert_int_eq(portinfo[0].protocol, 1);
+ }
+ ck_assert_int_eq(portinfo[0].port, 8080);
+ ck_assert_int_eq(portinfo[0].is_ssl, 0);
+ ck_assert_int_eq(portinfo[0].is_redirect, 0);
+ ck_assert_int_eq(portinfo[1].protocol, 0);
+ ck_assert_int_eq(portinfo[1].port, 0);
+ ck_assert_int_eq(portinfo[1].is_ssl, 0);
+ ck_assert_int_eq(portinfo[1].is_redirect, 0);
+
+ test_sleep(1);
+
+ /* HTTP 1.0 GET request */
+ memset(client_err, 0, sizeof(client_err));
+ client_conn = mg_connect_client(
+ localhost_name, 8080, 0, client_err, sizeof(client_err));
+
+ ck_assert_str_eq(client_err, "");
+ ck_assert(client_conn != NULL);
+
+ mg_printf(client_conn, "GET / HTTP/1.0\r\n\r\n");
+ client_res =
+ mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
+ ck_assert_int_ge(client_res, 0);
+ ck_assert_str_eq(client_err, "");
+ client_ri = mg_get_request_info(client_conn);
+ ck_assert(client_ri != NULL);
+
+#if defined(NO_FILES)
+ ck_assert_str_eq(client_ri->local_uri, "404");
+#else
+ ck_assert_str_eq(client_ri->local_uri, "200");
+ /* TODO: ck_assert_str_eq(client_ri->request_method, "HTTP/1.0"); */
+ client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
+ ck_assert_int_gt(client_res, 0);
+ ck_assert_int_le(client_res, sizeof(client_err));
+#endif
+ mg_close_connection(client_conn);
+
+ test_sleep(1);
+
+ /* HTTP 1.1 GET request */
+ memset(client_err, 0, sizeof(client_err));
+ client_conn = mg_connect_client(
+ localhost_name, 8080, 0, client_err, sizeof(client_err));
+
+ ck_assert_str_eq(client_err, "");
+ ck_assert(client_conn != NULL);
+
+ mg_printf(client_conn, "GET / HTTP/1.1\r\n");
+ mg_printf(client_conn, "Host: localhost:8080\r\n");
+ mg_printf(client_conn, "Connection: close\r\n\r\n");
+ client_res =
+ mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
+ ck_assert_int_ge(client_res, 0);
+ ck_assert_str_eq(client_err, "");
+ client_ri = mg_get_request_info(client_conn);
+ ck_assert(client_ri != NULL);
+
+#if defined(NO_FILES)
+ ck_assert_str_eq(client_ri->local_uri, "404");
+#else
+ ck_assert_str_eq(client_ri->local_uri, "200");
+ /* TODO: ck_assert_str_eq(client_ri->request_method, "HTTP/1.0"); */
+ client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
+ ck_assert_int_gt(client_res, 0);
+ ck_assert_int_le(client_res, sizeof(client_err));
+#endif
+ mg_close_connection(client_conn);
+
+ test_sleep(1);
+
+
+ /* HTTP 1.7 GET request - this HTTP version does not exist */
+ memset(client_err, 0, sizeof(client_err));
+ client_conn = mg_connect_client(
+ localhost_name, 8080, 0, client_err, sizeof(client_err));
+
+ ck_assert_str_eq(client_err, "");
+ ck_assert(client_conn != NULL);
+
+ mg_printf(client_conn, "GET / HTTP/1.7\r\n");
+ mg_printf(client_conn, "Host: localhost:8080\r\n");
+ mg_printf(client_conn, "Connection: close\r\n\r\n");
+ client_res =
+ mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
+ ck_assert_int_ge(client_res, 0);
+ ck_assert_str_eq(client_err, "");
+ client_ri = mg_get_request_info(client_conn);
+ ck_assert(client_ri != NULL);
+
+ /* Response must be 505 HTTP Version not supported */
+ ck_assert_str_eq(client_ri->local_uri, "505");
+ mg_close_connection(client_conn);
+
+ test_sleep(1);
+
+
+ /* HTTP request with multiline header.
+ * Multiline header are obsolete with RFC 7230 section-3.2.4
+ * and must return "400 Bad Request" */
+ memset(client_err, 0, sizeof(client_err));
+ client_conn = mg_connect_client(
+ localhost_name, 8080, 0, client_err, sizeof(client_err));
+
+ ck_assert_str_eq(client_err, "");
+ ck_assert(client_conn != NULL);
+
+ mg_printf(client_conn, "GET / HTTP/1.1\r\n");
+ mg_printf(client_conn, "Host: localhost:8080\r\n");
+ mg_printf(client_conn, "X-Obsolete-Header: something\r\nfor nothing\r\n");
+ mg_printf(client_conn, "Connection: close\r\n\r\n");
+ client_res =
+ mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
+ ck_assert_int_ge(client_res, 0);
+ ck_assert_str_eq(client_err, "");
+ client_ri = mg_get_request_info(client_conn);
+ ck_assert(client_ri != NULL);
+
+ /* Response must be 400 Bad Request */
+ ck_assert_str_eq(client_ri->local_uri, "400");
+ mg_close_connection(client_conn);
+
+ test_sleep(1);
+
+ /* End test */
+ test_mg_stop(ctx);
+ mark_point();
+}
+
+
+START_TEST(test_mg_start_stop_http_server)
+{
+ mark_point();
+ test_mg_start_stop_http_server_impl(0);
+ mark_point();
+}
+END_TEST
+
+
+START_TEST(test_mg_start_stop_http_server_ipv6)
+{
+ mark_point();
+#if defined(USE_IPV6)
+ test_mg_start_stop_http_server_impl(1);
+#endif
+ mark_point();
+}
+END_TEST
+
+
+START_TEST(test_mg_start_stop_https_server)
+{
+#ifndef NO_SSL
+
+ struct mg_context *ctx;
+
+#if defined(MG_LEGACY_INTERFACE)
+ size_t ports_cnt;
+ int ports[16];
+ int ssl[16];
+#endif
+ struct mg_callbacks callbacks;
+ char errmsg[256];
+
+ const char *OPTIONS[8]; /* initializer list here is rejected by CI test */
+ int opt_idx = 0;
+ const char *ssl_cert = locate_ssl_cert();
+
+ struct mg_connection *client_conn;
+ char client_err[256];
+ const struct mg_request_info *client_ri;
+ int client_res, ret;
+ struct mg_server_ports portinfo[8];
+
+ ck_assert(ssl_cert != NULL);
+
+ memset((void *)OPTIONS, 0, sizeof(OPTIONS));
+#if !defined(NO_FILES)
+ OPTIONS[opt_idx++] = "document_root";
+ OPTIONS[opt_idx++] = ".";
+#endif
+ OPTIONS[opt_idx++] = "listening_ports";
+ OPTIONS[opt_idx++] = "8080r,8443s";
+ OPTIONS[opt_idx++] = "ssl_certificate";
+ OPTIONS[opt_idx++] = ssl_cert;
+
+ ck_assert_int_le(opt_idx, (int)(sizeof(OPTIONS) / sizeof(OPTIONS[0])));
+ ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 1] == NULL);
+ ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 2] == NULL);
+
+#if defined(MG_LEGACY_INTERFACE)
+ memset(ports, 0, sizeof(ports));
+ memset(ssl, 0, sizeof(ssl));
+#endif
+ memset(portinfo, 0, sizeof(portinfo));
+ memset(&callbacks, 0, sizeof(callbacks));
+ memset(errmsg, 0, sizeof(errmsg));
+
+ callbacks.log_message = log_msg_func;
+
+ ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS);
+
+ ck_assert_str_eq(errmsg, "");
+ ck_assert(ctx != NULL);
+
+#if defined(MG_LEGACY_INTERFACE)
+ ports_cnt = mg_get_ports(ctx, 16, ports, ssl);
+ ck_assert_uint_eq(ports_cnt, 2);
+ ck_assert_int_eq(ports[0], 8080);
+ ck_assert_int_eq(ssl[0], 0);
+ ck_assert_int_eq(ports[1], 8443);
+ ck_assert_int_eq(ssl[1], 1);
+ ck_assert_int_eq(ports[2], 0);
+ ck_assert_int_eq(ssl[2], 0);
+#endif
+
+ ret = mg_get_server_ports(ctx, 0, portinfo);
+ ck_assert_int_lt(ret, 0);
+ ck_assert_int_eq(portinfo[0].protocol, 0);
+ ck_assert_int_eq(portinfo[0].port, 0);
+ ck_assert_int_eq(portinfo[0].is_ssl, 0);
+ ck_assert_int_eq(portinfo[0].is_redirect, 0);
+ ck_assert_int_eq(portinfo[1].protocol, 0);
+ ck_assert_int_eq(portinfo[1].port, 0);
+ ck_assert_int_eq(portinfo[1].is_ssl, 0);
+ ck_assert_int_eq(portinfo[1].is_redirect, 0);
+
+ ret = mg_get_server_ports(ctx, 4, portinfo);
+ ck_assert_int_eq(ret, 2);
+ ck_assert_int_eq(portinfo[0].protocol, 1);
+ ck_assert_int_eq(portinfo[0].port, 8080);
+ ck_assert_int_eq(portinfo[0].is_ssl, 0);
+ ck_assert_int_eq(portinfo[0].is_redirect, 1);
+ ck_assert_int_eq(portinfo[1].protocol, 1);
+ ck_assert_int_eq(portinfo[1].port, 8443);
+ ck_assert_int_eq(portinfo[1].is_ssl, 1);
+ ck_assert_int_eq(portinfo[1].is_redirect, 0);
+ ck_assert_int_eq(portinfo[2].protocol, 0);
+ ck_assert_int_eq(portinfo[2].port, 0);
+ ck_assert_int_eq(portinfo[2].is_ssl, 0);
+ ck_assert_int_eq(portinfo[2].is_redirect, 0);
+
+ test_sleep(1);
+
+ memset(client_err, 0, sizeof(client_err));
+ client_conn =
+ mg_connect_client("127.0.0.1", 8443, 1, client_err, sizeof(client_err));
+
+ ck_assert_str_eq(client_err, "");
+ ck_assert(client_conn != NULL);
+
+ mg_printf(client_conn, "GET / HTTP/1.0\r\n\r\n");
+ client_res =
+ mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
+ ck_assert_int_ge(client_res, 0);
+ ck_assert_str_eq(client_err, "");
+ client_ri = mg_get_request_info(client_conn);
+ ck_assert(client_ri != NULL);
+
+#if defined(NO_FILES)
+ ck_assert_str_eq(client_ri->local_uri, "404");
+#else
+ ck_assert_str_eq(client_ri->local_uri, "200");
+ /* TODO: ck_assert_str_eq(client_ri->request_method, "HTTP/1.0"); */
+ client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
+ ck_assert_int_gt(client_res, 0);
+ ck_assert_int_le(client_res, sizeof(client_err));
+#endif
+ mg_close_connection(client_conn);
+
+ test_sleep(1);
+
+ test_mg_stop(ctx);
+ mark_point();
+#endif
+}
+END_TEST
+
+
+START_TEST(test_mg_server_and_client_tls)
+{
+#ifndef NO_SSL
+
+ struct mg_context *ctx;
+
+ int ports_cnt;
+ struct mg_server_ports ports[16];
+ struct mg_callbacks callbacks;
+ char errmsg[256];
+
+ struct mg_connection *client_conn;
+ char client_err[256];
+ const struct mg_request_info *client_ri;
+ int client_res;
+ struct mg_client_options client_options;
+
+ const char *OPTIONS[32]; /* initializer list here is rejected by CI test */
+ int opt_idx = 0;
+ char server_cert[256];
+ char client_cert[256];
+ const char *res_dir = locate_resources();
+
+ ck_assert(res_dir != NULL);
+ strcpy(server_cert, res_dir);
+ strcpy(client_cert, res_dir);
+#ifdef _WIN32
+ strcat(server_cert, "cert\\server.pem");
+ strcat(client_cert, "cert\\client.pem");
+#else
+ strcat(server_cert, "cert/server.pem");
+ strcat(client_cert, "cert/client.pem");
+#endif
+
+ memset((void *)OPTIONS, 0, sizeof(OPTIONS));
+#if !defined(NO_FILES)
+ OPTIONS[opt_idx++] = "document_root";
+ OPTIONS[opt_idx++] = ".";
+#endif
+ OPTIONS[opt_idx++] = "listening_ports";
+ OPTIONS[opt_idx++] = "8080r,8443s";
+ OPTIONS[opt_idx++] = "ssl_certificate";
+ OPTIONS[opt_idx++] = server_cert;
+ OPTIONS[opt_idx++] = "ssl_verify_peer";
+ OPTIONS[opt_idx++] = "yes";
+ OPTIONS[opt_idx++] = "ssl_ca_file";
+ OPTIONS[opt_idx++] = client_cert;
+
+ ck_assert_int_le(opt_idx, (int)(sizeof(OPTIONS) / sizeof(OPTIONS[0])));
+ ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 1] == NULL);
+ ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 2] == NULL);
+
+ memset(ports, 0, sizeof(ports));
+ memset(&callbacks, 0, sizeof(callbacks));
+ memset(errmsg, 0, sizeof(errmsg));
+
+ callbacks.log_message = log_msg_func;
+
+ ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS);
+
+ ck_assert_str_eq(errmsg, "");
+ ck_assert(ctx != NULL);
+
+ ports_cnt = mg_get_server_ports(ctx, 16, ports);
+ ck_assert_int_eq(ports_cnt, 2);
+ ck_assert_int_eq(ports[0].protocol, 1);
+ ck_assert_int_eq(ports[0].port, 8080);
+ ck_assert_int_eq(ports[0].is_ssl, 0);
+ ck_assert_int_eq(ports[0].is_redirect, 1);
+ ck_assert_int_eq(ports[1].protocol, 1);
+ ck_assert_int_eq(ports[1].port, 8443);
+ ck_assert_int_eq(ports[1].is_ssl, 1);
+ ck_assert_int_eq(ports[1].is_redirect, 0);
+ ck_assert_int_eq(ports[2].protocol, 0);
+ ck_assert_int_eq(ports[2].port, 0);
+ ck_assert_int_eq(ports[2].is_ssl, 0);
+ ck_assert_int_eq(ports[2].is_redirect, 0);
+
+ test_sleep(1);
+
+ memset(client_err, 0, sizeof(client_err));
+ client_conn =
+ mg_connect_client("127.0.0.1", 8443, 1, client_err, sizeof(client_err));
+
+ ck_assert_str_ne(client_err, "");
+ ck_assert(client_conn == NULL);
+
+ memset(client_err, 0, sizeof(client_err));
+ memset(&client_options, 0, sizeof(client_options));
+ client_options.host = "127.0.0.1";
+ client_options.port = 8443;
+ client_options.client_cert = client_cert;
+ client_options.server_cert = server_cert;
+
+ client_conn = mg_connect_client_secure(&client_options,
+ client_err,
+ sizeof(client_err));
+
+ ck_assert_str_eq(client_err, "");
+ ck_assert(client_conn != NULL);
+
+ mg_printf(client_conn, "GET / HTTP/1.0\r\n\r\n");
+ client_res =
+ mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
+ ck_assert_int_ge(client_res, 0);
+ ck_assert_str_eq(client_err, "");
+ client_ri = mg_get_request_info(client_conn);
+ ck_assert(client_ri != NULL);
+
+#if defined(NO_FILES)
+ ck_assert_str_eq(client_ri->local_uri, "404");
+#else
+ ck_assert_str_eq(client_ri->local_uri, "200");
+ /* TODO: ck_assert_str_eq(client_ri->request_method, "HTTP/1.0"); */
+ client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
+ ck_assert_int_gt(client_res, 0);
+ ck_assert_int_le(client_res, sizeof(client_err));
+#endif
+ mg_close_connection(client_conn);
+
+ /* TODO: A client API using a client certificate is missing */
+
+ test_sleep(1);
+
+ test_mg_stop(ctx);
+#endif
+ mark_point();
+}
+END_TEST
+
+
+static struct mg_context *g_ctx;
+
+static int
+request_test_handler(struct mg_connection *conn, void *cbdata)
+{
+ int i;
+ char chunk_data[32];
+ const struct mg_request_info *ri;
+ struct mg_context *ctx;
+ void *ud, *cud;
+ void *dummy = malloc(1);
+
+ ctx = mg_get_context(conn);
+ ud = mg_get_user_data(ctx);
+ ri = mg_get_request_info(conn);
+
+ ck_assert(ri != NULL);
+ ck_assert(ctx == g_ctx);
+ ck_assert(ud == &g_ctx);
+
+ ck_assert(dummy != NULL);
+
+ mg_set_user_connection_data(conn, (void *)&dummy);
+ cud = mg_get_user_connection_data(conn);
+ ck_assert_ptr_eq((void *)cud, (void *)&dummy);
+
+ mg_set_user_connection_data(conn, (void *)NULL);
+ cud = mg_get_user_connection_data(conn);
+ ck_assert_ptr_eq((void *)cud, (void *)NULL);
+
+ free(dummy);
+
+ ck_assert_ptr_eq((void *)cbdata, (void *)(ptrdiff_t)7);
+ strcpy(chunk_data, "123456789A123456789B123456789C");
+
+ mg_printf(conn,
+ "HTTP/1.1 200 OK\r\n"
+ "Transfer-Encoding: chunked\r\n"
+ "Content-Type: text/plain\r\n\r\n");
+
+ for (i = 1; i <= 10; i++) {
+ mg_printf(conn, "%x\r\n", i);
+ mg_write(conn, chunk_data, (unsigned)i);
+ mg_printf(conn, "\r\n");
+ }
+
+ mg_printf(conn, "0\r\n\r\n");
+ mark_point();
+
+ return 1;
+}
+
+
+#ifdef USE_WEBSOCKET
+/****************************************************************************/
+/* WEBSOCKET SERVER */
+/****************************************************************************/
+static const char *websocket_welcome_msg = "websocket welcome\n";
+static const size_t websocket_welcome_msg_len =
+ 18 /* strlen(websocket_welcome_msg) */;
+static const char *websocket_goodbye_msg = "websocket bye\n";
+static const size_t websocket_goodbye_msg_len =
+ 14 /* strlen(websocket_goodbye_msg) */;
+
+
+#if defined(DEBUG)
+static void
+WS_TEST_TRACE(const char *f, ...)
+{
+ va_list l;
+ va_start(l, f);
+ vprintf(f, l);
+ va_end(l);
+}
+#else
+#define WS_TEST_TRACE(...)
+#endif
+
+
+static int
+websock_server_connect(const struct mg_connection *conn, void *udata)
+{
+ (void)conn;
+
+ ck_assert_ptr_eq((void *)udata, (void *)(ptrdiff_t)7531);
+ WS_TEST_TRACE("Server: Websocket connected\n");
+ mark_point();
+
+ return 0; /* return 0 to accept every connection */
+}
+
+
+static void
+websock_server_ready(struct mg_connection *conn, void *udata)
+{
+ ck_assert_ptr_eq((void *)udata, (void *)(ptrdiff_t)7531);
+ ck_assert_ptr_ne((void *)conn, (void *)NULL);
+ WS_TEST_TRACE("Server: Websocket ready\n");
+
+ /* Send websocket welcome message */
+ mg_lock_connection(conn);
+ mg_websocket_write(conn,
+ WEBSOCKET_OPCODE_TEXT,
+ websocket_welcome_msg,
+ websocket_welcome_msg_len);
+ mg_unlock_connection(conn);
+
+ WS_TEST_TRACE("Server: Websocket ready X\n");
+ mark_point();
+}
+
+
+#define long_ws_buf_len_16 (500)
+#define long_ws_buf_len_64 (70000)
+static char long_ws_buf[long_ws_buf_len_64];
+
+
+static int
+websock_server_data(struct mg_connection *conn,
+ int bits,
+ char *data,
+ size_t data_len,
+ void *udata)
+{
+ (void)bits;
+
+ ck_assert_ptr_eq((void *)udata, (void *)(ptrdiff_t)7531);
+ WS_TEST_TRACE("Server: Got %u bytes from the client\n", (unsigned)data_len);
+
+ if (data_len == 3 && !memcmp(data, "bye", 3)) {
+ /* Send websocket goodbye message */
+ mg_lock_connection(conn);
+ mg_websocket_write(conn,
+ WEBSOCKET_OPCODE_TEXT,
+ websocket_goodbye_msg,
+ websocket_goodbye_msg_len);
+ mg_unlock_connection(conn);
+ } else if (data_len == 5 && !memcmp(data, "data1", 5)) {
+ mg_lock_connection(conn);
+ mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, "ok1", 3);
+ mg_unlock_connection(conn);
+ } else if (data_len == 5 && !memcmp(data, "data2", 5)) {
+ mg_lock_connection(conn);
+ mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, "ok 2", 4);
+ mg_unlock_connection(conn);
+ } else if (data_len == 5 && !memcmp(data, "data3", 5)) {
+ mg_lock_connection(conn);
+ mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, "ok - 3", 6);
+ mg_unlock_connection(conn);
+ } else if (data_len == long_ws_buf_len_16) {
+ ck_assert(memcmp(data, long_ws_buf, long_ws_buf_len_16) == 0);
+ mg_lock_connection(conn);
+ mg_websocket_write(conn,
+ WEBSOCKET_OPCODE_BINARY,
+ long_ws_buf,
+ long_ws_buf_len_16);
+ mg_unlock_connection(conn);
+ } else if (data_len == long_ws_buf_len_64) {
+ ck_assert(memcmp(data, long_ws_buf, long_ws_buf_len_64) == 0);
+ mg_lock_connection(conn);
+ mg_websocket_write(conn,
+ WEBSOCKET_OPCODE_BINARY,
+ long_ws_buf,
+ long_ws_buf_len_64);
+ mg_unlock_connection(conn);
+ } else {
+
+#if defined(__MINGW32__) || defined(__GNUC__)
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wunreachable-code"
+#endif
+#ifdef __clang__
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wunreachable-code"
+#endif
+
+ ck_abort_msg("Got unexpected message from websocket client");
+
+
+ return 0;
+
+#ifdef __clang__
+#pragma clang diagnostic pop
+#endif
+#if defined(__MINGW32__) || defined(__GNUC__)
+#pragma GCC diagnostic pop
+#endif
+ }
+ mark_point();
+
+ return 1; /* return 1 to keep the connetion open */
+}
+
+
+static void
+websock_server_close(const struct mg_connection *conn, void *udata)
+{
+#ifndef __MACH__
+ ck_assert_ptr_eq((void *)udata, (void *)(ptrdiff_t)7531);
+ WS_TEST_TRACE("Server: Close connection\n");
+
+ /* Can not send a websocket goodbye message here -
+ * the connection is already closed */
+
+ mark_point();
+#endif
+
+ (void)conn;
+ (void)udata;
+}
+
+
+/****************************************************************************/
+/* WEBSOCKET CLIENT */
+/****************************************************************************/
+struct tclient_data {
+ void *data;
+ size_t len;
+ int closed;
+ int clientId;
+};
+
+
+static int
+websocket_client_data_handler(struct mg_connection *conn,
+ int flags,
+ char *data,
+ size_t data_len,
+ void *user_data)
+{
+ struct mg_context *ctx = mg_get_context(conn);
+ struct tclient_data *pclient_data =
+ (struct tclient_data *)mg_get_user_data(ctx);
+
+ ck_assert_ptr_eq(user_data, (void *)pclient_data);
+
+ ck_assert(pclient_data != NULL);
+ ck_assert_int_gt(flags, 128);
+ ck_assert_int_lt(flags, 128 + 16);
+ ck_assert((flags == (int)(128 | WEBSOCKET_OPCODE_BINARY))
+ || (flags == (int)(128 | WEBSOCKET_OPCODE_TEXT)));
+
+ if (flags == (int)(128 | WEBSOCKET_OPCODE_TEXT)) {
+ WS_TEST_TRACE(
+ "Client %i received %lu bytes text data from server: %.*s\n",
+ pclient_data->clientId,
+ (unsigned long)data_len,
+ (int)data_len,
+ data);
+ } else {
+ WS_TEST_TRACE("Client %i received %lu bytes binary data from\n",
+ pclient_data->clientId,
+ (unsigned long)data_len);
+ }
+
+ pclient_data->data = malloc(data_len);
+ ck_assert(pclient_data->data != NULL);
+ memcpy(pclient_data->data, data, data_len);
+ pclient_data->len = data_len;
+
+ mark_point();
+
+ return 1;
+}
+
+
+static void
+websocket_client_close_handler(const struct mg_connection *conn,
+ void *user_data)
+{
+ struct mg_context *ctx = mg_get_context(conn);
+ struct tclient_data *pclient_data =
+ (struct tclient_data *)mg_get_user_data(ctx);
+
+#ifndef __MACH__
+ ck_assert_ptr_eq(user_data, (void *)pclient_data);
+
+ ck_assert(pclient_data != NULL);
+
+ WS_TEST_TRACE("Client %i: Close handler\n", pclient_data->clientId);
+ pclient_data->closed++;
+
+ mark_point();
+#else
+
+ (void)user_data;
+ pclient_data->closed++;
+
+#endif /* __MACH__ */
+}
+
+#endif /* USE_WEBSOCKET */
+
+
+START_TEST(test_request_handlers)
+{
+ char ebuf[100];
+ struct mg_context *ctx;
+ struct mg_connection *client_conn;
+ const struct mg_request_info *ri;
+ char uri[64];
+ char buf[1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 8];
+ const char *expected =
+ "112123123412345123456123456712345678123456789123456789A";
+ int i;
+ const char *request = "GET /U7 HTTP/1.0\r\n\r\n";
+#if defined(USE_IPV6) && defined(NO_SSL)
+ const char *HTTP_PORT = "8084,[::]:8086";
+ short ipv4_port = 8084;
+ short ipv6_port = 8086;
+#elif !defined(USE_IPV6) && defined(NO_SSL)
+ const char *HTTP_PORT = "8084";
+ short ipv4_port = 8084;
+#elif defined(USE_IPV6) && !defined(NO_SSL)
+ const char *HTTP_PORT = "8084,[::]:8086,8194r,[::]:8196r,8094s,[::]:8096s";
+ short ipv4_port = 8084;
+ short ipv4s_port = 8094;
+ short ipv4r_port = 8194;
+ short ipv6_port = 8086;
+ short ipv6s_port = 8096;
+ short ipv6r_port = 8196;
+#elif !defined(USE_IPV6) && !defined(NO_SSL)
+ const char *HTTP_PORT = "8084,8194r,8094s";
+ short ipv4_port = 8084;
+ short ipv4s_port = 8094;
+ short ipv4r_port = 8194;
+#endif
+
+ const char *OPTIONS[16];
+ const char *opt;
+ FILE *f;
+ const char *plain_file_content;
+ const char *encoded_file_content;
+ const char *cgi_script_content;
+ const char *expected_cgi_result;
+ int opt_idx = 0;
+ struct stat st;
+
+#if !defined(NO_SSL)
+ const char *ssl_cert = locate_ssl_cert();
+#endif
+
+#if defined(USE_WEBSOCKET)
+ struct tclient_data ws_client1_data = {NULL, 0, 0, 1};
+ struct tclient_data ws_client2_data = {NULL, 0, 0, 2};
+ struct tclient_data ws_client3_data = {NULL, 0, 0, 3};
+ struct tclient_data ws_client4_data = {NULL, 0, 0, 4};
+ struct mg_connection *ws_client1_conn = NULL;
+ struct mg_connection *ws_client2_conn = NULL;
+ struct mg_connection *ws_client3_conn = NULL;
+ struct mg_connection *ws_client4_conn = NULL;
+#endif
+
+ char cmd_buf[256];
+ char *cgi_env_opt;
+
+ mark_point();
+
+ memset((void *)OPTIONS, 0, sizeof(OPTIONS));
+ OPTIONS[opt_idx++] = "listening_ports";
+ OPTIONS[opt_idx++] = HTTP_PORT;
+ OPTIONS[opt_idx++] = "authentication_domain";
+ OPTIONS[opt_idx++] = "test.domain";
+#if !defined(NO_FILES)
+ OPTIONS[opt_idx++] = "document_root";
+ OPTIONS[opt_idx++] = ".";
+#endif
+#ifndef NO_SSL
+ ck_assert(ssl_cert != NULL);
+ OPTIONS[opt_idx++] = "ssl_certificate";
+ OPTIONS[opt_idx++] = ssl_cert;
+#endif
+ OPTIONS[opt_idx++] = "cgi_environment";
+ cgi_env_opt = (char *)calloc(1, 4096 /* CGI_ENVIRONMENT_SIZE */);
+ ck_assert_ptr_ne(cgi_env_opt, NULL);
+ cgi_env_opt[0] = 'x';
+ cgi_env_opt[1] = '=';
+ memset(cgi_env_opt + 2, 'y', 4090); /* Add large env field, so the server
+ * must reallocate buffers. */
+ OPTIONS[opt_idx++] = cgi_env_opt;
+
+ OPTIONS[opt_idx++] = "num_threads";
+ OPTIONS[opt_idx++] = "2";
+
+
+ ck_assert_int_le(opt_idx, (int)(sizeof(OPTIONS) / sizeof(OPTIONS[0])));
+ ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 1] == NULL);
+ ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 2] == NULL);
+
+ ctx = test_mg_start(NULL, &g_ctx, OPTIONS);
+
+ ck_assert(ctx != NULL);
+ g_ctx = ctx;
+
+ opt = mg_get_option(ctx, "listening_ports");
+ ck_assert_str_eq(opt, HTTP_PORT);
+
+ opt = mg_get_option(ctx, "cgi_environment");
+ ck_assert_ptr_ne(opt, cgi_env_opt);
+ ck_assert_int_eq((int)opt[0], (int)cgi_env_opt[0]);
+ ck_assert_int_eq((int)opt[1], (int)cgi_env_opt[1]);
+ ck_assert_int_eq((int)opt[2], (int)cgi_env_opt[2]);
+ ck_assert_int_eq((int)opt[3], (int)cgi_env_opt[3]);
+ /* full length string compare will reach limit in the implementation
+ * of the check unit test framework */
+ {
+ size_t len_check_1 = strlen(opt);
+ size_t len_check_2 = strlen(cgi_env_opt);
+ ck_assert_uint_eq(len_check_1, len_check_2);
+ }
+
+ /* We don't need the original anymore, the server has a private copy */
+ free(cgi_env_opt);
+
+ opt = mg_get_option(ctx, "throttle");
+ ck_assert_str_eq(opt, "");
+
+ opt = mg_get_option(ctx, "unknown_option_name");
+ ck_assert(opt == NULL);
+
+ for (i = 0; i < 1000; i++) {
+ sprintf(uri, "/U%u", i);
+ mg_set_request_handler(ctx, uri, request_test_handler, NULL);
+ }
+ for (i = 500; i < 800; i++) {
+ sprintf(uri, "/U%u", i);
+ mg_set_request_handler(ctx, uri, NULL, (void *)(ptrdiff_t)1);
+ }
+ for (i = 600; i >= 0; i--) {
+ sprintf(uri, "/U%u", i);
+ mg_set_request_handler(ctx, uri, NULL, (void *)(ptrdiff_t)2);
+ }
+ for (i = 750; i <= 1000; i++) {
+ sprintf(uri, "/U%u", i);
+ mg_set_request_handler(ctx, uri, NULL, (void *)(ptrdiff_t)3);
+ }
+ for (i = 5; i < 9; i++) {
+ sprintf(uri, "/U%u", i);
+ mg_set_request_handler(ctx,
+ uri,
+ request_test_handler,
+ (void *)(ptrdiff_t)i);
+ }
+
+#ifdef USE_WEBSOCKET
+ mg_set_websocket_handler(ctx,
+ "/websocket",
+ websock_server_connect,
+ websock_server_ready,
+ websock_server_data,
+ websock_server_close,
+ (void *)(ptrdiff_t)7531);
+#endif
+
+ /* Try to load non existing file */
+ client_conn = mg_download("localhost",
+ ipv4_port,
+ 0,
+ ebuf,
+ sizeof(ebuf),
+ "%s",
+ "GET /file/not/found HTTP/1.0\r\n\r\n");
+ ck_assert(client_conn != NULL);
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "404");
+ mg_close_connection(client_conn);
+
+ /* Get data from callback */
+ client_conn = mg_download(
+ "localhost", ipv4_port, 0, ebuf, sizeof(ebuf), "%s", request);
+ ck_assert(client_conn != NULL);
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "200");
+ i = mg_read(client_conn, buf, sizeof(buf));
+ ck_assert_int_eq(i, (int)strlen(expected));
+ buf[i] = 0;
+ ck_assert_str_eq(buf, expected);
+ mg_close_connection(client_conn);
+
+ /* Get data from callback using http://127.0.0.1 */
+ client_conn = mg_download(
+ "127.0.0.1", ipv4_port, 0, ebuf, sizeof(ebuf), "%s", request);
+ ck_assert(client_conn != NULL);
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "200");
+ i = mg_read(client_conn, buf, sizeof(buf));
+ if ((i >= 0) && ((size_t)i < sizeof(buf))) {
+ buf[i] = 0;
+ } else {
+ ck_abort_msg(
+ "ERROR: test_request_handlers: read returned %i (>=0, <%i)",
+ (int)i,
+ (int)sizeof(buf));
+ }
+ ck_assert((int)i < (int)sizeof(buf));
+ ck_assert(i > 0);
+ ck_assert_int_eq(i, (int)strlen(expected));
+ buf[i] = 0;
+ ck_assert_str_eq(buf, expected);
+ mg_close_connection(client_conn);
+
+#if defined(USE_IPV6)
+ /* Get data from callback using http://[::1] */
+ client_conn =
+ mg_download("[::1]", ipv6_port, 0, ebuf, sizeof(ebuf), "%s", request);
+ ck_assert(client_conn != NULL);
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "200");
+ i = mg_read(client_conn, buf, sizeof(buf));
+ ck_assert_int_eq(i, (int)strlen(expected));
+ buf[i] = 0;
+ ck_assert_str_eq(buf, expected);
+ mg_close_connection(client_conn);
+#endif
+
+#if !defined(NO_SSL)
+ /* Get data from callback using https://127.0.0.1 */
+ client_conn = mg_download(
+ "127.0.0.1", ipv4s_port, 1, ebuf, sizeof(ebuf), "%s", request);
+ ck_assert(client_conn != NULL);
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "200");
+ i = mg_read(client_conn, buf, sizeof(buf));
+ ck_assert_int_eq(i, (int)strlen(expected));
+ buf[i] = 0;
+ ck_assert_str_eq(buf, expected);
+ mg_close_connection(client_conn);
+
+ /* Get redirect from callback using http://127.0.0.1 */
+ client_conn = mg_download(
+ "127.0.0.1", ipv4r_port, 0, ebuf, sizeof(ebuf), "%s", request);
+ ck_assert(client_conn != NULL);
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "302");
+ i = mg_read(client_conn, buf, sizeof(buf));
+ ck_assert_int_eq(i, -1);
+ mg_close_connection(client_conn);
+#endif
+
+#if defined(USE_IPV6) && !defined(NO_SSL)
+ /* Get data from callback using https://[::1] */
+ client_conn =
+ mg_download("[::1]", ipv6s_port, 1, ebuf, sizeof(ebuf), "%s", request);
+ ck_assert(client_conn != NULL);
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "200");
+ i = mg_read(client_conn, buf, sizeof(buf));
+ ck_assert_int_eq(i, (int)strlen(expected));
+ buf[i] = 0;
+ ck_assert_str_eq(buf, expected);
+ mg_close_connection(client_conn);
+
+ /* Get redirect from callback using http://127.0.0.1 */
+ client_conn =
+ mg_download("[::1]", ipv6r_port, 0, ebuf, sizeof(ebuf), "%s", request);
+ ck_assert(client_conn != NULL);
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "302");
+ i = mg_read(client_conn, buf, sizeof(buf));
+ ck_assert_int_eq(i, -1);
+ mg_close_connection(client_conn);
+#endif
+
+/* It seems to be impossible to find out what the actual working
+ * directory of the CI test environment is. Before breaking another
+ * dozen of builds by trying blindly with different paths, just
+ * create the file here */
+#ifdef _WIN32
+ f = fopen("test.txt", "wb");
+#else
+ f = fopen("test.txt", "w");
+#endif
+ plain_file_content = "simple text file\n";
+ fwrite(plain_file_content, 17, 1, f);
+ fclose(f);
+
+#ifdef _WIN32
+ f = fopen("test_gz.txt.gz", "wb");
+#else
+ f = fopen("test_gz.txt.gz", "w");
+#endif
+ encoded_file_content = "\x1f\x8b\x08\x08\xf8\x9d\xcb\x55\x00\x00"
+ "test_gz.txt"
+ "\x00\x01\x11\x00\xee\xff"
+ "zipped text file"
+ "\x0a\x34\x5f\xcc\x49\x11\x00\x00\x00";
+ fwrite(encoded_file_content, 1, 52, f);
+ fclose(f);
+
+#ifdef _WIN32
+ f = fopen("test.cgi", "wb");
+ cgi_script_content = "#!test.cgi.cmd\r\n";
+ fwrite(cgi_script_content, strlen(cgi_script_content), 1, f);
+ fclose(f);
+ f = fopen("test.cgi.cmd", "w");
+ cgi_script_content = "@echo off\r\n"
+ "echo Connection: close\r\n"
+ "echo Content-Type: text/plain\r\n"
+ "echo.\r\n"
+ "echo CGI test\r\n"
+ "\r\n";
+ fwrite(cgi_script_content, strlen(cgi_script_content), 1, f);
+ fclose(f);
+#else
+ f = fopen("test.cgi", "w");
+ cgi_script_content = "#!/bin/sh\n\n"
+ "printf \"Connection: close\\r\\n\"\n"
+ "printf \"Content-Type: text/plain\\r\\n\"\n"
+ "printf \"\\r\\n\"\n"
+ "printf \"CGI test\\r\\n\"\n"
+ "\n";
+ (void)fwrite(cgi_script_content, strlen(cgi_script_content), 1, f);
+ (void)fclose(f);
+ (void)system("chmod a+x test.cgi");
+#endif
+ expected_cgi_result = "CGI test";
+
+ /* Get static data */
+ client_conn = mg_download("localhost",
+ ipv4_port,
+ 0,
+ ebuf,
+ sizeof(ebuf),
+ "%s",
+ "GET /test.txt HTTP/1.0\r\n\r\n");
+ ck_assert(client_conn != NULL);
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+
+#if defined(NO_FILES)
+ ck_assert_str_eq(ri->local_uri, "404");
+#else
+ ck_assert_str_eq(ri->local_uri, "200");
+ i = mg_read(client_conn, buf, sizeof(buf));
+ ck_assert_int_eq(i, 17);
+ if ((i >= 0) && (i < (int)sizeof(buf))) {
+ buf[i] = 0;
+ }
+ ck_assert_str_eq(buf, plain_file_content);
+#endif
+ mg_close_connection(client_conn);
+
+
+ /* Check if CGI test executable exists */
+ memset(&st, 0, sizeof(st));
+
+#if defined(_WIN32)
+ /* TODO: not yet available */
+ sprintf(ebuf, "%scgi_test.cgi", locate_test_exes());
+#else
+ sprintf(ebuf, "%scgi_test.cgi", locate_test_exes());
+
+ if (stat(ebuf, &st) != 0) {
+ fprintf(stderr, "\nFile %s not found\n", ebuf);
+ fprintf(stderr,
+ "This file needs to be compiled manually before "
+ "starting the test\n");
+ fprintf(stderr,
+ "e.g. by gcc test/cgi_test.c -o output/cgi_test.cgi\n\n");
+
+ /* Abort test with diagnostic message */
+ ck_abort_msg("Mandatory file %s must be built before starting the test",
+ ebuf);
+ }
+#endif
+
+
+/* Test with CGI test executable */
+#if defined(_WIN32)
+ sprintf(cmd_buf, "copy %s\\cgi_test.cgi cgi_test.exe", locate_test_exes());
+#else
+ sprintf(cmd_buf, "cp %s/cgi_test.cgi cgi_test.cgi", locate_test_exes());
+#endif
+ (void)system(cmd_buf);
+
+#if !defined(NO_CGI) && !defined(NO_FILES) && !defined(_WIN32)
+ /* TODO: add test for windows, check with POST */
+ client_conn = mg_download(
+ "localhost",
+ ipv4_port,
+ 0,
+ ebuf,
+ sizeof(ebuf),
+ "%s",
+ "POST /cgi_test.cgi/x/y.z HTTP/1.0\r\nContent-Length: 3\r\n\r\nABC");
+ ck_assert(client_conn != NULL);
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "200");
+ mg_close_connection(client_conn);
+#endif
+
+ /* Get zipped static data - will not work if Accept-Encoding is not set */
+ client_conn = mg_download("localhost",
+ ipv4_port,
+ 0,
+ ebuf,
+ sizeof(ebuf),
+ "%s",
+ "GET /test_gz.txt HTTP/1.0\r\n\r\n");
+ ck_assert(client_conn != NULL);
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "404");
+ mg_close_connection(client_conn);
+
+ /* Get zipped static data - with Accept-Encoding */
+ client_conn = mg_download(
+ "localhost",
+ ipv4_port,
+ 0,
+ ebuf,
+ sizeof(ebuf),
+ "%s",
+ "GET /test_gz.txt HTTP/1.0\r\nAccept-Encoding: gzip\r\n\r\n");
+ ck_assert(client_conn != NULL);
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+
+#if defined(NO_FILES)
+ ck_assert_str_eq(ri->local_uri, "404");
+#else
+ ck_assert_str_eq(ri->local_uri, "200");
+ i = mg_read(client_conn, buf, sizeof(buf));
+ ck_assert_int_eq(i, 52);
+ if ((i >= 0) && (i < (int)sizeof(buf))) {
+ buf[i] = 0;
+ }
+ ck_assert_int_eq(ri->content_length, 52);
+ ck_assert_str_eq(buf, encoded_file_content);
+#endif
+ mg_close_connection(client_conn);
+
+/* Get CGI generated data */
+#if !defined(NO_CGI)
+ client_conn = mg_download("localhost",
+ ipv4_port,
+ 0,
+ ebuf,
+ sizeof(ebuf),
+ "%s",
+ "GET /test.cgi HTTP/1.0\r\n\r\n");
+ ck_assert(client_conn != NULL);
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+
+#if defined(NO_FILES)
+ ck_assert_str_eq(ri->local_uri, "404");
+
+ (void)expected_cgi_result;
+ (void)cgi_script_content;
+#else
+ i = mg_read(client_conn, buf, sizeof(buf));
+ if ((i >= 0) && (i < (int)sizeof(buf))) {
+ while ((i > 0) && ((buf[i - 1] == '\r') || (buf[i - 1] == '\n'))) {
+ i--;
+ }
+ buf[i] = 0;
+ }
+ /* ck_assert_int_eq(i, (int)strlen(expected_cgi_result)); */
+ ck_assert_str_eq(buf, expected_cgi_result);
+ ck_assert_str_eq(ri->local_uri, "200");
+ mg_close_connection(client_conn);
+#endif
+
+#else
+ (void)expected_cgi_result;
+ (void)cgi_script_content;
+#endif
+
+ /* Get directory listing */
+ client_conn = mg_download("localhost",
+ ipv4_port,
+ 0,
+ ebuf,
+ sizeof(ebuf),
+ "%s",
+ "GET / HTTP/1.0\r\n\r\n");
+ ck_assert(client_conn != NULL);
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+#if defined(NO_FILES)
+ ck_assert_str_eq(ri->local_uri, "404");
+#else
+ ck_assert_str_eq(ri->local_uri, "200");
+ i = mg_read(client_conn, buf, sizeof(buf));
+ ck_assert(i > 6);
+ buf[6] = 0;
+ ck_assert_str_eq(buf, "");
+#endif
+ mg_close_connection(client_conn);
+
+ /* POST to static file (will not work) */
+ client_conn = mg_download("localhost",
+ ipv4_port,
+ 0,
+ ebuf,
+ sizeof(ebuf),
+ "%s",
+ "POST /test.txt HTTP/1.0\r\n\r\n");
+ ck_assert(client_conn != NULL);
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+#if defined(NO_FILES)
+ ck_assert_str_eq(ri->local_uri, "404");
+#else
+ ck_assert_str_eq(ri->local_uri, "405");
+ i = mg_read(client_conn, buf, sizeof(buf));
+ ck_assert(i >= 29);
+ buf[29] = 0;
+ ck_assert_str_eq(buf, "Error 405: Method Not Allowed");
+#endif
+ mg_close_connection(client_conn);
+
+ /* PUT to static file (will not work) */
+ client_conn = mg_download("localhost",
+ ipv4_port,
+ 0,
+ ebuf,
+ sizeof(ebuf),
+ "%s",
+ "PUT /test.txt HTTP/1.0\r\n\r\n");
+ ck_assert(client_conn != NULL);
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+#if defined(NO_FILES)
+ ck_assert_str_eq(ri->local_uri, "405"); /* method not allowed */
+#else
+ ck_assert_str_eq(ri->local_uri, "401"); /* not authorized */
+#endif
+ mg_close_connection(client_conn);
+
+
+ /* Get data from callback using mg_connect_client instead of mg_download */
+ memset(ebuf, 0, sizeof(ebuf));
+ client_conn =
+ mg_connect_client("127.0.0.1", ipv4_port, 0, ebuf, sizeof(ebuf));
+
+ ck_assert_str_eq(ebuf, "");
+ ck_assert(client_conn != NULL);
+
+ mg_printf(client_conn, "%s", request);
+
+ i = mg_get_response(client_conn, ebuf, sizeof(ebuf), 10000);
+ ck_assert_int_ge(i, 0);
+ ck_assert_str_eq(ebuf, "");
+
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "200");
+ i = mg_read(client_conn, buf, sizeof(buf));
+ ck_assert_int_eq(i, (int)strlen(expected));
+ buf[i] = 0;
+ ck_assert_str_eq(buf, expected);
+ mg_close_connection(client_conn);
+
+ /* Get data from callback using mg_connect_client and absolute URI */
+ memset(ebuf, 0, sizeof(ebuf));
+ client_conn =
+ mg_connect_client("localhost", ipv4_port, 0, ebuf, sizeof(ebuf));
+
+ ck_assert_str_eq(ebuf, "");
+ ck_assert(client_conn != NULL);
+
+ mg_printf(client_conn,
+ "GET http://test.domain:%d/U7 HTTP/1.0\r\n\r\n",
+ ipv4_port);
+
+ i = mg_get_response(client_conn, ebuf, sizeof(ebuf), 10000);
+ ck_assert_int_ge(i, 0);
+ ck_assert_str_eq(ebuf, "");
+
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "200");
+ i = mg_read(client_conn, buf, sizeof(buf));
+ ck_assert_int_eq(i, (int)strlen(expected));
+ buf[i] = 0;
+ ck_assert_str_eq(buf, expected);
+ mg_close_connection(client_conn);
+
+ /* Get data from callback using mg_connect_client and absolute URI with a
+ * sub-domain */
+ memset(ebuf, 0, sizeof(ebuf));
+ client_conn =
+ mg_connect_client("localhost", ipv4_port, 0, ebuf, sizeof(ebuf));
+
+ ck_assert_str_eq(ebuf, "");
+ ck_assert(client_conn != NULL);
+
+ mg_printf(client_conn,
+ "GET http://subdomain.test.domain:%d/U7 HTTP/1.0\r\n\r\n",
+ ipv4_port);
+
+ i = mg_get_response(client_conn, ebuf, sizeof(ebuf), 10000);
+ ck_assert_int_ge(i, 0);
+ ck_assert_str_eq(ebuf, "");
+
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "200");
+ i = mg_read(client_conn, buf, sizeof(buf));
+ ck_assert_int_eq(i, (int)strlen(expected));
+ buf[i] = 0;
+ ck_assert_str_eq(buf, expected);
+ mg_close_connection(client_conn);
+
+
+/* Websocket test */
+#ifdef USE_WEBSOCKET
+ /* Then connect a first client */
+ ws_client1_conn =
+ mg_connect_websocket_client("localhost",
+ ipv4_port,
+ 0,
+ ebuf,
+ sizeof(ebuf),
+ "/websocket",
+ NULL,
+ websocket_client_data_handler,
+ websocket_client_close_handler,
+ &ws_client1_data);
+
+ ck_assert(ws_client1_conn != NULL);
+
+ wait_not_null(
+ &(ws_client1_data.data)); /* Wait for the websocket welcome message */
+ ck_assert_int_eq(ws_client1_data.closed, 0);
+ ck_assert_int_eq(ws_client2_data.closed, 0);
+ ck_assert_int_eq(ws_client3_data.closed, 0);
+ ck_assert(ws_client2_data.data == NULL);
+ ck_assert_uint_eq(ws_client2_data.len, 0);
+ ck_assert(ws_client1_data.data != NULL);
+ ck_assert_uint_eq(ws_client1_data.len, websocket_welcome_msg_len);
+ ck_assert(!memcmp(ws_client1_data.data,
+ websocket_welcome_msg,
+ websocket_welcome_msg_len));
+ free(ws_client1_data.data);
+ ws_client1_data.data = NULL;
+ ws_client1_data.len = 0;
+
+ mg_websocket_client_write(ws_client1_conn,
+ WEBSOCKET_OPCODE_TEXT,
+ "data1",
+ 5);
+
+ wait_not_null(
+ &(ws_client1_data
+ .data)); /* Wait for the websocket acknowledge message */
+ ck_assert_int_eq(ws_client1_data.closed, 0);
+ ck_assert_int_eq(ws_client2_data.closed, 0);
+ ck_assert(ws_client2_data.data == NULL);
+ ck_assert_uint_eq(ws_client2_data.len, 0);
+ ck_assert(ws_client1_data.data != NULL);
+ ck_assert_uint_eq(ws_client1_data.len, 3);
+ ck_assert(!memcmp(ws_client1_data.data, "ok1", 3));
+ free(ws_client1_data.data);
+ ws_client1_data.data = NULL;
+ ws_client1_data.len = 0;
+
+/* Now connect a second client */
+#ifdef USE_IPV6
+ ws_client2_conn =
+ mg_connect_websocket_client("[::1]",
+ ipv6_port,
+ 0,
+ ebuf,
+ sizeof(ebuf),
+ "/websocket",
+ NULL,
+ websocket_client_data_handler,
+ websocket_client_close_handler,
+ &ws_client2_data);
+#else
+ ws_client2_conn =
+ mg_connect_websocket_client("127.0.0.1",
+ ipv4_port,
+ 0,
+ ebuf,
+ sizeof(ebuf),
+ "/websocket",
+ NULL,
+ websocket_client_data_handler,
+ websocket_client_close_handler,
+ &ws_client2_data);
+#endif
+ ck_assert(ws_client2_conn != NULL);
+
+ wait_not_null(
+ &(ws_client2_data.data)); /* Wait for the websocket welcome message */
+ ck_assert(ws_client1_data.closed == 0);
+ ck_assert(ws_client2_data.closed == 0);
+ ck_assert(ws_client1_data.data == NULL);
+ ck_assert(ws_client1_data.len == 0);
+ ck_assert(ws_client2_data.data != NULL);
+ ck_assert(ws_client2_data.len == websocket_welcome_msg_len);
+ ck_assert(!memcmp(ws_client2_data.data,
+ websocket_welcome_msg,
+ websocket_welcome_msg_len));
+ free(ws_client2_data.data);
+ ws_client2_data.data = NULL;
+ ws_client2_data.len = 0;
+
+ mg_websocket_client_write(ws_client1_conn,
+ WEBSOCKET_OPCODE_TEXT,
+ "data2",
+ 5);
+
+ wait_not_null(
+ &(ws_client1_data
+ .data)); /* Wait for the websocket acknowledge message */
+
+ ck_assert(ws_client1_data.closed == 0);
+ ck_assert(ws_client2_data.closed == 0);
+ ck_assert(ws_client2_data.data == NULL);
+ ck_assert(ws_client2_data.len == 0);
+ ck_assert(ws_client1_data.data != NULL);
+ ck_assert(ws_client1_data.len == 4);
+ ck_assert(!memcmp(ws_client1_data.data, "ok 2", 4));
+ free(ws_client1_data.data);
+ ws_client1_data.data = NULL;
+ ws_client1_data.len = 0;
+
+ mg_websocket_client_write(ws_client1_conn, WEBSOCKET_OPCODE_TEXT, "bye", 3);
+
+ wait_not_null(
+ &(ws_client1_data.data)); /* Wait for the websocket goodbye message */
+
+ ck_assert(ws_client1_data.closed == 0);
+ ck_assert(ws_client2_data.closed == 0);
+ ck_assert(ws_client2_data.data == NULL);
+ ck_assert(ws_client2_data.len == 0);
+ ck_assert(ws_client1_data.data != NULL);
+ ck_assert(ws_client1_data.len == websocket_goodbye_msg_len);
+ ck_assert(!memcmp(ws_client1_data.data,
+ websocket_goodbye_msg,
+ websocket_goodbye_msg_len));
+ free(ws_client1_data.data);
+ ws_client1_data.data = NULL;
+ ws_client1_data.len = 0;
+
+ ck_assert(ws_client1_data.closed == 0); /* Not closed */
+
+ mg_close_connection(ws_client1_conn);
+
+ test_sleep(3); /* Won't get any message */
+
+ ck_assert(ws_client1_data.closed == 1); /* Closed */
+
+ ck_assert(ws_client2_data.closed == 0);
+ ck_assert(ws_client1_data.data == NULL);
+ ck_assert(ws_client1_data.len == 0);
+ ck_assert(ws_client2_data.data == NULL);
+ ck_assert(ws_client2_data.len == 0);
+
+ mg_websocket_client_write(ws_client2_conn, WEBSOCKET_OPCODE_TEXT, "bye", 3);
+
+ wait_not_null(
+ &(ws_client2_data.data)); /* Wait for the websocket goodbye message */
+
+ ck_assert(ws_client1_data.closed == 1);
+ ck_assert(ws_client2_data.closed == 0);
+ ck_assert(ws_client1_data.data == NULL);
+ ck_assert(ws_client1_data.len == 0);
+ ck_assert(ws_client2_data.data != NULL);
+ ck_assert(ws_client2_data.len == websocket_goodbye_msg_len);
+ ck_assert(!memcmp(ws_client2_data.data,
+ websocket_goodbye_msg,
+ websocket_goodbye_msg_len));
+ free(ws_client2_data.data);
+ ws_client2_data.data = NULL;
+ ws_client2_data.len = 0;
+
+ mg_close_connection(ws_client2_conn);
+
+ test_sleep(3); /* Won't get any message */
+
+ ck_assert(ws_client1_data.closed == 1);
+ ck_assert(ws_client2_data.closed == 1);
+ ck_assert(ws_client1_data.data == NULL);
+ ck_assert(ws_client1_data.len == 0);
+ ck_assert(ws_client2_data.data == NULL);
+ ck_assert(ws_client2_data.len == 0);
+
+ /* Connect client 3 */
+ ws_client3_conn =
+ mg_connect_websocket_client("localhost",
+#if defined(NO_SSL)
+ ipv4_port,
+ 0,
+#else
+ ipv4s_port,
+ 1,
+#endif
+ ebuf,
+ sizeof(ebuf),
+ "/websocket",
+ NULL,
+ websocket_client_data_handler,
+ websocket_client_close_handler,
+ &ws_client3_data);
+
+ ck_assert(ws_client3_conn != NULL);
+
+ wait_not_null(
+ &(ws_client3_data.data)); /* Wait for the websocket welcome message */
+ ck_assert(ws_client1_data.closed == 1);
+ ck_assert(ws_client2_data.closed == 1);
+ ck_assert(ws_client3_data.closed == 0);
+ ck_assert(ws_client1_data.data == NULL);
+ ck_assert(ws_client1_data.len == 0);
+ ck_assert(ws_client2_data.data == NULL);
+ ck_assert(ws_client2_data.len == 0);
+ ck_assert(ws_client3_data.data != NULL);
+ ck_assert(ws_client3_data.len == websocket_welcome_msg_len);
+ ck_assert(!memcmp(ws_client3_data.data,
+ websocket_welcome_msg,
+ websocket_welcome_msg_len));
+ free(ws_client3_data.data);
+ ws_client3_data.data = NULL;
+ ws_client3_data.len = 0;
+
+ /* Write long data (16 bit size header) */
+ mg_websocket_client_write(ws_client3_conn,
+ WEBSOCKET_OPCODE_BINARY,
+ long_ws_buf,
+ long_ws_buf_len_16);
+
+ /* Wait for the response */
+ wait_not_null(&(ws_client3_data.data));
+
+ ck_assert_int_eq((int)ws_client3_data.len, (int)long_ws_buf_len_16);
+ ck_assert(!memcmp(ws_client3_data.data, long_ws_buf, long_ws_buf_len_16));
+ free(ws_client3_data.data);
+ ws_client3_data.data = NULL;
+ ws_client3_data.len = 0;
+
+ /* Write long data (64 bit size header) */
+ mg_websocket_client_write(ws_client3_conn,
+ WEBSOCKET_OPCODE_BINARY,
+ long_ws_buf,
+ long_ws_buf_len_64);
+
+ /* Wait for the response */
+ wait_not_null(&(ws_client3_data.data));
+
+ ck_assert_int_eq((int)ws_client3_data.len, (int)long_ws_buf_len_64);
+ ck_assert(!memcmp(ws_client3_data.data, long_ws_buf, long_ws_buf_len_64));
+ free(ws_client3_data.data);
+ ws_client3_data.data = NULL;
+ ws_client3_data.len = 0;
+
+ /* Disconnect client 3 */
+ ck_assert(ws_client3_data.closed == 0);
+ mg_close_connection(ws_client3_conn);
+ ck_assert(ws_client3_data.closed == 1);
+
+ /* Connect client 4 */
+ ws_client4_conn =
+ mg_connect_websocket_client("localhost",
+#if defined(NO_SSL)
+ ipv4_port,
+ 0,
+#else
+ ipv4s_port,
+ 1,
+#endif
+ ebuf,
+ sizeof(ebuf),
+ "/websocket",
+ NULL,
+ websocket_client_data_handler,
+ websocket_client_close_handler,
+ &ws_client4_data);
+
+ ck_assert(ws_client4_conn != NULL);
+
+ wait_not_null(
+ &(ws_client4_data.data)); /* Wait for the websocket welcome message */
+ ck_assert(ws_client1_data.closed == 1);
+ ck_assert(ws_client2_data.closed == 1);
+ ck_assert(ws_client3_data.closed == 1);
+ ck_assert(ws_client4_data.closed == 0);
+ ck_assert(ws_client4_data.data != NULL);
+ ck_assert(ws_client4_data.len == websocket_welcome_msg_len);
+ ck_assert(!memcmp(ws_client4_data.data,
+ websocket_welcome_msg,
+ websocket_welcome_msg_len));
+ free(ws_client4_data.data);
+ ws_client4_data.data = NULL;
+ ws_client4_data.len = 0;
+
+/* stop the server without closing this connection */
+
+#endif
+
+ /* Close the server */
+ g_ctx = NULL;
+ test_mg_stop(ctx);
+ mark_point();
+
+#ifdef USE_WEBSOCKET
+ for (i = 0; i < 100; i++) {
+ test_sleep(1);
+ if (ws_client3_data.closed != 0) {
+ mark_point();
+ break;
+ }
+ }
+
+ ck_assert_int_eq(ws_client4_data.closed, 1);
+
+ /* Free data in ws_client4_conn */
+ mg_close_connection(ws_client4_conn);
+
+#endif
+ mark_point();
+}
+END_TEST
+
+
+static int g_field_found_return = -999;
+
+static int
+field_found(const char *key,
+ const char *filename,
+ char *path,
+ size_t pathlen,
+ void *user_data)
+{
+ ck_assert_ptr_ne(key, NULL);
+ ck_assert_ptr_ne(filename, NULL);
+ ck_assert_ptr_ne(path, NULL);
+ ck_assert_uint_gt(pathlen, 128);
+ ck_assert_ptr_eq(user_data, (void *)&g_field_found_return);
+
+ ck_assert((g_field_found_return == FORM_FIELD_STORAGE_GET)
+ || (g_field_found_return == FORM_FIELD_STORAGE_STORE)
+ || (g_field_found_return == FORM_FIELD_STORAGE_SKIP)
+ || (g_field_found_return == FORM_FIELD_STORAGE_ABORT));
+
+ ck_assert_str_ne(key, "dontread");
+
+ if (!strcmp(key, "break_field_handler")) {
+ return FORM_FIELD_STORAGE_ABORT;
+ }
+ if (!strcmp(key, "continue_field_handler")) {
+ return FORM_FIELD_STORAGE_SKIP;
+ }
+
+ if (g_field_found_return == FORM_FIELD_STORAGE_STORE) {
+ strncpy(path, key, pathlen - 8);
+ strcat(path, ".txt");
+ }
+
+ mark_point();
+
+ return g_field_found_return;
+}
+
+
+static int g_field_step;
+
+static int
+field_get(const char *key,
+ const char *value_untruncated,
+ size_t valuelen,
+ void *user_data)
+{
+ /* Copy the untruncated value, so string compare functions can be used. */
+ /* The check unit test library does not have build in memcmp functions. */
+ char *value = (char *)malloc(valuelen + 1);
+ ck_assert(value != NULL);
+ memcpy(value, value_untruncated, valuelen);
+ value[valuelen] = 0;
+
+ ck_assert_ptr_eq(user_data, (void *)&g_field_found_return);
+ ck_assert_int_ge(g_field_step, 0);
+
+ ++g_field_step;
+ switch (g_field_step) {
+ case 1:
+ ck_assert_str_eq(key, "textin");
+ ck_assert_uint_eq(valuelen, 4);
+ ck_assert_str_eq(value, "text");
+ break;
+ case 2:
+ ck_assert_str_eq(key, "passwordin");
+ ck_assert_uint_eq(valuelen, 0);
+ ck_assert_str_eq(value, "");
+ break;
+ case 3:
+ ck_assert_str_eq(key, "radio1");
+ ck_assert_uint_eq(valuelen, 4);
+ ck_assert_str_eq(value, "val1");
+ break;
+ case 4:
+ ck_assert_str_eq(key, "radio2");
+ ck_assert_uint_eq(valuelen, 4);
+ ck_assert_str_eq(value, "val1");
+ break;
+ case 5:
+ ck_assert_str_eq(key, "check1");
+ ck_assert_uint_eq(valuelen, 4);
+ ck_assert_str_eq(value, "val1");
+ break;
+ case 6:
+ ck_assert_str_eq(key, "numberin");
+ ck_assert_uint_eq(valuelen, 1);
+ ck_assert_str_eq(value, "1");
+ break;
+ case 7:
+ ck_assert_str_eq(key, "datein");
+ ck_assert_uint_eq(valuelen, 8);
+ ck_assert_str_eq(value, "1.1.2016");
+ break;
+ case 8:
+ ck_assert_str_eq(key, "colorin");
+ ck_assert_uint_eq(valuelen, 7);
+ ck_assert_str_eq(value, "#80ff00");
+ break;
+ case 9:
+ ck_assert_str_eq(key, "rangein");
+ ck_assert_uint_eq(valuelen, 1);
+ ck_assert_str_eq(value, "3");
+ break;
+ case 10:
+ ck_assert_str_eq(key, "monthin");
+ ck_assert_uint_eq(valuelen, 0);
+ ck_assert_str_eq(value, "");
+ break;
+ case 11:
+ ck_assert_str_eq(key, "weekin");
+ ck_assert_uint_eq(valuelen, 0);
+ ck_assert_str_eq(value, "");
+ break;
+ case 12:
+ ck_assert_str_eq(key, "timein");
+ ck_assert_uint_eq(valuelen, 0);
+ ck_assert_str_eq(value, "");
+ break;
+ case 13:
+ ck_assert_str_eq(key, "datetimen");
+ ck_assert_uint_eq(valuelen, 0);
+ ck_assert_str_eq(value, "");
+ break;
+ case 14:
+ ck_assert_str_eq(key, "datetimelocalin");
+ ck_assert_uint_eq(valuelen, 0);
+ ck_assert_str_eq(value, "");
+ break;
+ case 15:
+ ck_assert_str_eq(key, "emailin");
+ ck_assert_uint_eq(valuelen, 0);
+ ck_assert_str_eq(value, "");
+ break;
+ case 16:
+ ck_assert_str_eq(key, "searchin");
+ ck_assert_uint_eq(valuelen, 0);
+ ck_assert_str_eq(value, "");
+ break;
+ case 17:
+ ck_assert_str_eq(key, "telin");
+ ck_assert_uint_eq(valuelen, 0);
+ ck_assert_str_eq(value, "");
+ break;
+ case 18:
+ ck_assert_str_eq(key, "urlin");
+ ck_assert_uint_eq(valuelen, 0);
+ ck_assert_str_eq(value, "");
+ break;
+ case 19:
+ ck_assert_str_eq(key, "filein");
+ ck_assert_uint_eq(valuelen, 0);
+ ck_assert_str_eq(value, "");
+ break;
+ case 20:
+ ck_assert_str_eq(key, "filesin");
+ ck_assert_uint_eq(valuelen, 0);
+ ck_assert_str_eq(value, "");
+ break;
+ case 21:
+ ck_assert_str_eq(key, "selectin");
+ ck_assert_uint_eq(valuelen, 4);
+ ck_assert_str_eq(value, "opt1");
+ break;
+ case 22:
+ ck_assert_str_eq(key, "message");
+ ck_assert_uint_eq(valuelen, 23);
+ ck_assert_str_eq(value, "Text area default text.");
+ break;
+ default:
+ ck_abort_msg("field_get called with g_field_step == %i",
+ (int)g_field_step);
+ }
+
+ free(value);
+ mark_point();
+
+ return 0;
+}
+
+
+static const char *myfile_content = "Content of myfile.txt\r\n";
+static const int myfile_content_rep = 500;
+
+
+static int
+field_store(const char *path, long long file_size, void *user_data)
+{
+ FILE *f;
+ ck_assert_ptr_eq(user_data, (void *)&g_field_found_return);
+ ck_assert_int_ge(g_field_step, 100);
+
+ ++g_field_step;
+ switch (g_field_step) {
+ case 101:
+ ck_assert_str_eq(path, "storeme.txt");
+ ck_assert_int_eq(file_size, 9);
+ f = fopen(path, "r");
+ ck_assert_ptr_ne(f, NULL);
+ if (f) {
+ char buf[32] = {0};
+ int i = (int)fread(buf, 1, 31, f);
+ ck_assert_int_eq(i, 9);
+ fclose(f);
+ ck_assert_str_eq(buf, "storetest");
+ }
+ break;
+ case 102:
+ ck_assert_str_eq(path, "file2store.txt");
+ ck_assert_uint_eq(23, strlen(myfile_content));
+ ck_assert_int_eq(file_size, 23 * myfile_content_rep);
+#ifdef _WIN32
+ f = fopen(path, "rb");
+#else
+ f = fopen(path, "r");
+#endif
+ ck_assert_ptr_ne(f, NULL);
+ if (f) {
+ char buf[32] = {0};
+ int r, i;
+ for (r = 0; r < myfile_content_rep; r++) {
+ i = (int)fread(buf, 1, 23, f);
+ ck_assert_int_eq(i, 23);
+ ck_assert_str_eq(buf, myfile_content);
+ }
+ i = (int)fread(buf, 1, 23, f);
+ ck_assert_int_eq(i, 0);
+ fclose(f);
+ }
+ break;
+ default:
+ ck_abort_msg("field_get called with g_field_step == %i",
+ (int)g_field_step);
+ }
+ mark_point();
+
+ return 0;
+}
+
+
+static int
+FormGet(struct mg_connection *conn, void *cbdata)
+{
+ const struct mg_request_info *req_info = mg_get_request_info(conn);
+ int ret;
+ struct mg_form_data_handler fdh = {field_found, field_get, NULL, NULL};
+
+ (void)cbdata;
+
+ ck_assert(req_info != NULL);
+
+ mg_printf(conn, "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n");
+ fdh.user_data = (void *)&g_field_found_return;
+
+ /* Call the form handler */
+ g_field_step = 0;
+ g_field_found_return = FORM_FIELD_STORAGE_GET;
+ ret = mg_handle_form_request(conn, &fdh);
+ g_field_found_return = -888;
+ ck_assert_int_eq(ret, 22);
+ ck_assert_int_eq(g_field_step, 22);
+ mg_printf(conn, "%i\r\n", ret);
+ g_field_step = 1000;
+
+ mark_point();
+
+ return 1;
+}
+
+
+static int
+FormStore(struct mg_connection *conn,
+ void *cbdata,
+ int ret_expected,
+ int field_step_expected)
+{
+ const struct mg_request_info *req_info = mg_get_request_info(conn);
+ int ret;
+ struct mg_form_data_handler fdh = {field_found,
+ field_get,
+ field_store,
+ NULL};
+
+ (void)cbdata;
+
+ ck_assert(req_info != NULL);
+
+ mg_printf(conn, "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n");
+ fdh.user_data = (void *)&g_field_found_return;
+
+ /* Call the form handler */
+ g_field_step = 100;
+ g_field_found_return = FORM_FIELD_STORAGE_STORE;
+ ret = mg_handle_form_request(conn, &fdh);
+ ck_assert_int_eq(ret, ret_expected);
+ ck_assert_int_eq(g_field_step, field_step_expected);
+ mg_printf(conn, "%i\r\n", ret);
+ g_field_step = 1000;
+
+ mark_point();
+
+ return 1;
+}
+
+
+static int
+FormStore1(struct mg_connection *conn, void *cbdata)
+{
+ mark_point();
+ return FormStore(conn, cbdata, 3, 101);
+}
+
+
+static int
+FormStore2(struct mg_connection *conn, void *cbdata)
+{
+ mark_point();
+ return FormStore(conn, cbdata, 4, 102);
+}
+
+
+static void
+send_chunk_stringl(struct mg_connection *conn,
+ const char *chunk,
+ unsigned int chunk_len)
+{
+ char lenbuf[16];
+ size_t lenbuf_len;
+ int ret;
+
+ mark_point();
+
+ /* First store the length information in a text buffer. */
+ sprintf(lenbuf, "%x\r\n", chunk_len);
+ lenbuf_len = strlen(lenbuf);
+
+ /* Then send length information, chunk and terminating \r\n. */
+ ret = mg_write(conn, lenbuf, lenbuf_len);
+ ck_assert_int_eq(ret, (int)lenbuf_len);
+
+ ret = mg_write(conn, chunk, chunk_len);
+ ck_assert_int_eq(ret, (int)chunk_len);
+
+ ret = mg_write(conn, "\r\n", 2);
+ ck_assert_int_eq(ret, 2);
+}
+
+
+static void
+send_chunk_string(struct mg_connection *conn, const char *chunk)
+{
+ mark_point();
+ send_chunk_stringl(conn, chunk, (unsigned int)strlen(chunk));
+ mark_point();
+}
+
+
+START_TEST(test_handle_form)
+{
+ struct mg_context *ctx;
+ struct mg_connection *client_conn;
+ const struct mg_request_info *ri;
+ const char *OPTIONS[8];
+ const char *opt;
+ int opt_idx = 0;
+ char ebuf[100];
+ const char *multipart_body;
+ const char *boundary;
+ size_t body_len, body_sent, chunk_len;
+ int sleep_cnt;
+
+ mark_point();
+
+ memset((void *)OPTIONS, 0, sizeof(OPTIONS));
+ OPTIONS[opt_idx++] = "listening_ports";
+ OPTIONS[opt_idx++] = "8884";
+ ck_assert_int_le(opt_idx, (int)(sizeof(OPTIONS) / sizeof(OPTIONS[0])));
+ ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 1] == NULL);
+ ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 2] == NULL);
+
+ ctx = test_mg_start(NULL, &g_ctx, OPTIONS);
+
+ ck_assert(ctx != NULL);
+ g_ctx = ctx;
+
+ opt = mg_get_option(ctx, "listening_ports");
+ ck_assert_str_eq(opt, "8884");
+
+ mg_set_request_handler(ctx, "/handle_form", FormGet, NULL);
+ mg_set_request_handler(ctx, "/handle_form_store", FormStore1, NULL);
+ mg_set_request_handler(ctx, "/handle_form_store2", FormStore2, NULL);
+
+ test_sleep(1);
+
+ /* Handle form: "GET" */
+ client_conn = mg_download("localhost",
+ 8884,
+ 0,
+ ebuf,
+ sizeof(ebuf),
+ "%s",
+ "GET /handle_form"
+ "?textin=text&passwordin=&radio1=val1"
+ "&radio2=val1&check1=val1&numberin=1"
+ "&datein=1.1.2016&colorin=%2380ff00"
+ "&rangein=3&monthin=&weekin=&timein="
+ "&datetimen=&datetimelocalin=&emailin="
+ "&searchin=&telin=&urlin=&filein="
+ "&filesin=&selectin=opt1"
+ "&message=Text+area+default+text. "
+ "HTTP/1.0\r\n"
+ "Host: localhost:8884\r\n"
+ "Connection: close\r\n\r\n");
+ ck_assert(client_conn != NULL);
+ for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) {
+ test_sleep(1);
+ if (g_field_step == 1000) {
+ break;
+ }
+ }
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "200");
+ mg_close_connection(client_conn);
+
+ /* Handle form: "POST x-www-form-urlencoded" */
+ client_conn =
+ mg_download("localhost",
+ 8884,
+ 0,
+ ebuf,
+ sizeof(ebuf),
+ "%s",
+ "POST /handle_form HTTP/1.1\r\n"
+ "Host: localhost:8884\r\n"
+ "Connection: close\r\n"
+ "Content-Type: application/x-www-form-urlencoded\r\n"
+ "Content-Length: 263\r\n"
+ "\r\n"
+ "textin=text&passwordin=&radio1=val1&radio2=val1"
+ "&check1=val1&numberin=1&datein=1.1.2016"
+ "&colorin=%2380ff00&rangein=3&monthin=&weekin="
+ "&timein=&datetimen=&datetimelocalin=&emailin="
+ "&searchin=&telin=&urlin=&filein=&filesin="
+ "&selectin=opt1&message=Text+area+default+text.");
+ ck_assert(client_conn != NULL);
+ for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) {
+ test_sleep(1);
+ if (g_field_step == 1000) {
+ break;
+ }
+ }
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "200");
+ mg_close_connection(client_conn);
+
+ /* Handle form: "POST multipart/form-data" */
+ multipart_body =
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=\"textin\"\r\n"
+ "\r\n"
+ "text\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=\"passwordin\"\r\n"
+ "\r\n"
+ "\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=\"radio1\"\r\n"
+ "\r\n"
+ "val1\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=radio2\r\n"
+ "\r\n"
+ "val1\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=\"check1\"\r\n"
+ "\r\n"
+ "val1\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=\"numberin\"\r\n"
+ "\r\n"
+ "1\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=\"datein\"\r\n"
+ "\r\n"
+ "1.1.2016\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=\"colorin\"\r\n"
+ "\r\n"
+ "#80ff00\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=\"rangein\"\r\n"
+ "\r\n"
+ "3\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=\"monthin\"\r\n"
+ "\r\n"
+ "\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=\"weekin\"\r\n"
+ "\r\n"
+ "\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=\"timein\"\r\n"
+ "\r\n"
+ "\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=\"datetimen\"\r\n"
+ "\r\n"
+ "\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=\"datetimelocalin\"\r\n"
+ "\r\n"
+ "\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=\"emailin\"\r\n"
+ "\r\n"
+ "\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=\"searchin\"\r\n"
+ "\r\n"
+ "\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=\"telin\"\r\n"
+ "\r\n"
+ "\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=\"urlin\"\r\n"
+ "\r\n"
+ "\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=\"filein\"; filename=\"\"\r\n"
+ "Content-Type: application/octet-stream\r\n"
+ "\r\n"
+ "\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=filesin; filename=\r\n"
+ "Content-Type: application/octet-stream\r\n"
+ "\r\n"
+ "\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=\"selectin\"\r\n"
+ "\r\n"
+ "opt1\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Disposition: form-data; name=\"message\"\r\n"
+ "\r\n"
+ "Text area default text.\r\n"
+ "--multipart-form-data-boundary--see-RFC-2388--\r\n";
+ body_len = strlen(multipart_body);
+ ck_assert_uint_eq(body_len, 2368); /* not required */
+
+ client_conn =
+ mg_download("localhost",
+ 8884,
+ 0,
+ ebuf,
+ sizeof(ebuf),
+ "POST /handle_form HTTP/1.1\r\n"
+ "Host: localhost:8884\r\n"
+ "Connection: close\r\n"
+ "Content-Type: multipart/form-data; "
+ "boundary=multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Content-Length: %u\r\n"
+ "\r\n%s",
+ (unsigned int)body_len,
+ multipart_body);
+
+ ck_assert(client_conn != NULL);
+ for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) {
+ test_sleep(1);
+ if (g_field_step == 1000) {
+ break;
+ }
+ }
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "200");
+ mg_close_connection(client_conn);
+
+
+ /* Handle form: "POST multipart/form-data" with chunked transfer encoding */
+ client_conn =
+ mg_download("localhost",
+ 8884,
+ 0,
+ ebuf,
+ sizeof(ebuf),
+ "%s",
+ "POST /handle_form HTTP/1.1\r\n"
+ "Host: localhost:8884\r\n"
+ "Connection: close\r\n"
+ "Content-Type: multipart/form-data; "
+ "boundary=multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Transfer-Encoding: chunked\r\n"
+ "\r\n");
+
+ ck_assert(client_conn != NULL);
+
+ body_len = strlen(multipart_body);
+ chunk_len = 1;
+ body_sent = 0;
+ while (body_len > body_sent) {
+ if (chunk_len > (body_len - body_sent)) {
+ chunk_len = body_len - body_sent;
+ }
+ ck_assert_int_gt((int)chunk_len, 0);
+ mg_printf(client_conn, "%x\r\n", (unsigned int)chunk_len);
+ mg_write(client_conn, multipart_body + body_sent, chunk_len);
+ mg_printf(client_conn, "\r\n");
+ body_sent += chunk_len;
+ chunk_len = (chunk_len % 40) + 1;
+ }
+ mg_printf(client_conn, "0\r\n");
+
+ for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) {
+ test_sleep(1);
+ if (g_field_step == 1000) {
+ break;
+ }
+ }
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "200");
+ mg_close_connection(client_conn);
+
+ /* Handle form: "POST multipart/form-data" with chunked transfer
+ * encoding, using a quoted boundary string */
+ client_conn = mg_download(
+ "localhost",
+ 8884,
+ 0,
+ ebuf,
+ sizeof(ebuf),
+ "%s",
+ "POST /handle_form HTTP/1.1\r\n"
+ "Host: localhost:8884\r\n"
+ "Connection: close\r\n"
+ "Content-Type: multipart/form-data; "
+ "boundary=\"multipart-form-data-boundary--see-RFC-2388\"\r\n"
+ "Transfer-Encoding: chunked\r\n"
+ "\r\n");
+
+ ck_assert(client_conn != NULL);
+
+ body_len = strlen(multipart_body);
+ chunk_len = 1;
+ body_sent = 0;
+ while (body_len > body_sent) {
+ if (chunk_len > (body_len - body_sent)) {
+ chunk_len = body_len - body_sent;
+ }
+ ck_assert_int_gt((int)chunk_len, 0);
+ mg_printf(client_conn, "%x\r\n", (unsigned int)chunk_len);
+ mg_write(client_conn, multipart_body + body_sent, chunk_len);
+ mg_printf(client_conn, "\r\n");
+ body_sent += chunk_len;
+ chunk_len = (chunk_len % 40) + 1;
+ }
+ mg_printf(client_conn, "0\r\n");
+
+ for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) {
+ test_sleep(1);
+ if (g_field_step == 1000) {
+ break;
+ }
+ }
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "200");
+ mg_close_connection(client_conn);
+
+
+ /* Now test form_store */
+
+ /* First test with GET */
+ client_conn = mg_download("localhost",
+ 8884,
+ 0,
+ ebuf,
+ sizeof(ebuf),
+ "%s",
+ "GET /handle_form_store"
+ "?storeme=storetest"
+ "&continue_field_handler=ignore"
+ "&break_field_handler=abort"
+ "&dontread=xyz "
+ "HTTP/1.0\r\n"
+ "Host: localhost:8884\r\n"
+ "Connection: close\r\n\r\n");
+
+ ck_assert(client_conn != NULL);
+
+ for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) {
+ test_sleep(1);
+ if (g_field_step == 1000) {
+ break;
+ }
+ }
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "200");
+ mg_close_connection(client_conn);
+
+
+ /* Handle form: "POST x-www-form-urlencoded", chunked, store */
+ client_conn =
+ mg_download("localhost",
+ 8884,
+ 0,
+ ebuf,
+ sizeof(ebuf),
+ "%s",
+ "POST /handle_form_store HTTP/1.0\r\n"
+ "Host: localhost:8884\r\n"
+ "Connection: close\r\n"
+ "Content-Type: application/x-www-form-urlencoded\r\n"
+ "Transfer-Encoding: chunked\r\n"
+ "\r\n");
+ ck_assert(client_conn != NULL);
+
+ send_chunk_string(client_conn, "storeme=store");
+ send_chunk_string(client_conn, "test&");
+ send_chunk_string(client_conn, "continue_field_handler=ignore");
+ send_chunk_string(client_conn, "&br");
+ test_sleep(1);
+ send_chunk_string(client_conn, "eak_field_handler=abort&");
+ send_chunk_string(client_conn, "dontread=xyz");
+ mg_printf(client_conn, "0\r\n");
+
+ for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) {
+ test_sleep(1);
+ if (g_field_step == 1000) {
+ break;
+ }
+ }
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "200");
+ mg_close_connection(client_conn);
+
+ /* Handle form: "POST multipart/form-data", chunked, store */
+ client_conn =
+ mg_download("localhost",
+ 8884,
+ 0,
+ ebuf,
+ sizeof(ebuf),
+ "%s",
+ "POST /handle_form_store HTTP/1.0\r\n"
+ "Host: localhost:8884\r\n"
+ "Connection: close\r\n"
+ "Content-Type: multipart/form-data; "
+ "boundary=multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Transfer-Encoding: chunked\r\n"
+ "\r\n");
+ ck_assert(client_conn != NULL);
+
+ send_chunk_string(client_conn, "--multipart-form-data-boundary");
+ send_chunk_string(client_conn, "--see-RFC-2388\r\n");
+ send_chunk_string(client_conn, "Content-Disposition: form-data; ");
+ send_chunk_string(client_conn, "name=\"storeme\"\r\n");
+ send_chunk_string(client_conn, "\r\n");
+ send_chunk_string(client_conn, "storetest\r\n");
+
+ send_chunk_string(client_conn, "--multipart-form-data-boundary-");
+ send_chunk_string(client_conn, "-see-RFC-2388\r\n");
+ send_chunk_string(client_conn, "Content-Disposition: form-data; ");
+ send_chunk_string(client_conn, "name=\"continue_field_handler\"\r\n");
+ send_chunk_string(client_conn, "\r\n");
+ send_chunk_string(client_conn, "ignore\r\n");
+
+ send_chunk_string(client_conn, "--multipart-form-data-boundary-");
+ send_chunk_string(client_conn, "-see-RFC-2388\r\n");
+ send_chunk_string(client_conn, "Content-Disposition: form-data; ");
+ send_chunk_string(client_conn, "name=\"break_field_handler\"\r\n");
+ send_chunk_string(client_conn, "\r\n");
+ send_chunk_string(client_conn, "abort\r\n");
+
+ send_chunk_string(client_conn, "--multipart-form-data-boundary-");
+ send_chunk_string(client_conn, "-see-RFC-2388\r\n");
+ send_chunk_string(client_conn, "Content-Disposition: form-data; ");
+ send_chunk_string(client_conn, "name=\"dontread\"\r\n");
+ send_chunk_string(client_conn, "\r\n");
+ send_chunk_string(client_conn, "xyz\r\n");
+ send_chunk_string(client_conn, "--multipart-form-data-boundary");
+ send_chunk_string(client_conn, "--see-RFC-2388--\r\n");
+ mg_printf(client_conn, "0\r\n");
+
+ for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) {
+ test_sleep(1);
+ if (g_field_step == 1000) {
+ break;
+ }
+ }
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "200");
+ mg_close_connection(client_conn);
+
+
+ /* Handle form: "POST multipart/form-data", chunked, store, with files */
+ client_conn =
+ mg_download("localhost",
+ 8884,
+ 0,
+ ebuf,
+ sizeof(ebuf),
+ "%s",
+ "POST /handle_form_store2 HTTP/1.0\r\n"
+ "Host: localhost:8884\r\n"
+ "Connection: close\r\n"
+ "Content-Type: multipart/form-data; "
+ "boundary=multipart-form-data-boundary--see-RFC-2388\r\n"
+ "Transfer-Encoding: chunked\r\n"
+ "\r\n");
+ ck_assert(client_conn != NULL);
+
+ boundary = "--multipart-form-data-boundary--see-RFC-2388\r\n";
+
+ send_chunk_string(client_conn, boundary);
+ send_chunk_string(client_conn, "Content-Disposition: form-data; ");
+ send_chunk_string(client_conn, "name=\"storeme\"\r\n");
+ send_chunk_string(client_conn, "\r\n");
+ send_chunk_string(client_conn, "storetest\r\n");
+
+ send_chunk_string(client_conn, boundary);
+ send_chunk_string(client_conn, "Content-Disposition: form-data; ");
+ send_chunk_string(client_conn, "name=\"continue_field_handler\";");
+ send_chunk_string(client_conn, "filename=\"file_ignored.txt\"\r\n");
+ send_chunk_string(client_conn, "Content-Type: ");
+ send_chunk_string(client_conn, "application/octet-stream\r\n");
+ send_chunk_string(client_conn, "X-Ignored-Header: xyz\r\n");
+ send_chunk_string(client_conn, "\r\n");
+
+ /* send some kilobyte of data */
+ /* sending megabytes to localhost does not allways work in CI test
+ * environments (depending on the network stack) */
+ body_sent = 0;
+ do {
+ send_chunk_string(client_conn, "ignore\r\n");
+ body_sent += 8;
+ /* send some strings that are almost boundaries */
+ for (chunk_len = 1; chunk_len < strlen(boundary); chunk_len++) {
+ /* chunks from 1 byte to strlen(boundary)-1 */
+ send_chunk_stringl(client_conn, boundary, (unsigned int)chunk_len);
+ body_sent += chunk_len;
+ }
+ } while (body_sent < 8 * 1024);
+ send_chunk_string(client_conn, "\r\n");
+
+ send_chunk_string(client_conn, boundary);
+ send_chunk_string(client_conn, "Content-Disposition: form-data; ");
+ send_chunk_string(client_conn, "name=\"file2store\";");
+ send_chunk_string(client_conn, "filename=\"myfile.txt\"\r\n");
+ send_chunk_string(client_conn, "Content-Type: ");
+ send_chunk_string(client_conn, "application/octet-stream\r\n");
+ send_chunk_string(client_conn, "X-Ignored-Header: xyz\r\n");
+ send_chunk_string(client_conn, "\r\n");
+ for (body_sent = 0; (int)body_sent < (int)myfile_content_rep; body_sent++) {
+ send_chunk_string(client_conn, myfile_content);
+ }
+ send_chunk_string(client_conn, "\r\n");
+
+ send_chunk_string(client_conn, boundary);
+ send_chunk_string(client_conn, "Content-Disposition: form-data; ");
+ send_chunk_string(client_conn, "name=\"break_field_handler\"\r\n");
+ send_chunk_string(client_conn, "\r\n");
+ send_chunk_string(client_conn, "abort\r\n");
+
+ send_chunk_string(client_conn, boundary);
+ send_chunk_string(client_conn, "Content-Disposition: form-data; ");
+ send_chunk_string(client_conn, "name=\"dontread\"\r\n");
+ send_chunk_string(client_conn, "\r\n");
+ send_chunk_string(client_conn, "xyz\r\n");
+ send_chunk_string(client_conn, "--multipart-form-data-boundary");
+ send_chunk_string(client_conn, "--see-RFC-2388--\r\n");
+ mg_printf(client_conn, "0\r\n");
+
+ for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) {
+ test_sleep(1);
+ if (g_field_step == 1000) {
+ break;
+ }
+ }
+ ri = mg_get_request_info(client_conn);
+
+ ck_assert(ri != NULL);
+ ck_assert_str_eq(ri->local_uri, "200");
+ mg_close_connection(client_conn);
+
+
+ /* Close the server */
+ g_ctx = NULL;
+ test_mg_stop(ctx);
+ mark_point();
+}
+END_TEST
+
+
+START_TEST(test_http_auth)
+{
+#if !defined(NO_FILES)
+ const char *OPTIONS[] = {
+ "document_root",
+ ".",
+ "listening_ports",
+ "8080",
+#if !defined(NO_CACHING)
+ "static_file_max_age",
+ "0",
+#endif
+ "put_delete_auth_file",
+ "put_delete_auth_file.csv",
+ NULL,
+ };
+
+ struct mg_context *ctx;
+ struct mg_connection *client_conn;
+ char client_err[256], nonce[256];
+ const struct mg_request_info *client_ri;
+ int client_res;
+ FILE *f;
+ const char *passwd_file = ".htpasswd";
+ const char *test_file = "test_http_auth.test_file.txt";
+ const char *test_content = "test_http_auth test_file content";
+ const char *domain;
+ const char *doc_root;
+ const char *auth_request;
+ const char *str;
+ size_t len;
+ int i;
+ char HA1[256], HA2[256], HA[256];
+ char HA1_md5_buf[33], HA2_md5_buf[33], HA_md5_buf[33];
+ char *HA1_md5_ret, *HA2_md5_ret, *HA_md5_ret;
+ const char *nc = "00000001";
+ const char *cnonce = "6789ABCD";
+
+ mark_point();
+
+ /* Start with default options */
+ ctx = test_mg_start(NULL, NULL, OPTIONS);
+
+ ck_assert(ctx != NULL);
+ domain = mg_get_option(ctx, "authentication_domain");
+ ck_assert(domain != NULL);
+ len = strlen(domain);
+ ck_assert_uint_gt(len, 0);
+ ck_assert_uint_lt(len, 64);
+ doc_root = mg_get_option(ctx, "document_root");
+ ck_assert_str_eq(doc_root, ".");
+
+ /* Create a default file in the document root */
+ f = fopen(test_file, "w");
+ if (f) {
+ fprintf(f, "%s", test_content);
+ fclose(f);
+ } else {
+ ck_abort_msg("Cannot create file %s", test_file);
+ }
+
+ (void)remove(passwd_file);
+ (void)remove("put_delete_auth_file.csv");
+
+ client_res = mg_modify_passwords_file("put_delete_auth_file.csv",
+ domain,
+ "admin",
+ "adminpass");
+ ck_assert_int_eq(client_res, 1);
+
+ /* Read file before a .htpasswd file has been created */
+ memset(client_err, 0, sizeof(client_err));
+ client_conn =
+ mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
+
+ ck_assert_str_eq(client_err, "");
+ ck_assert(client_conn != NULL);
+
+ mg_printf(client_conn, "GET /%s HTTP/1.0\r\n\r\n", test_file);
+ client_res =
+ mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
+ ck_assert_int_ge(client_res, 0);
+ ck_assert_str_eq(client_err, "");
+ client_ri = mg_get_request_info(client_conn);
+ ck_assert(client_ri != NULL);
+
+ ck_assert_str_eq(client_ri->local_uri, "200");
+ client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
+ ck_assert_int_gt(client_res, 0);
+ ck_assert_int_le(client_res, sizeof(client_err));
+ ck_assert_str_eq(client_err, test_content);
+ mg_close_connection(client_conn);
+
+ test_sleep(1);
+
+ /* Create a .htpasswd file */
+ client_res = mg_modify_passwords_file(passwd_file, domain, "user", "pass");
+ ck_assert_int_eq(client_res, 1);
+
+ client_res = mg_modify_passwords_file(NULL, domain, "user", "pass");
+ ck_assert_int_eq(client_res, 0); /* Filename is required */
+
+ test_sleep(1);
+
+ /* Repeat test after .htpasswd is created */
+ memset(client_err, 0, sizeof(client_err));
+ client_conn =
+ mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
+
+ ck_assert_str_eq(client_err, "");
+ ck_assert(client_conn != NULL);
+
+ mg_printf(client_conn, "GET /%s HTTP/1.0\r\n\r\n", test_file);
+ client_res =
+ mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
+ ck_assert_int_ge(client_res, 0);
+ ck_assert_str_eq(client_err, "");
+ client_ri = mg_get_request_info(client_conn);
+ ck_assert(client_ri != NULL);
+
+ ck_assert_str_eq(client_ri->local_uri, "401");
+
+ auth_request = NULL;
+ for (i = 0; i < client_ri->num_headers; i++) {
+ if (!mg_strcasecmp(client_ri->http_headers[i].name,
+ "WWW-Authenticate")) {
+ ck_assert_ptr_eq(auth_request, NULL);
+ auth_request = client_ri->http_headers[i].value;
+ ck_assert_ptr_ne(auth_request, NULL);
+ }
+ }
+ ck_assert_ptr_ne(auth_request, NULL);
+ str = "Digest qop=\"auth\", realm=\"";
+ len = strlen(str);
+ ck_assert(!mg_strncasecmp(auth_request, str, len));
+ ck_assert(!strncmp(auth_request + len, domain, strlen(domain)));
+ len += strlen(domain);
+ str = "\", nonce=\"";
+ ck_assert(!strncmp(auth_request + len, str, strlen(str)));
+ len += strlen(str);
+ str = strchr(auth_request + len, '\"');
+ ck_assert_ptr_ne(str, NULL);
+ ck_assert_ptr_ne(str, auth_request + len);
+ /* nonce is from including (auth_request + len) to excluding (str) */
+ ck_assert_int_gt((ptrdiff_t)(str) - (ptrdiff_t)(auth_request + len), 0);
+ ck_assert_int_lt((ptrdiff_t)(str) - (ptrdiff_t)(auth_request + len),
+ (ptrdiff_t)sizeof(nonce));
+ memset(nonce, 0, sizeof(nonce));
+ memcpy(nonce,
+ auth_request + len,
+ (size_t)((ptrdiff_t)(str) - (ptrdiff_t)(auth_request + len)));
+ memset(HA1, 0, sizeof(HA1));
+ memset(HA2, 0, sizeof(HA2));
+ memset(HA, 0, sizeof(HA));
+ memset(HA1_md5_buf, 0, sizeof(HA1_md5_buf));
+ memset(HA2_md5_buf, 0, sizeof(HA2_md5_buf));
+ memset(HA_md5_buf, 0, sizeof(HA_md5_buf));
+
+ sprintf(HA1, "%s:%s:%s", "user", domain, "pass");
+ sprintf(HA2, "%s:/%s", "GET", test_file);
+ HA1_md5_ret = mg_md5(HA1_md5_buf, HA1, NULL);
+ HA2_md5_ret = mg_md5(HA2_md5_buf, HA2, NULL);
+
+ ck_assert_ptr_eq(HA1_md5_ret, HA1_md5_buf);
+ ck_assert_ptr_eq(HA2_md5_ret, HA2_md5_buf);
+
+ HA_md5_ret = mg_md5(HA_md5_buf, "user", ":", domain, ":", "pass", NULL);
+ ck_assert_ptr_eq(HA_md5_ret, HA_md5_buf);
+ ck_assert_str_eq(HA1_md5_ret, HA_md5_buf);
+
+ HA_md5_ret = mg_md5(HA_md5_buf, "GET", ":", "/", test_file, NULL);
+ ck_assert_ptr_eq(HA_md5_ret, HA_md5_buf);
+ ck_assert_str_eq(HA2_md5_ret, HA_md5_buf);
+
+ HA_md5_ret = mg_md5(HA_md5_buf,
+ HA1_md5_buf,
+ ":",
+ nonce,
+ ":",
+ nc,
+ ":",
+ cnonce,
+ ":",
+ "auth",
+ ":",
+ HA2_md5_buf,
+ NULL);
+ ck_assert_ptr_eq(HA_md5_ret, HA_md5_buf);
+
+ mg_close_connection(client_conn);
+
+ /* Retry with authorization */
+ memset(client_err, 0, sizeof(client_err));
+ client_conn =
+ mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
+
+ ck_assert_str_eq(client_err, "");
+ ck_assert(client_conn != NULL);
+
+ mg_printf(client_conn, "GET /%s HTTP/1.0\r\n", test_file);
+ mg_printf(client_conn,
+ "Authorization: Digest "
+ "username=\"%s\", "
+ "realm=\"%s\", "
+ "nonce=\"%s\", "
+ "uri=\"/%s\", "
+ "qop=auth, "
+ "nc=%s, "
+ "cnonce=\"%s\", "
+ "response=\"%s\"\r\n\r\n",
+ "user",
+ domain,
+ nonce,
+ test_file,
+ nc,
+ cnonce,
+ HA_md5_buf);
+ client_res =
+ mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
+ ck_assert_int_ge(client_res, 0);
+ ck_assert_str_eq(client_err, "");
+ client_ri = mg_get_request_info(client_conn);
+ ck_assert(client_ri != NULL);
+
+ ck_assert_str_eq(client_ri->local_uri, "200");
+ client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
+ ck_assert_int_gt(client_res, 0);
+ ck_assert_int_le(client_res, sizeof(client_err));
+ ck_assert_str_eq(client_err, test_content);
+ mg_close_connection(client_conn);
+
+ test_sleep(1);
+
+ /* Retry DELETE with authorization of a user not authorized for DELETE */
+ memset(client_err, 0, sizeof(client_err));
+ client_conn =
+ mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
+
+ ck_assert_str_eq(client_err, "");
+ ck_assert(client_conn != NULL);
+
+ mg_printf(client_conn, "DELETE /%s HTTP/1.0\r\n", test_file);
+ mg_printf(client_conn,
+ "Authorization: Digest "
+ "username=\"%s\", "
+ "realm=\"%s\", "
+ "nonce=\"%s\", "
+ "uri=\"/%s\", "
+ "qop=auth, "
+ "nc=%s, "
+ "cnonce=\"%s\", "
+ "response=\"%s\"\r\n\r\n",
+ "user",
+ domain,
+ nonce,
+ test_file,
+ nc,
+ cnonce,
+ HA_md5_buf);
+ client_res =
+ mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
+ ck_assert_int_ge(client_res, 0);
+ ck_assert_str_eq(client_err, "");
+ client_ri = mg_get_request_info(client_conn);
+ ck_assert(client_ri != NULL);
+
+ ck_assert_str_eq(client_ri->local_uri, "401");
+ mg_close_connection(client_conn);
+
+ test_sleep(1);
+
+ /* Remove the user from the .htpasswd file again */
+ client_res = mg_modify_passwords_file(passwd_file, domain, "user", NULL);
+ ck_assert_int_eq(client_res, 1);
+
+ test_sleep(1);
+
+
+ /* Try to access the file again. Expected: 401 error */
+ memset(client_err, 0, sizeof(client_err));
+ client_conn =
+ mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
+
+ ck_assert_str_eq(client_err, "");
+ ck_assert(client_conn != NULL);
+
+ mg_printf(client_conn, "GET /%s HTTP/1.0\r\n\r\n", test_file);
+ client_res =
+ mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
+ ck_assert_int_ge(client_res, 0);
+ ck_assert_str_eq(client_err, "");
+ client_ri = mg_get_request_info(client_conn);
+ ck_assert(client_ri != NULL);
+
+ ck_assert_str_eq(client_ri->local_uri, "401");
+ mg_close_connection(client_conn);
+
+ test_sleep(1);
+
+
+ /* Now remove the password file */
+ (void)remove(passwd_file);
+ test_sleep(1);
+
+
+ /* Access to the file must work like before */
+ memset(client_err, 0, sizeof(client_err));
+ client_conn =
+ mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
+
+ ck_assert_str_eq(client_err, "");
+ ck_assert(client_conn != NULL);
+
+ mg_printf(client_conn, "GET /%s HTTP/1.0\r\n\r\n", test_file);
+ client_res =
+ mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
+ ck_assert_int_ge(client_res, 0);
+ ck_assert_str_eq(client_err, "");
+ client_ri = mg_get_request_info(client_conn);
+ ck_assert(client_ri != NULL);
+
+ ck_assert_str_eq(client_ri->local_uri, "200");
+ client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
+ ck_assert_int_gt(client_res, 0);
+ ck_assert_int_le(client_res, sizeof(client_err));
+ ck_assert_str_eq(client_err, test_content);
+ mg_close_connection(client_conn);
+
+ test_sleep(1);
+
+
+ /* Stop the server and clean up */
+ test_mg_stop(ctx);
+ (void)remove(test_file);
+ (void)remove(passwd_file);
+ (void)remove("put_delete_auth_file.csv");
+
+#endif
+ mark_point();
+}
+END_TEST
+
+
+START_TEST(test_keep_alive)
+{
+ struct mg_context *ctx;
+ const char *OPTIONS[] =
+ { "listening_ports",
+ "8081",
+ "request_timeout_ms",
+ "10000",
+ "enable_keep_alive",
+ "yes",
+#if !defined(NO_FILES)
+ "document_root",
+ ".",
+ "enable_directory_listing",
+ "no",
+#endif
+ NULL };
+
+ struct mg_connection *client_conn;
+ char client_err[256];
+ const struct mg_request_info *client_ri;
+ int client_res, i;
+ const char *connection_header;
+
+ mark_point();
+
+ ctx = test_mg_start(NULL, NULL, OPTIONS);
+
+ ck_assert(ctx != NULL);
+
+ /* HTTP 1.1 GET request */
+ memset(client_err, 0, sizeof(client_err));
+ client_conn =
+ mg_connect_client("127.0.0.1", 8081, 0, client_err, sizeof(client_err));
+
+ ck_assert_str_eq(client_err, "");
+ ck_assert(client_conn != NULL);
+
+ mg_printf(client_conn,
+ "GET / HTTP/1.1\r\nHost: "
+ "localhost:8081\r\nConnection: keep-alive\r\n\r\n");
+ client_res =
+ mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
+ ck_assert_int_ge(client_res, 0);
+ ck_assert_str_eq(client_err, "");
+ client_ri = mg_get_request_info(client_conn);
+ ck_assert(client_ri != NULL);
+
+#if defined(NO_FILES)
+ ck_assert_str_eq(client_ri->local_uri, "404");
+#else
+ ck_assert_str_eq(client_ri->local_uri, "403");
+#endif
+
+ connection_header = 0;
+ for (i = 0; i < client_ri->num_headers; i++) {
+ if (!mg_strcasecmp(client_ri->http_headers[i].name, "Connection")) {
+ ck_assert_ptr_eq(connection_header, NULL);
+ connection_header = client_ri->http_headers[i].value;
+ ck_assert_ptr_ne(connection_header, NULL);
+ }
+ }
+ /* Error replies will close the connection, even if keep-alive is set. */
+ ck_assert_ptr_ne(connection_header, NULL);
+ ck_assert_str_eq(connection_header, "close");
+ mg_close_connection(client_conn);
+
+ test_sleep(1);
+
+ /* TODO: request a file and keep alive
+ * (will only work if NO_FILES is not set). */
+
+ /* Stop the server and clean up */
+ test_mg_stop(ctx);
+
+ mark_point();
+}
+END_TEST
+
+
+START_TEST(test_error_handling)
+{
+ struct mg_context *ctx;
+ FILE *f;
+
+ char bad_thread_num[32] = "badnumber";
+
+ struct mg_callbacks callbacks;
+ char errmsg[256];
+
+ struct mg_connection *client_conn;
+ char client_err[256];
+ const struct mg_request_info *client_ri;
+ int client_res, i;
+
+ const char *OPTIONS[32];
+ int opt_cnt = 0;
+
+ mark_point();
+
+#if !defined(NO_FILES)
+ OPTIONS[opt_cnt++] = "document_root";
+ OPTIONS[opt_cnt++] = ".";
+#endif
+ OPTIONS[opt_cnt++] = "error_pages";
+ OPTIONS[opt_cnt++] = "./";
+ OPTIONS[opt_cnt++] = "listening_ports";
+ OPTIONS[opt_cnt++] = "8080";
+ OPTIONS[opt_cnt++] = "num_threads";
+ OPTIONS[opt_cnt++] = bad_thread_num;
+ OPTIONS[opt_cnt++] = "unknown_option";
+ OPTIONS[opt_cnt++] = "unknown_option_value";
+ OPTIONS[opt_cnt] = NULL;
+
+ memset(&callbacks, 0, sizeof(callbacks));
+
+ callbacks.log_message = log_msg_func;
+
+ /* test with unknown option */
+ memset(errmsg, 0, sizeof(errmsg));
+ ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS);
+
+ /* Details of errmsg may vary, but it may not be empty */
+ ck_assert_str_ne(errmsg, "");
+ ck_assert(ctx == NULL);
+ ck_assert_str_eq(errmsg, "Invalid option: unknown_option");
+
+ /* Remove invalid option */
+ for (i = 0; OPTIONS[i]; i++) {
+ if (strstr(OPTIONS[i], "unknown_option")) {
+ OPTIONS[i] = 0;
+ }
+ }
+
+ /* Test with bad num_thread option */
+ memset(errmsg, 0, sizeof(errmsg));
+ ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS);
+
+ /* Details of errmsg may vary, but it may not be empty */
+ ck_assert_str_ne(errmsg, "");
+ ck_assert(ctx == NULL);
+ ck_assert_str_eq(errmsg, "Invalid number of worker threads");
+
+/* Set to a number - but use a number above the limit */
+#ifdef MAX_WORKER_THREADS
+ sprintf(bad_thread_num, "%u", MAX_WORKER_THREADS + 1);
+#else
+ sprintf(bad_thread_num, "%lu", 1000000000lu);
+#endif
+
+ /* Test with bad num_thread option */
+ memset(errmsg, 0, sizeof(errmsg));
+ ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS);
+
+ /* Details of errmsg may vary, but it may not be empty */
+ ck_assert_str_ne(errmsg, "");
+ ck_assert(ctx == NULL);
+ ck_assert_str_eq(errmsg, "Too many worker threads");
+
+
+ /* HTTP 1.0 GET request - server is not running */
+ memset(client_err, 0, sizeof(client_err));
+ client_conn =
+ mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
+ ck_assert(client_conn == NULL);
+
+ /* Error message detail may vary - it may not be empty ans should contain
+ * some information "connect" failed */
+ ck_assert_str_ne(client_err, "");
+ ck_assert(strstr(client_err, "connect"));
+
+
+ /* This time start the server with a valid configuration */
+ sprintf(bad_thread_num, "%i", 1);
+ memset(errmsg, 0, sizeof(errmsg));
+ ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS);
+
+ ck_assert_str_eq(errmsg, "");
+ ck_assert(ctx != NULL);
+
+
+ /* Server is running now */
+ test_sleep(1);
+
+ /* Remove error files (in case they exist) */
+ (void)remove("error.htm");
+ (void)remove("error4xx.htm");
+ (void)remove("error404.htm");
+
+
+ /* Ask for something not existing - should get default 404 */
+ memset(client_err, 0, sizeof(client_err));
+ client_conn =
+ mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
+
+ ck_assert_str_eq(client_err, "");
+ ck_assert(client_conn != NULL);
+
+ mg_printf(client_conn, "GET /something/not/existing HTTP/1.0\r\n\r\n");
+ client_res =
+ mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
+ ck_assert_int_ge(client_res, 0);
+ ck_assert_str_eq(client_err, "");
+ client_ri = mg_get_request_info(client_conn);
+ ck_assert(client_ri != NULL);
+
+ ck_assert_str_eq(client_ri->local_uri, "404");
+ mg_close_connection(client_conn);
+ test_sleep(1);
+
+ /* Create an error.htm file */
+ f = fopen("error.htm", "wt");
+ ck_assert(f != NULL);
+ (void)fprintf(f, "err-all");
+ (void)fclose(f);
+
+
+ /* Ask for something not existing - should get error.htm */
+ memset(client_err, 0, sizeof(client_err));
+ client_conn =
+ mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
+
+ ck_assert_str_eq(client_err, "");
+ ck_assert(client_conn != NULL);
+
+ mg_printf(client_conn, "GET /something/not/existing HTTP/1.0\r\n\r\n");
+ client_res =
+ mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
+ ck_assert_int_ge(client_res, 0);
+ ck_assert_str_eq(client_err, "");
+ client_ri = mg_get_request_info(client_conn);
+ ck_assert(client_ri != NULL);
+
+ ck_assert_str_eq(client_ri->local_uri, "200");
+
+ client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
+ mg_close_connection(client_conn);
+ ck_assert_int_eq(client_res, 7);
+ client_err[8] = 0;
+ ck_assert_str_eq(client_err, "err-all");
+ test_sleep(1);
+
+ /* Create an error4xx.htm file */
+ f = fopen("error4xx.htm", "wt");
+ ck_assert(f != NULL);
+ (void)fprintf(f, "err-4xx");
+ (void)fclose(f);
+
+
+ /* Ask for something not existing - should get error4xx.htm */
+ memset(client_err, 0, sizeof(client_err));
+ client_conn =
+ mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
+
+ ck_assert_str_eq(client_err, "");
+ ck_assert(client_conn != NULL);
+
+ mg_printf(client_conn, "GET /something/not/existing HTTP/1.0\r\n\r\n");
+ client_res =
+ mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
+ ck_assert_int_ge(client_res, 0);
+ ck_assert_str_eq(client_err, "");
+ client_ri = mg_get_request_info(client_conn);
+ ck_assert(client_ri != NULL);
+
+ ck_assert_str_eq(client_ri->local_uri, "200");
+
+ client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
+ mg_close_connection(client_conn);
+ ck_assert_int_eq(client_res, 7);
+ client_err[8] = 0;
+ ck_assert_str_eq(client_err, "err-4xx");
+ test_sleep(1);
+
+ /* Create an error404.htm file */
+ f = fopen("error404.htm", "wt");
+ ck_assert(f != NULL);
+ (void)fprintf(f, "err-404");
+ (void)fclose(f);
+
+
+ /* Ask for something not existing - should get error404.htm */
+ memset(client_err, 0, sizeof(client_err));
+ client_conn =
+ mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
+
+ ck_assert_str_eq(client_err, "");
+ ck_assert(client_conn != NULL);
+
+ mg_printf(client_conn, "GET /something/not/existing HTTP/1.0\r\n\r\n");
+ client_res =
+ mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
+ ck_assert_int_ge(client_res, 0);
+ ck_assert_str_eq(client_err, "");
+ client_ri = mg_get_request_info(client_conn);
+ ck_assert(client_ri != NULL);
+
+ ck_assert_str_eq(client_ri->local_uri, "200");
+
+ client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
+ mg_close_connection(client_conn);
+ ck_assert_int_eq(client_res, 7);
+ client_err[8] = 0;
+ ck_assert_str_eq(client_err, "err-404");
+ test_sleep(1);
+
+
+ /* Ask in a malformed way - should get error4xx.htm */
+ memset(client_err, 0, sizeof(client_err));
+ client_conn =
+ mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
+
+ ck_assert_str_eq(client_err, "");
+ ck_assert(client_conn != NULL);
+
+ mg_printf(client_conn, "Gimme some file!\r\n\r\n");
+ client_res =
+ mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
+ ck_assert_int_ge(client_res, 0);
+ ck_assert_str_eq(client_err, "");
+ client_ri = mg_get_request_info(client_conn);
+ ck_assert(client_ri != NULL);
+
+ ck_assert_str_eq(client_ri->local_uri, "200");
+
+ client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
+ mg_close_connection(client_conn);
+ ck_assert_int_eq(client_res, 7);
+ client_err[8] = 0;
+ ck_assert_str_eq(client_err, "err-4xx");
+ test_sleep(1);
+
+
+ /* Remove all error files created by this test */
+ (void)remove("error.htm");
+ (void)remove("error4xx.htm");
+ (void)remove("error404.htm");
+
+
+ /* Stop the server */
+ test_mg_stop(ctx);
+
+
+ /* HTTP 1.1 GET request - must not work, since server is already stopped */
+ memset(client_err, 0, sizeof(client_err));
+ client_conn =
+ mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err));
+
+ ck_assert(client_conn == NULL);
+ ck_assert_str_ne(client_err, "");
+
+ test_sleep(1);
+
+ mark_point();
+}
+END_TEST
+
+
+START_TEST(test_error_log_file)
+{
+ /* Server var */
+ struct mg_context *ctx;
+ const char *OPTIONS[32];
+ int opt_cnt = 0;
+
+ /* Client var */
+ struct mg_connection *client;
+ char client_err_buf[256];
+ char client_data_buf[256];
+ const struct mg_request_info *client_ri;
+
+ /* File content check var */
+ FILE *f;
+ char buf[1024];
+ int len, ok;
+
+ mark_point();
+
+ /* Set options and start server */
+ OPTIONS[opt_cnt++] = "listening_ports";
+ OPTIONS[opt_cnt++] = "8080";
+ OPTIONS[opt_cnt++] = "error_log_file";
+ OPTIONS[opt_cnt++] = "error.log";
+ OPTIONS[opt_cnt++] = "access_log_file";
+ OPTIONS[opt_cnt++] = "access.log";
+#if !defined(NO_FILES)
+ OPTIONS[opt_cnt++] = "document_root";
+ OPTIONS[opt_cnt++] = ".";
+#endif
+ OPTIONS[opt_cnt] = NULL;
+
+ ctx = test_mg_start(NULL, 0, OPTIONS);
+ ck_assert(ctx != NULL);
+
+ /* Remove log files (they may exist from previous incomplete runs of
+ * this test) */
+ (void)remove("error.log");
+ (void)remove("access.log");
+
+ /* connect client */
+ memset(client_err_buf, 0, sizeof(client_err_buf));
+ memset(client_data_buf, 0, sizeof(client_data_buf));
+
+ client = mg_download("127.0.0.1",
+ 8080,
+ 0,
+ client_err_buf,
+ sizeof(client_err_buf),
+ "GET /not_existing_file.ext HTTP/1.0\r\n\r\n");
+
+ ck_assert(ctx != NULL);
+ ck_assert_str_eq(client_err_buf, "");
+
+ client_ri = mg_get_request_info(client);
+
+ ck_assert(client_ri != NULL);
+ ck_assert_str_eq(client_ri->local_uri, "404");
+
+ /* Close the client connection */
+ mg_close_connection(client);
+
+ /* Stop the server */
+ test_mg_stop(ctx);
+
+
+ /* Check access.log */
+ memset(buf, 0, sizeof(buf));
+ f = fopen("access.log", "r");
+ ck_assert_msg(f != NULL, "Cannot open access log file");
+ ok = (NULL != fgets(buf, sizeof(buf) - 1, f));
+ (void)fclose(f);
+ ck_assert_msg(ok, "Cannot read access log file");
+ len = (int)strlen(buf);
+ ck_assert_int_gt(len, 0);
+ ok = (NULL != strstr(buf, "not_existing_file.ext"));
+ ck_assert_msg(ok, "Did not find uri in access log file");
+ ok = (NULL != strstr(buf, "404"));
+ ck_assert_msg(ok, "Did not find HTTP status code in access log file");
+
+ /* Check error.log */
+ memset(buf, 0, sizeof(buf));
+ f = fopen("error.log", "r");
+ if (f) {
+ (void)fgets(buf, sizeof(buf) - 1, f);
+ fclose(f);
+ }
+ ck_assert_msg(f == NULL,
+ "Should not create error log file on 404, but got [%s]",
+ buf);
+
+ /* Remove log files */
+ (void)remove("error.log");
+ (void)remove("access.log");
+
+ /* Start server with bad options */
+ ck_assert_str_eq(OPTIONS[0], "listening_ports");
+ OPTIONS[1] = "bad port syntax";
+
+ ctx = test_mg_start(NULL, 0, OPTIONS);
+ ck_assert_msg(
+ ctx == NULL,
+ "Should not be able to start server with bad port configuration");
+
+ /* Check access.log */
+ memset(buf, 0, sizeof(buf));
+ f = fopen("access.log", "r");
+ if (f) {
+ (void)fgets(buf, sizeof(buf) - 1, f);
+ fclose(f);
+ }
+ ck_assert_msg(
+ f == NULL,
+ "Should not create access log file if start fails, but got [%s]",
+ buf);
+
+ /* Check error.log */
+ memset(buf, 0, sizeof(buf));
+ f = fopen("error.log", "r");
+ ck_assert_msg(f != NULL, "Cannot open access log file");
+ ok = (NULL != fgets(buf, sizeof(buf) - 1, f));
+ (void)fclose(f);
+ ck_assert_msg(ok, "Cannot read access log file");
+ len = (int)strlen(buf);
+ ck_assert_int_gt(len, 0);
+ ok = (NULL != strstr(buf, "port"));
+ ck_assert_msg(ok, "Did not find port as error reason in error log file");
+
+
+ /* Remove log files */
+ (void)remove("error.log");
+ (void)remove("access.log");
+
+ mark_point();
+}
+END_TEST
+
+
+static int
+test_throttle_begin_request(struct mg_connection *conn)
+{
+ const struct mg_request_info *ri;
+ long unsigned len = 1024 * 10;
+ const char *block = "0123456789";
+ unsigned long i, blocklen;
+
+ ck_assert(conn != NULL);
+ ri = mg_get_request_info(conn);
+ ck_assert(ri != NULL);
+
+ ck_assert_str_eq(ri->request_method, "GET");
+ ck_assert_str_eq(ri->request_uri, "/throttle");
+ ck_assert_str_eq(ri->local_uri, "/throttle");
+ ck_assert_str_eq(ri->http_version, "1.0");
+ ck_assert_str_eq(ri->query_string, "q");
+ ck_assert_str_eq(ri->remote_addr, "127.0.0.1");
+
+ mg_printf(conn,
+ "HTTP/1.1 200 OK\r\n"
+ "Content-Length: %lu\r\n"
+ "Connection: close\r\n\r\n",
+ len);
+
+ blocklen = (unsigned long)strlen(block);
+
+ for (i = 0; i < len; i += blocklen) {
+ mg_write(conn, block, blocklen);
+ }
+
+ mark_point();
+
+ return 987; /* Not a valid HTTP response code,
+ * but it should be written to the log and passed to
+ * end_request. */
+}
+
+
+static void
+test_throttle_end_request(const struct mg_connection *conn,
+ int reply_status_code)
+{
+ const struct mg_request_info *ri;
+
+ ck_assert(conn != NULL);
+ ri = mg_get_request_info(conn);
+ ck_assert(ri != NULL);
+
+ ck_assert_str_eq(ri->request_method, "GET");
+ ck_assert_str_eq(ri->request_uri, "/throttle");
+ ck_assert_str_eq(ri->local_uri, "/throttle");
+ ck_assert_str_eq(ri->http_version, "1.0");
+ ck_assert_str_eq(ri->query_string, "q");
+ ck_assert_str_eq(ri->remote_addr, "127.0.0.1");
+
+ ck_assert_int_eq(reply_status_code, 987);
+}
+
+
+START_TEST(test_throttle)
+{
+ /* Server var */
+ struct mg_context *ctx;
+ struct mg_callbacks callbacks;
+ const char *OPTIONS[32];
+ int opt_cnt = 0;
+
+ /* Client var */
+ struct mg_connection *client;
+ char client_err_buf[256];
+ char client_data_buf[256];
+ const struct mg_request_info *client_ri;
+
+ /* timing test */
+ int r, data_read;
+ time_t t0, t1;
+ double dt;
+
+ mark_point();
+
+
+/* Set options and start server */
+#if !defined(NO_FILES)
+ OPTIONS[opt_cnt++] = "document_root";
+ OPTIONS[opt_cnt++] = ".";
+#endif
+ OPTIONS[opt_cnt++] = "listening_ports";
+ OPTIONS[opt_cnt++] = "8080";
+ OPTIONS[opt_cnt++] = "throttle";
+ OPTIONS[opt_cnt++] = "*=1k";
+ OPTIONS[opt_cnt] = NULL;
+
+ memset(&callbacks, 0, sizeof(callbacks));
+ callbacks.begin_request = test_throttle_begin_request;
+ callbacks.end_request = test_throttle_end_request;
+
+ ctx = test_mg_start(&callbacks, 0, OPTIONS);
+ ck_assert(ctx != NULL);
+
+ /* connect client */
+ memset(client_err_buf, 0, sizeof(client_err_buf));
+ memset(client_data_buf, 0, sizeof(client_data_buf));
+
+ strcpy(client_err_buf, "reset-content");
+ client = mg_download("127.0.0.1",
+ 8080,
+ 0,
+ client_err_buf,
+ sizeof(client_err_buf),
+ "GET /throttle?q HTTP/1.0\r\n\r\n");
+
+ ck_assert(ctx != NULL);
+ ck_assert_str_eq(client_err_buf, "");
+
+ client_ri = mg_get_request_info(client);
+
+ ck_assert(client_ri != NULL);
+ ck_assert_str_eq(client_ri->local_uri, "200");
+
+ ck_assert_int_eq(client_ri->content_length, 1024 * 10);
+
+ data_read = 0;
+ t0 = time(NULL);
+ while (data_read < client_ri->content_length) {
+ r = mg_read(client, client_data_buf, sizeof(client_data_buf));
+ ck_assert_int_ge(r, 0);
+ data_read += r;
+ }
+ t1 = time(NULL);
+ dt = difftime(t1, t0) * 1000.0; /* Elapsed time in ms - in most systems
+ * only with second resolution */
+
+ /* Time estimation: Data size is 10 kB, with 1 kB/s speed limit.
+ * The first block (1st kB) is transferred immediately, the second
+ * block (2nd kB) one second later, the third block (3rd kB) two
+ * seconds later, .. the last block (10th kB) nine seconds later.
+ * The resolution of time measurement using the "time" C library
+ * function is 1 second, so we should add +/- one second tolerance.
+ * Thus, download of 10 kB with 1 kB/s should not be faster than
+ * 8 seconds. */
+
+ /* Check if there are at least 8 seconds */
+ ck_assert_int_ge((int)dt, 8 * 1000);
+
+ /* Nothing left to read */
+ r = mg_read(client, client_data_buf, sizeof(client_data_buf));
+ ck_assert_int_eq(r, 0);
+
+ /* Close the client connection */
+ mg_close_connection(client);
+
+ /* Stop the server */
+ test_mg_stop(ctx);
+
+ mark_point();
+}
+END_TEST
+
+
+START_TEST(test_init_library)
+{
+ unsigned f_avail, f_ret;
+
+ mark_point();
+
+ f_avail = mg_check_feature(0xFF);
+ f_ret = mg_init_library(f_avail);
+ ck_assert_uint_eq(f_ret, f_avail);
+}
+END_TEST
+
+
+#define LARGE_FILE_SIZE (1024 * 1024 * 10)
+
+static int
+test_large_file_begin_request(struct mg_connection *conn)
+{
+ const struct mg_request_info *ri;
+ long unsigned len = LARGE_FILE_SIZE;
+ const char *block = "0123456789";
+ uint64_t i;
+ size_t blocklen;
+
+ ck_assert(conn != NULL);
+ ri = mg_get_request_info(conn);
+ ck_assert(ri != NULL);
+
+ ck_assert_str_eq(ri->request_method, "GET");
+ ck_assert_str_eq(ri->http_version, "1.1");
+ ck_assert_str_eq(ri->remote_addr, "127.0.0.1");
+ ck_assert_ptr_eq(ri->query_string, NULL);
+ ck_assert_ptr_ne(ri->local_uri, NULL);
+
+ mg_printf(conn,
+ "HTTP/1.1 200 OK\r\n"
+ "Content-Length: %lu\r\n"
+ "Connection: close\r\n\r\n",
+ len);
+
+ blocklen = strlen(block);
+
+ for (i = 0; i < len; i += blocklen) {
+ mg_write(conn, block, blocklen);
+ }
+
+ mark_point();
+
+ return 200;
+}
+
+
+START_TEST(test_large_file)
+{
+ /* Server var */
+ struct mg_context *ctx;
+ struct mg_callbacks callbacks;
+ const char *OPTIONS[32];
+ int opt_cnt = 0;
+#if !defined(NO_SSL)
+ const char *ssl_cert = locate_ssl_cert();
+#endif
+ char errmsg[256] = {0};
+
+ /* Client var */
+ struct mg_connection *client;
+ char client_err_buf[256];
+ char client_data_buf[256];
+ const struct mg_request_info *client_ri;
+ int64_t data_read;
+ int r;
+ int retry, retry_ok_cnt, retry_fail_cnt;
+
+ mark_point();
+
+/* Set options and start server */
+#if !defined(NO_FILES)
+ OPTIONS[opt_cnt++] = "document_root";
+ OPTIONS[opt_cnt++] = ".";
+#endif
+#if defined(NO_SSL)
+ OPTIONS[opt_cnt++] = "listening_ports";
+ OPTIONS[opt_cnt++] = "8080";
+#else
+ OPTIONS[opt_cnt++] = "listening_ports";
+ OPTIONS[opt_cnt++] = "8443s";
+ OPTIONS[opt_cnt++] = "ssl_certificate";
+ OPTIONS[opt_cnt++] = ssl_cert;
+#ifdef __MACH__
+ /* The Apple builds on Travis CI seem to have problems with TLS1.x
+ * Allow SSLv3 and TLS */
+ OPTIONS[opt_cnt++] = "ssl_protocol_version";
+ OPTIONS[opt_cnt++] = "2";
+#else
+ /* The Linux builds on Travis CI work fine with TLS1.2 */
+ OPTIONS[opt_cnt++] = "ssl_protocol_version";
+ OPTIONS[opt_cnt++] = "4";
+#endif
+ ck_assert(ssl_cert != NULL);
+#endif
+ OPTIONS[opt_cnt] = NULL;
+
+
+ memset(&callbacks, 0, sizeof(callbacks));
+ callbacks.begin_request = test_large_file_begin_request;
+ callbacks.log_message = log_msg_func;
+
+ ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS);
+ ck_assert_str_eq(errmsg, "");
+ ck_assert(ctx != NULL);
+
+ /* Try downloading several times */
+ retry_ok_cnt = 0;
+ retry_fail_cnt = 0;
+ for (retry = 0; retry < 3; retry++) {
+ int fail = 0;
+ /* connect client */
+ memset(client_err_buf, 0, sizeof(client_err_buf));
+ memset(client_data_buf, 0, sizeof(client_data_buf));
+
+ client =
+ mg_download("127.0.0.1",
+#if defined(NO_SSL)
+ 8080,
+ 0,
+#else
+ 8443,
+ 1,
+#endif
+ client_err_buf,
+ sizeof(client_err_buf),
+ "GET /large.file HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n");
+
+ ck_assert(client != NULL);
+ ck_assert_str_eq(client_err_buf, "");
+
+ client_ri = mg_get_request_info(client);
+
+ ck_assert(client_ri != NULL);
+ ck_assert_str_eq(client_ri->local_uri, "200");
+
+ ck_assert_int_eq(client_ri->content_length, LARGE_FILE_SIZE);
+
+ data_read = 0;
+ while (data_read < client_ri->content_length) {
+ r = mg_read(client, client_data_buf, sizeof(client_data_buf));
+ if (r < 0) {
+ fail = 1;
+ break;
+ };
+ data_read += r;
+ }
+
+ /* Nothing left to read */
+ r = mg_read(client, client_data_buf, sizeof(client_data_buf));
+ if (fail) {
+ ck_assert_int_eq(r, -1);
+ retry_fail_cnt++;
+ } else {
+ ck_assert_int_eq(r, 0);
+ retry_ok_cnt++;
+ }
+
+ /* Close the client connection */
+ mg_close_connection(client);
+ }
+
+#if defined(_WIN32)
+// TODO: Check this problem on AppVeyor
+// ck_assert_int_le(retry_fail_cnt, 2);
+// ck_assert_int_ge(retry_ok_cnt, 1);
+#else
+ ck_assert_int_eq(retry_fail_cnt, 0);
+ ck_assert_int_eq(retry_ok_cnt, 3);
+#endif
+
+ /* Stop the server */
+ test_mg_stop(ctx);
+
+ mark_point();
+}
+END_TEST
+
+
+static int test_mg_store_body_con_len = 20000;
+
+
+static int
+test_mg_store_body_put_delete_handler(struct mg_connection *conn, void *ignored)
+{
+ char path[4096] = {0};
+ const struct mg_request_info *info = mg_get_request_info(conn);
+ int64_t rc;
+
+ (void)ignored;
+
+ mark_point();
+
+ sprintf(path, "./%s", info->local_uri);
+ rc = mg_store_body(conn, path);
+
+ ck_assert_int_eq(test_mg_store_body_con_len, rc);
+
+ if (rc < 0) {
+ mg_printf(conn,
+ "HTTP/1.1 500 Internal Server Error\r\n"
+ "Content-Type:text/plain;charset=UTF-8\r\n"
+ "Connection:close\r\n\r\n"
+ "%s (ret: %ld)\n",
+ path,
+ (long)rc);
+ mg_close_connection(conn);
+
+ /* Debug output for tests */
+ printf("mg_store_body(%s) failed (ret: %ld)\n", path, (long)rc);
+
+ return 500;
+ }
+
+ mg_printf(conn,
+ "HTTP/1.1 200 OK\r\n"
+ "Content-Type:text/plain;charset=UTF-8\r\n"
+ "Connection:close\r\n\r\n"
+ "%s OK (%ld bytes saved)\n",
+ path,
+ (long)rc);
+ mg_close_connection(conn);
+
+ /* Debug output for tests */
+ printf("mg_store_body(%s) OK (%ld bytes)\n", path, (long)rc);
+
+ mark_point();
+
+ return 200;
+}
+
+
+static int
+test_mg_store_body_begin_request_callback(struct mg_connection *conn)
+{
+ const struct mg_request_info *info = mg_get_request_info(conn);
+
+ mark_point();
+
+ /* Debug output for tests */
+ printf("test_mg_store_body_begin_request_callback called (%s)\n",
+ info->request_method);
+
+ if ((strcmp(info->request_method, "PUT") == 0)
+ || (strcmp(info->request_method, "DELETE") == 0)) {
+ return test_mg_store_body_put_delete_handler(conn, NULL);
+ }
+
+ mark_point();
+
+ return 0;
+}
+
+
+START_TEST(test_mg_store_body)
+{
+ /* Client data */
+ char client_err_buf[256];
+ char client_data_buf[1024];
+ struct mg_connection *client;
+ const struct mg_request_info *client_ri;
+ int r;
+ char check_data[256];
+ char *check_ptr;
+ char errmsg[256] = {0};
+
+ /* Server context handle */
+ struct mg_context *ctx;
+ struct mg_callbacks callbacks;
+ const char *options[] = {
+#if !defined(NO_FILES)
+ "document_root",
+ ".",
+#endif
+#if !defined(NO_CACHING)
+ "static_file_max_age",
+ "0",
+#endif
+ "listening_ports",
+ "127.0.0.1:8082",
+ "num_threads",
+ "1",
+ NULL
+ };
+
+ mark_point();
+
+ memset(&callbacks, 0, sizeof(callbacks));
+ callbacks.begin_request = test_mg_store_body_begin_request_callback;
+ callbacks.log_message = log_msg_func;
+
+ /* Initialize the library */
+ mg_init_library(0);
+
+ /* Start the server */
+ ctx = mg_start(&callbacks, (void *)errmsg, options);
+ ck_assert_str_eq(errmsg, "");
+ ck_assert(ctx != NULL);
+
+ /* Run the server for 15 seconds */
+ test_sleep(15);
+
+ /* Call a test client */
+ client = mg_connect_client(
+ "127.0.0.1", 8082, 0, client_err_buf, sizeof(client_err_buf));
+
+ ck_assert_str_eq(client_err_buf, "");
+ ck_assert(client != NULL);
+
+ mg_printf(client,
+ "PUT /%s HTTP/1.0\r\nContent-Length: %i\r\n\r\n",
+ "test_file_name.txt",
+ test_mg_store_body_con_len);
+
+ r = 0;
+ while (r < test_mg_store_body_con_len) {
+ int l = mg_write(client, "1234567890", 10);
+ ck_assert_int_eq(l, 10);
+ r += 10;
+ }
+
+ r = mg_get_response(client, client_err_buf, sizeof(client_err_buf), 10000);
+ ck_assert_int_ge(r, 0);
+ ck_assert_str_eq(client_err_buf, "");
+
+ client_ri = mg_get_request_info(client);
+ ck_assert(client_ri != NULL);
+
+ /* Response must be 200 OK */
+ ck_assert_ptr_ne(client_ri->request_uri, NULL);
+ ck_assert_str_eq(client_ri->request_uri, "200");
+
+ /* Read PUT response */
+ r = mg_read(client, client_data_buf, sizeof(client_data_buf) - 1);
+ ck_assert_int_gt(r, 0);
+ client_data_buf[r] = 0;
+
+ sprintf(check_data, "(%i bytes saved)", test_mg_store_body_con_len);
+ check_ptr = strstr(client_data_buf, check_data);
+ ck_assert_ptr_ne(check_ptr, NULL);
+
+ mg_close_connection(client);
+
+ /* Run the server for 5 seconds */
+ test_sleep(5);
+
+ /* Stop the server */
+ test_mg_stop(ctx);
+
+ /* Un-initialize the library */
+ mg_exit_library();
+
+ mark_point();
+}
+END_TEST
+
+
+#if defined(MG_USE_OPEN_FILE) && !defined(NO_FILES)
+
+#define FILE_IN_MEM_SIZE (1024 * 100)
+static char *file_in_mem_data;
+
+static const char *
+test_file_in_memory_open_file(const struct mg_connection *conn,
+ const char *file_path,
+ size_t *file_size)
+{
+ (void)conn;
+
+ if (strcmp(file_path, "./file_in_mem") == 0) {
+ /* File is in memory */
+ *file_size = FILE_IN_MEM_SIZE;
+ return file_in_mem_data;
+ } else {
+ /* File is not in memory */
+ return NULL;
+ }
+}
+
+
+START_TEST(test_file_in_memory)
+{
+ /* Server var */
+ struct mg_context *ctx;
+ struct mg_callbacks callbacks;
+ const char *OPTIONS[32];
+ int opt_cnt = 0;
+#if !defined(NO_SSL)
+ const char *ssl_cert = locate_ssl_cert();
+#endif
+
+ /* Client var */
+ struct mg_connection *client;
+ char client_err_buf[256];
+ char client_data_buf[256];
+ const struct mg_request_info *client_ri;
+ int64_t data_read;
+ int r, i;
+
+ /* Prepare test data */
+ file_in_mem_data = (char *)malloc(FILE_IN_MEM_SIZE);
+ ck_assert_ptr_ne(file_in_mem_data, NULL);
+ for (r = 0; r < FILE_IN_MEM_SIZE; r++) {
+ file_in_mem_data[r] = (char)(r);
+ }
+
+ /* Set options and start server */
+ OPTIONS[opt_cnt++] = "document_root";
+ OPTIONS[opt_cnt++] = ".";
+#if defined(NO_SSL)
+ OPTIONS[opt_cnt++] = "listening_ports";
+ OPTIONS[opt_cnt++] = "8080";
+#else
+ OPTIONS[opt_cnt++] = "listening_ports";
+ OPTIONS[opt_cnt++] = "8443s";
+ OPTIONS[opt_cnt++] = "ssl_certificate";
+ OPTIONS[opt_cnt++] = ssl_cert;
+ ck_assert(ssl_cert != NULL);
+#endif
+ OPTIONS[opt_cnt] = NULL;
+
+
+ memset(&callbacks, 0, sizeof(callbacks));
+ callbacks.open_file = test_file_in_memory_open_file;
+
+ ctx = test_mg_start(&callbacks, 0, OPTIONS);
+ ck_assert(ctx != NULL);
+
+ /* connect client */
+ memset(client_err_buf, 0, sizeof(client_err_buf));
+ memset(client_data_buf, 0, sizeof(client_data_buf));
+
+ client =
+ mg_download("127.0.0.1",
+#if defined(NO_SSL)
+ 8080,
+ 0,
+#else
+ 8443,
+ 1,
+#endif
+ client_err_buf,
+ sizeof(client_err_buf),
+ "GET /file_in_mem HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n");
+
+ ck_assert(client != NULL);
+ ck_assert_str_eq(client_err_buf, "");
+
+ client_ri = mg_get_request_info(client);
+
+ ck_assert(client_ri != NULL);
+ ck_assert_str_eq(client_ri->local_uri, "200");
+
+ ck_assert_int_eq(client_ri->content_length, FILE_IN_MEM_SIZE);
+
+ data_read = 0;
+ while (data_read < client_ri->content_length) {
+ r = mg_read(client, client_data_buf, sizeof(client_data_buf));
+ if (r > 0) {
+ for (i = 0; i < r; i++) {
+ ck_assert_int_eq((int)client_data_buf[i],
+ (int)file_in_mem_data[data_read + i]);
+ }
+ data_read += r;
+ }
+ }
+
+ /* Nothing left to read */
+ r = mg_read(client, client_data_buf, sizeof(client_data_buf));
+ ck_assert_int_eq(r, 0);
+
+ /* Close the client connection */
+ mg_close_connection(client);
+
+ /* Stop the server */
+ test_mg_stop(ctx);
+
+ /* Free test data */
+ free(file_in_mem_data);
+ file_in_mem_data = NULL;
+}
+END_TEST
+
+#else /* defined(MG_USE_OPEN_FILE) */
+
+START_TEST(test_file_in_memory)
+{
+ mark_point();
+}
+END_TEST
+
+#endif
+
+
+static void
+minimal_http_https_client_impl(const char *server,
+ uint16_t port,
+ int use_ssl,
+ const char *uri)
+{
+ /* Client var */
+ struct mg_connection *client;
+ char client_err_buf[256];
+ char client_data_buf[256];
+ const struct mg_request_info *client_ri;
+ int64_t data_read;
+ int r;
+
+ mark_point();
+
+ client = mg_connect_client(
+ server, port, use_ssl, client_err_buf, sizeof(client_err_buf));
+
+ ck_assert_str_eq(client_err_buf, "");
+ ck_assert(client != NULL);
+
+ mg_printf(client, "GET /%s HTTP/1.0\r\n\r\n", uri);
+
+ r = mg_get_response(client, client_err_buf, sizeof(client_err_buf), 10000);
+ ck_assert_int_ge(r, 0);
+ ck_assert_str_eq(client_err_buf, "");
+
+ client_ri = mg_get_request_info(client);
+ ck_assert(client_ri != NULL);
+
+ /* e.g.: ck_assert_str_eq(client_ri->request_uri, "200"); */
+ ck_assert_ptr_ne(client_ri->request_uri, NULL);
+ r = (int)strlen(client_ri->request_uri);
+ ck_assert_int_eq(r, 3);
+
+ data_read = 0;
+ while (data_read < client_ri->content_length) {
+ r = mg_read(client, client_data_buf, sizeof(client_data_buf));
+ if (r > 0) {
+ data_read += r;
+ }
+ }
+
+ /* Nothing left to read */
+ r = mg_read(client, client_data_buf, sizeof(client_data_buf));
+ ck_assert_int_eq(r, 0);
+
+ mark_point();
+
+ mg_close_connection(client);
+
+ mark_point();
+}
+
+
+static void
+minimal_http_client_impl(const char *server, uint16_t port, const char *uri)
+{
+ minimal_http_https_client_impl(server, port, 0, uri);
+}
+
+
+#if !defined(NO_SSL)
+static void
+minimal_https_client_impl(const char *server, uint16_t port, const char *uri)
+{
+ minimal_http_https_client_impl(server, port, 1, uri);
+}
+#endif
+
+
+START_TEST(test_minimal_client)
+{
+ mark_point();
+
+ /* Initialize the library */
+ mg_init_library(0);
+
+ mark_point();
+
+ /* Call a test client */
+ minimal_http_client_impl("192.30.253.113" /* www.github.com */,
+ 80,
+ "civetweb/civetweb/");
+
+ mark_point();
+
+ /* Un-initialize the library */
+ mg_exit_library();
+
+ mark_point();
+}
+END_TEST
+
+
+static int
+minimal_test_request_handler(struct mg_connection *conn, void *cbdata)
+{
+ const char *msg = (const char *)cbdata;
+ unsigned long len = (unsigned long)strlen(msg);
+
+ mark_point();
+
+ mg_printf(conn,
+ "HTTP/1.1 200 OK\r\n"
+ "Content-Length: %lu\r\n"
+ "Content-Type: text/plain\r\n"
+ "Connection: close\r\n\r\n",
+ len);
+
+ mg_write(conn, msg, len);
+
+ mark_point();
+
+ return 200;
+}
+
+
+START_TEST(test_minimal_http_server_callback)
+{
+ /* This test should ensure the minimum server example in
+ * docs/Embedding.md is still running. */
+
+ /* Server context handle */
+ struct mg_context *ctx;
+
+ mark_point();
+
+ /* Initialize the library */
+ mg_init_library(0);
+
+ /* Start the server */
+ ctx = test_mg_start(NULL, 0, NULL);
+ ck_assert(ctx != NULL);
+
+ /* Add some handler */
+ mg_set_request_handler(ctx,
+ "/hello",
+ minimal_test_request_handler,
+ (void *)"Hello world");
+ mg_set_request_handler(ctx,
+ "/8",
+ minimal_test_request_handler,
+ (void *)"Number eight");
+
+ /* Run the server for 15 seconds */
+ test_sleep(10);
+
+ /* Call a test client */
+ minimal_http_client_impl("127.0.0.1", 8080, "/hello");
+
+ /* Run the server for 15 seconds */
+ test_sleep(5);
+
+
+ /* Stop the server */
+ test_mg_stop(ctx);
+
+ /* Un-initialize the library */
+ mg_exit_library();
+
+ mark_point();
+}
+END_TEST
+
+
+START_TEST(test_minimal_https_server_callback)
+{
+#if !defined(NO_SSL)
+ /* This test should show a HTTPS server with enhanced
+ * security settings.
+ *
+ * Articles:
+ * https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
+ *
+ * Scanners:
+ * https://securityheaders.io/
+ * https://www.htbridge.com/ssl/
+ * https://www.htbridge.com/websec/
+ * https://www.ssllabs.com/ssltest/
+ * https://www.qualys.com/forms/freescan/
+ */
+
+ /* Server context handle */
+ struct mg_context *ctx;
+
+ /* Server start parameters for HTTPS */
+ const char *OPTIONS[32];
+ int opt_idx = 0;
+
+ /* HTTPS port - required */
+ OPTIONS[opt_idx++] = "listening_ports";
+ OPTIONS[opt_idx++] = "8443s";
+
+ /* path to certificate file - required */
+ OPTIONS[opt_idx++] = "ssl_certificate";
+ OPTIONS[opt_idx++] = locate_ssl_cert();
+
+#if defined(LOCAL_TEST) || defined(_WIN32)
+ /* Do not set this on Travis CI, since the build containers
+ * contain older SSL libraries */
+
+ /* set minimum SSL version to TLS 1.2 - recommended */
+ OPTIONS[opt_idx++] = "ssl_protocol_version";
+ OPTIONS[opt_idx++] = "4";
+
+ /* set some modern ciphers - recommended */
+ OPTIONS[opt_idx++] = "ssl_cipher_list";
+ OPTIONS[opt_idx++] = "ECDH+AESGCM+AES256:!aNULL:!MD5:!DSS";
+#endif
+
+ /* set "HTTPS only" header - recommended */
+ OPTIONS[opt_idx++] = "strict_transport_security_max_age";
+ OPTIONS[opt_idx++] = "31622400";
+
+ /* end of options - required */
+ OPTIONS[opt_idx] = NULL;
+
+ mark_point();
+
+ /* Initialize the library */
+ mg_init_library(0);
+
+
+ /* Start the server */
+ ctx = test_mg_start(NULL, 0, OPTIONS);
+ ck_assert(ctx != NULL);
+
+ /* Add some handler */
+ mg_set_request_handler(ctx,
+ "/hello",
+ minimal_test_request_handler,
+ (void *)"Hello world");
+ mg_set_request_handler(ctx,
+ "/8",
+ minimal_test_request_handler,
+ (void *)"Number eight");
+
+ /* Run the server for 15 seconds */
+ test_sleep(10);
+
+ /* Call a test client */
+ minimal_https_client_impl("127.0.0.1", 8443, "/hello");
+
+ /* Run the server for 15 seconds */
+ test_sleep(5);
+
+
+ /* Stop the server */
+ test_mg_stop(ctx);
+
+ /* Un-initialize the library */
+ mg_exit_library();
+#endif
+ mark_point();
+}
+END_TEST
+
+
+#if !defined(REPLACE_CHECK_FOR_LOCAL_DEBUGGING)
+Suite *
+make_public_server_suite(void)
+{
+ Suite *const suite = suite_create("PublicServer");
+
+ TCase *const tcase_checktestenv = tcase_create("Check test environment");
+ TCase *const tcase_initlib = tcase_create("Init library");
+ TCase *const tcase_startthreads = tcase_create("Start threads");
+ TCase *const tcase_minimal_svr = tcase_create("Minimal Server");
+ TCase *const tcase_minimal_cli = tcase_create("Minimal Client");
+ TCase *const tcase_startstophttp = tcase_create("Start Stop HTTP Server");
+ TCase *const tcase_startstophttp_ipv6 =
+ tcase_create("Start Stop HTTP Server IPv6");
+ TCase *const tcase_startstophttps = tcase_create("Start Stop HTTPS Server");
+ TCase *const tcase_serverandclienttls = tcase_create("TLS Server Client");
+ TCase *const tcase_serverrequests = tcase_create("Server Requests");
+ TCase *const tcase_storebody = tcase_create("Store Body");
+ TCase *const tcase_handle_form = tcase_create("Handle Form");
+ TCase *const tcase_http_auth = tcase_create("HTTP Authentication");
+ TCase *const tcase_keep_alive = tcase_create("HTTP Keep Alive");
+ TCase *const tcase_error_handling = tcase_create("Error handling");
+ TCase *const tcase_throttle = tcase_create("Limit speed");
+ TCase *const tcase_large_file = tcase_create("Large file");
+ TCase *const tcase_file_in_mem = tcase_create("File in memory");
+
+
+ tcase_add_test(tcase_checktestenv, test_the_test_environment);
+ tcase_set_timeout(tcase_checktestenv, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_checktestenv);
+
+ tcase_add_test(tcase_initlib, test_init_library);
+ tcase_set_timeout(tcase_initlib, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_initlib);
+
+ tcase_add_test(tcase_startthreads, test_threading);
+ tcase_set_timeout(tcase_startthreads, civetweb_min_test_timeout);
+ suite_add_tcase(suite, tcase_startthreads);
+
+ tcase_add_test(tcase_minimal_svr, test_minimal_http_server_callback);
+ tcase_add_test(tcase_minimal_svr, test_minimal_https_server_callback);
+ tcase_set_timeout(tcase_minimal_svr, civetweb_min_server_test_timeout);
+ suite_add_tcase(suite, tcase_minimal_svr);
+
+ tcase_add_test(tcase_minimal_cli, test_minimal_client);
+ tcase_set_timeout(tcase_minimal_cli, civetweb_min_server_test_timeout);
+ suite_add_tcase(suite, tcase_minimal_cli);
+
+ tcase_add_test(tcase_startstophttp, test_mg_start_stop_http_server);
+ tcase_set_timeout(tcase_startstophttp, civetweb_min_server_test_timeout);
+ suite_add_tcase(suite, tcase_startstophttp);
+
+ tcase_add_test(tcase_startstophttp_ipv6,
+ test_mg_start_stop_http_server_ipv6);
+ tcase_set_timeout(tcase_startstophttp_ipv6,
+ civetweb_min_server_test_timeout);
+ suite_add_tcase(suite, tcase_startstophttp_ipv6);
+
+ tcase_add_test(tcase_startstophttps, test_mg_start_stop_https_server);
+ tcase_set_timeout(tcase_startstophttps, civetweb_min_server_test_timeout);
+ suite_add_tcase(suite, tcase_startstophttps);
+
+ tcase_add_test(tcase_serverandclienttls, test_mg_server_and_client_tls);
+ tcase_set_timeout(tcase_serverandclienttls,
+ civetweb_min_server_test_timeout);
+ suite_add_tcase(suite, tcase_serverandclienttls);
+
+ tcase_add_test(tcase_serverrequests, test_request_handlers);
+ tcase_set_timeout(tcase_serverrequests, civetweb_mid_server_test_timeout);
+ suite_add_tcase(suite, tcase_serverrequests);
+
+ tcase_add_test(tcase_storebody, test_mg_store_body);
+ tcase_set_timeout(tcase_storebody, civetweb_mid_server_test_timeout);
+ suite_add_tcase(suite, tcase_storebody);
+
+ tcase_add_test(tcase_handle_form, test_handle_form);
+ tcase_set_timeout(tcase_handle_form, civetweb_mid_server_test_timeout);
+ suite_add_tcase(suite, tcase_handle_form);
+
+ tcase_add_test(tcase_http_auth, test_http_auth);
+ tcase_set_timeout(tcase_http_auth, civetweb_min_server_test_timeout);
+ suite_add_tcase(suite, tcase_http_auth);
+
+ tcase_add_test(tcase_keep_alive, test_keep_alive);
+ tcase_set_timeout(tcase_keep_alive, civetweb_mid_server_test_timeout);
+ suite_add_tcase(suite, tcase_keep_alive);
+
+ tcase_add_test(tcase_error_handling, test_error_handling);
+ tcase_add_test(tcase_error_handling, test_error_log_file);
+ tcase_set_timeout(tcase_error_handling, civetweb_mid_server_test_timeout);
+ suite_add_tcase(suite, tcase_error_handling);
+
+ tcase_add_test(tcase_throttle, test_throttle);
+ tcase_set_timeout(tcase_throttle, civetweb_mid_server_test_timeout);
+ suite_add_tcase(suite, tcase_throttle);
+
+ tcase_add_test(tcase_large_file, test_large_file);
+ tcase_set_timeout(tcase_large_file, civetweb_mid_server_test_timeout);
+ suite_add_tcase(suite, tcase_large_file);
+
+ tcase_add_test(tcase_file_in_mem, test_file_in_memory);
+ tcase_set_timeout(tcase_file_in_mem, civetweb_mid_server_test_timeout);
+ suite_add_tcase(suite, tcase_file_in_mem);
+
+ return suite;
+}
+#endif
+
+
+#ifdef REPLACE_CHECK_FOR_LOCAL_DEBUGGING
+/* Used to debug test cases without using the check framework */
+/* Build command for Linux:
+gcc test/public_server.c src/civetweb.c -I include/ -I test/ -l pthread -l dl -D
+LOCAL_TEST -D REPLACE_CHECK_FOR_LOCAL_DEBUGGING -D MAIN_PUBLIC_SERVER=main
+*/
+
+static int chk_ok = 0;
+static int chk_failed = 0;
+
+
+void
+MAIN_PUBLIC_SERVER(void)
+{
+ unsigned f_avail = mg_check_feature(0xFF);
+ unsigned f_ret = mg_init_library(f_avail);
+ ck_assert_uint_eq(f_ret, f_avail);
+
+ test_the_test_environment(0);
+ test_threading(0);
+
+ test_minimal_client(0);
+
+ test_mg_start_stop_http_server(0);
+ test_mg_start_stop_https_server(0);
+ test_request_handlers(0);
+ test_mg_store_body(0);
+ test_mg_server_and_client_tls(0);
+ test_handle_form(0);
+ test_http_auth(0);
+ test_keep_alive(0);
+ test_error_handling(0);
+ test_error_log_file(0);
+ test_throttle(0);
+ test_large_file(0);
+ test_file_in_memory(0);
+
+ mg_exit_library();
+
+ printf("\nok: %i\nfailed: %i\n\n", chk_ok, chk_failed);
+}
+
+void
+_ck_assert_failed(const char *file, int line, const char *expr, ...)
+{
+ va_list va;
+ va_start(va, expr);
+ fprintf(stderr, "Error: %s, line %i\n", file, line); /* breakpoint here ! */
+ vfprintf(stderr, expr, va);
+ fprintf(stderr, "\n\n");
+ va_end(va);
+ chk_failed++;
+}
+
+void
+_ck_assert_msg(int cond, const char *file, int line, const char *expr, ...)
+{
+ va_list va;
+
+ if (cond) {
+ chk_ok++;
+ return;
+ }
+
+ va_start(va, expr);
+ fprintf(stderr, "Error: %s, line %i\n", file, line); /* breakpoint here ! */
+ vfprintf(stderr, expr, va);
+ fprintf(stderr, "\n\n");
+ va_end(va);
+ chk_failed++;
+}
+
+void
+_mark_point(const char *file, int line)
+{
+ chk_ok++;
+}
+
+void
+tcase_fn_start(const char *fname, const char *file, int line)
+{
+}
+void suite_add_tcase(Suite *s, TCase *tc){};
+void _tcase_add_test(TCase *tc,
+ TFun tf,
+ const char *fname,
+ int _signal,
+ int allowed_exit_value,
+ int start,
+ int end){};
+TCase *
+tcase_create(const char *name)
+{
+ return NULL;
+};
+Suite *
+suite_create(const char *name)
+{
+ return NULL;
+};
+void tcase_set_timeout(TCase *tc, double timeout){};
+
+#endif
diff --git a/src/civetweb/test/public_server.h b/src/civetweb/test/public_server.h
new file mode 100644
index 00000000..c3e0d8e8
--- /dev/null
+++ b/src/civetweb/test/public_server.h
@@ -0,0 +1,28 @@
+/* Copyright (c) 2015-2017 the Civetweb developers
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+#ifndef TEST_PUBLIC_SERVER_H_
+#define TEST_PUBLIC_SERVER_H_
+
+#include "civetweb_check.h"
+
+Suite *make_public_server_suite(void);
+
+#endif /* TEST_PUBLIC_H_ */
diff --git a/src/civetweb/test/require_test.lua b/src/civetweb/test/require_test.lua
new file mode 100644
index 00000000..6173dfa0
--- /dev/null
+++ b/src/civetweb/test/require_test.lua
@@ -0,0 +1,2 @@
+require 'html_esc'
+require 'HugeText'
diff --git a/src/civetweb/test/resource_script_demo.lua b/src/civetweb/test/resource_script_demo.lua
new file mode 100644
index 00000000..e21e4654
--- /dev/null
+++ b/src/civetweb/test/resource_script_demo.lua
@@ -0,0 +1,124 @@
+-- This is a Lua script that handles sub-resources, e.g. resource_script_demo.lua/path/file.ext
+
+scriptUri = "resource_script_demo.lua"
+envVar = "resource_script_demo_storage"
+
+resourcedir = os.getenv(envVar) or "R:\\RESOURCEDIR"
+method = mg.request_info.request_method:upper()
+
+if resourcedir then
+ attr = lfs.attributes(resourcedir)
+end
+
+if (not mg.request_info.uri:find(scriptUri)) or (not resourcedir) or (not attr) or (attr.mode~="directory") then
+ mg.write("HTTP/1.0 500 OK\r\n")
+ mg.write("Connection: close\r\n")
+ mg.write("Content-Type: text/html; charset=utf-8\r\n")
+ mg.write("\r\n")
+ mg.write("Civetweb Lua script resource handling test\r\n")
+ mg.write("\r\nServer error. \r\n")
+ mg.write("The server admin must make sure this script is available as URI " .. scriptUri .. " \r\n")
+ mg.write("The server admin must set the environment variable " .. envVar .. " to a directory. \r\n")
+ mg.write("\r\n\r\n")
+ return
+end
+subresource = mg.request_info.uri:match(scriptUri .. "/(.*)")
+
+if not subresource then
+ if method=="GET" then
+ mg.write("HTTP/1.0 200 OK\r\n")
+ mg.write("Connection: close\r\n")
+ mg.write("Content-Type: text/html; charset=utf-8\r\n")
+ mg.write("\r\n")
+ mg.write("Civetweb Lua script resource handling test\r\n")
+ mg.write("No resource specified. resourcedir is " .. resourcedir .. "\r\n")
+ else
+ mg.write("HTTP/1.0 405 Method Not Allowed\r\n")
+ mg.write("Connection: close\r\n")
+ mg.write("Content-Type: text/html; charset=utf-8\r\n")
+ mg.write("\r\n")
+ mg.write("Civetweb Lua script resource handling test\r\n")
+ mg.write("Method not allowed.\r\n")
+ end
+ return
+end
+
+
+if method=="GET" then
+ file = resourcedir .. "/" .. subresource
+ if lfs.attributes(file) then
+ mg.send_file(file)
+ else
+ mime = mg.get_mime_type(file)
+ mg.write("HTTP/1.0 404 Not Found\r\n")
+ mg.write("Connection: close\r\n")
+ mg.write("Content-Type: text/html; charset=utf-8\r\n")
+ mg.write("\r\n")
+ mg.write("Civetweb Lua script resource handling test\r\n")
+ mg.write("Resource of type \"" .. mime .. "\" not found.\r\n")
+ end
+ return
+end
+
+if method=="PUT" then
+ file = resourcedir .. "/" .. subresource
+ mime = mg.get_mime_type(file)
+ if lfs.attributes(file) then
+ mg.write("HTTP/1.0 405 Method Not Allowed\r\n")
+ mg.write("Connection: close\r\n")
+ mg.write("Content-Type: text/html; charset=utf-8\r\n")
+ mg.write("\r\n")
+ mg.write("Civetweb Lua script resource handling test\r\n")
+ mg.write("Resource of type \"" .. mime .. "\" already exists.\r\n")
+ else
+ local f = io.open(file, "w")
+
+ local data = {}
+ repeat
+ local l = mg.read();
+ data[#data+1] = l;
+ until ((l == "") or (l == nil));
+
+ f:write(table.concat(data, ""))
+ f:close()
+ mg.write("HTTP/1.0 200 OK\r\n")
+ mg.write("Connection: close\r\n")
+ mg.write("Content-Type: text/html; charset=utf-8\r\n")
+ mg.write("\r\n")
+ mg.write("Civetweb Lua script resource handling test\r\n")
+ mg.write("Resource of type \"" .. mime .. "\" created.\r\n")
+ end
+ return
+end
+
+if method=="DELETE" then
+ file = resourcedir .. "/" .. subresource
+ mime = mg.get_mime_type(file)
+ if lfs.attributes(file) then
+ os.remove(file)
+ mg.write("HTTP/1.0 200 OK\r\n")
+ mg.write("Connection: close\r\n")
+ mg.write("Content-Type: text/html; charset=utf-8\r\n")
+ mg.write("\r\n")
+ mg.write("Civetweb Lua script resource handling test\r\n")
+ mg.write("Resource of type \"" .. mime .. "\" deleted.\r\n")
+ else
+ mime = mg.get_mime_type(file)
+ mg.write("HTTP/1.0 404 Not Found\r\n")
+ mg.write("Connection: close\r\n")
+ mg.write("Content-Type: text/html; charset=utf-8\r\n")
+ mg.write("\r\n")
+ mg.write("Civetweb Lua script resource handling test\r\n")
+ mg.write("Resource of type \"" .. mime .. "\" not found.\r\n")
+ end
+ return
+end
+
+-- Any other method
+mg.write("HTTP/1.0 405 Method Not Allowed\r\n")
+mg.write("Connection: close\r\n")
+mg.write("Content-Type: text/html; charset=utf-8\r\n")
+mg.write("\r\n")
+mg.write("Civetweb Lua script resource handling test\r\n")
+mg.write("Method not allowed.\r\n")
+
diff --git a/src/civetweb/test/shared.c b/src/civetweb/test/shared.c
new file mode 100644
index 00000000..a35a8637
--- /dev/null
+++ b/src/civetweb/test/shared.c
@@ -0,0 +1,48 @@
+/* Copyright (c) 2015-2017 the Civetweb developers
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#ifdef _MSC_VER
+#if !defined(_CRT_SECURE_NO_WARNINGS)
+#define _CRT_SECURE_NO_WARNINGS
+#endif
+#if !defined(_CRT_SECURE_NO_DEPRECATE)
+#define _CRT_SECURE_NO_DEPRECATE
+#endif
+#endif
+
+#include "shared.h"
+#include
+
+static char s_test_directory[1024] = {'\0'};
+
+const char *
+get_test_directory(void)
+{
+ return s_test_directory;
+}
+
+void
+set_test_directory(const char *const path)
+{
+ strncpy(s_test_directory,
+ path,
+ sizeof(s_test_directory) / sizeof(s_test_directory[0]));
+}
diff --git a/src/civetweb/test/shared.h b/src/civetweb/test/shared.h
new file mode 100644
index 00000000..937fcff6
--- /dev/null
+++ b/src/civetweb/test/shared.h
@@ -0,0 +1,27 @@
+/* Copyright (c) 2015-2017 the Civetweb developers
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+#ifndef TEST_SHARED_H_
+#define TEST_SHARED_H_
+
+const char *get_test_directory(void);
+void set_test_directory(const char *const path);
+
+#endif /* TEST_SHARED_H_ */
diff --git a/src/civetweb/test/ssi_test.shtml b/src/civetweb/test/ssi_test.shtml
new file mode 100644
index 00000000..eb03d171
--- /dev/null
+++ b/src/civetweb/test/ssi_test.shtml
@@ -0,0 +1,37 @@
+
+
+
+
+ The HTML5 Herald
+
+
+
+
+
+
CivetWeb Server Side Include (SSI) Test Page
+
Note: Some of the tests below will only work on Windows, others only on Linux, and some probably not on all Linux distributions and all Windows versions.
+
+
Execute: "cd"
+
+
Execute: "pwd"
+
+
+
File relative to current document: "hello.txt"
+
+
Short form: "hello.txt"
+
+
+
File relative to document root: "hello.txt"
+
+
+
File with absolute path: "C:\Windows\system.ini"
+
+
File with absolute path: "/etc/issue"
+
+
+
Nested file relative to current documentt: "hello.shtml"
+
+
+
+
+
diff --git a/src/civetweb/test/syntax_error.ssjs b/src/civetweb/test/syntax_error.ssjs
new file mode 100644
index 00000000..d8619edd
--- /dev/null
+++ b/src/civetweb/test/syntax_error.ssjs
@@ -0,0 +1,7 @@
+
+conn.write('HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n');
+
+conn.write('Syntax error:');
+
+asdf ghjk qwert 123456789 +-*/
+.!,;
diff --git a/src/civetweb/test/test.ico b/src/civetweb/test/test.ico
new file mode 100644
index 00000000..70ab89d0
Binary files /dev/null and b/src/civetweb/test/test.ico differ
diff --git a/src/civetweb/test/test.pl b/src/civetweb/test/test.pl
new file mode 100755
index 00000000..e5034890
--- /dev/null
+++ b/src/civetweb/test/test.pl
@@ -0,0 +1,461 @@
+#!/usr/bin/env perl
+# This script is used to test Civetweb web server
+
+use IO::Socket;
+use File::Path;
+use Cwd;
+use strict;
+use warnings;
+#use diagnostics;
+
+sub on_windows { $^O =~ /win32/i; }
+
+my $port = 23456;
+my $pid = undef;
+my $num_requests;
+my $dir_separator = on_windows() ? '\\' : '/';
+my $copy_cmd = on_windows() ? 'copy' : 'cp';
+my $test_dir_uri = "test_dir";
+my $root = 'test';
+my $test_dir = $root . $dir_separator. $test_dir_uri;
+my $config = 'civetweb.conf';
+my $exe_ext = on_windows() ? '.exe' : '';
+my $civetweb_exe = '.' . $dir_separator . 'civetweb' . $exe_ext;
+my $embed_exe = '.' . $dir_separator . 'embed' . $exe_ext;
+my $unit_test_exe = '.' . $dir_separator . 'unit_test' . $exe_ext;
+my $exit_code = 0;
+
+my @files_to_delete = ('debug.log', 'access.log', $config, "$root/a/put.txt",
+ "$root/a+.txt", "$root/.htpasswd", "$root/binary_file", "$root/a",
+ "$root/myperl", $embed_exe, $unit_test_exe);
+
+END {
+ unlink @files_to_delete;
+ kill_spawned_child();
+ File::Path::rmtree($test_dir);
+ exit $exit_code;
+}
+
+sub fail {
+ print "FAILED: @_\n";
+ $exit_code = 1;
+ exit 1;
+}
+
+sub get_num_of_log_entries {
+ open FD, "access.log" or return 0;
+ my @lines = ();
+ close FD;
+ return scalar @lines;
+}
+
+# Send the request to the 127.0.0.1:$port and return the reply
+sub req {
+ my ($request, $inc, $timeout) = @_;
+ my $sock = IO::Socket::INET->new(Proto => 6,
+ PeerAddr => '127.0.0.1', PeerPort => $port);
+ fail("Cannot connect to http://127.0.0.1:$port : $!") unless $sock;
+ $sock->autoflush(1);
+ foreach my $byte (split //, $request) {
+ last unless print $sock $byte;
+ select undef, undef, undef, .001 if length($request) < 256;
+ }
+ my ($out, $buf) = ('', '');
+ eval {
+ alarm $timeout if $timeout;
+ $out .= $buf while (sysread($sock, $buf, 1024) > 0);
+ alarm 0 if $timeout;
+ };
+ close $sock;
+
+ $num_requests += defined($inc) ? $inc : 1;
+ my $num_logs = get_num_of_log_entries();
+
+ unless ($num_requests == $num_logs) {
+ fail("Request has not been logged: [$request], output: [$out]");
+ }
+
+ return $out;
+}
+
+# Send the request. Compare with the expected reply. Fail if no match
+sub o {
+ my ($request, $expected_reply, $message, $num_logs) = @_;
+ print "==> $message ... ";
+ my $reply = req($request, $num_logs);
+ if ($reply =~ /$expected_reply/s) {
+ print "OK\n";
+ } else {
+#fail("Requested: [$request]\nExpected: [$expected_reply], got: [$reply]");
+ fail("Expected: [$expected_reply], got: [$reply]");
+ }
+}
+
+# Spawn a server listening on specified port
+sub spawn {
+ my ($cmdline) = @_;
+ print 'Executing: ', @_, "\n";
+ if (on_windows()) {
+ my @args = split /\s+/, $cmdline;
+ my $executable = $args[0];
+ Win32::Spawn($executable, $cmdline, $pid);
+ die "Cannot spawn @_: $!" unless $pid;
+ } else {
+ unless ($pid = fork()) {
+ exec $cmdline;
+ die "cannot exec [$cmdline]: $!\n";
+ }
+ }
+ sleep 1;
+}
+
+sub write_file {
+ open FD, ">$_[0]" or fail "Cannot open $_[0]: $!";
+ binmode FD;
+ print FD $_[1];
+ close FD;
+}
+
+sub read_file {
+ open FD, $_[0] or fail "Cannot open $_[0]: $!";
+ my @lines = ;
+ close FD;
+ return join '', @lines;
+}
+
+sub kill_spawned_child {
+ if (defined($pid)) {
+ kill(9, $pid);
+ waitpid($pid, 0);
+ }
+}
+
+####################################################### ENTRY POINT
+
+unlink @files_to_delete;
+$SIG{PIPE} = 'IGNORE';
+$SIG{ALRM} = sub { die "timeout\n" };
+#local $| =1;
+
+# Make sure we export only symbols that start with "mg_", and keep local
+# symbols static.
+if ($^O =~ /darwin|bsd|linux/) {
+ my $out = `(cc -c src/civetweb.c && nm src/civetweb.o) | grep ' T '`;
+ foreach (split /\n/, $out) {
+ /T\s+_?mg_.+/ or fail("Exported symbol $_")
+ }
+}
+
+if (scalar(@ARGV) > 0 and $ARGV[0] eq 'unit') {
+ do_unit_test();
+ exit 0;
+}
+
+# Make sure we load config file if no options are given.
+# Command line options override config files settings
+write_file($config, "access_log_file access.log\n" .
+ "listening_ports 127.0.0.1:12345\n");
+spawn("$civetweb_exe -listening_ports 127.0.0.1:$port");
+o("GET /test/hello.txt HTTP/1.0\n\n", 'HTTP/1.1 200 OK', 'Loading config file');
+unlink $config;
+kill_spawned_child();
+
+# Spawn the server on port $port
+my $cmd = "$civetweb_exe ".
+ "-listening_ports 127.0.0.1:$port ".
+ "-access_log_file access.log ".
+ "-error_log_file debug.log ".
+ "-cgi_environment CGI_FOO=foo,CGI_BAR=bar,CGI_BAZ=baz " .
+ "-extra_mime_types .bar=foo/bar,.tar.gz=blah,.baz=foo " .
+ '-put_delete_auth_file test/passfile ' .
+ '-access_control_list -0.0.0.0/0,+127.0.0.1 ' .
+ "-document_root $root ".
+ "-hide_files_patterns **exploit.PL ".
+ "-enable_keep_alive yes ".
+ "-url_rewrite_patterns /aiased=/etc/,/ta=$test_dir";
+$cmd .= ' -cgi_interpreter perl' if on_windows();
+spawn($cmd);
+
+o("GET /hello.txt HTTP/1.1\nConnection: close\nRange: bytes=3-50\r\n\r\n",
+ 'Content-Length: 15\s', 'Range past the file end');
+
+o("GET /hello.txt HTTP/1.1\n\n GET /hello.txt HTTP/1.0\n\n",
+ 'HTTP/1.1 200.+keep-alive.+HTTP/1.1 200.+close',
+ 'Request pipelining', 2);
+
+my $x = 'x=' . 'A' x (200 * 1024);
+my $len = length($x);
+o("POST /env.cgi HTTP/1.0\r\nContent-Length: $len\r\n\r\n$x",
+ '^HTTP/1.1 200 OK', 'Long POST');
+
+# Try to overflow: Send very long request
+req('POST ' . '/..' x 100 . 'ABCD' x 3000 . "\n\n", 0); # don't log this one
+
+o("GET /hello.txt HTTP/1.0\n\n", 'HTTP/1.1 200 OK', 'GET regular file');
+o("GET /hello.txt HTTP/1.0\nContent-Length: -2147483648\n\n",
+ 'HTTP/1.1 200 OK', 'Negative content length');
+o("GET /hello.txt HTTP/1.0\n\n", 'Content-Length: 17\s',
+ 'GET regular file Content-Length');
+o("GET /%68%65%6c%6c%6f%2e%74%78%74 HTTP/1.0\n\n",
+ 'HTTP/1.1 200 OK', 'URL-decoding');
+
+# Break CGI reading after 1 second. We must get full output.
+# Since CGI script does sleep, we sleep as well and increase request count
+# manually.
+my $slow_cgi_reply;
+print "==> Slow CGI output ... ";
+fail('Slow CGI output forward reply=', $slow_cgi_reply) unless
+ ($slow_cgi_reply = req("GET /timeout.cgi HTTP/1.0\r\n\r\n", 0, 1)) =~ /Some data/s;
+print "OK\n";
+sleep 3;
+$num_requests++;
+
+# '+' in URI must not be URL-decoded to space
+write_file("$root/a+.txt", '');
+o("GET /a+.txt HTTP/1.0\n\n", 'HTTP/1.1 200 OK', 'URL-decoding, + in URI');
+
+# Test HTTP version parsing
+o("GET / HTTPX/1.0\r\n\r\n", '^HTTP/1.1 500', 'Bad HTTP Version', 0);
+o("GET / HTTP/x.1\r\n\r\n", '^HTTP/1.1 505', 'Bad HTTP maj Version', 0);
+o("GET / HTTP/1.1z\r\n\r\n", '^HTTP/1.1 505', 'Bad HTTP min Version', 0);
+o("GET / HTTP/02.0\r\n\r\n", '^HTTP/1.1 505', 'HTTP Version >1.1', 0);
+
+# File with leading single dot
+o("GET /.leading.dot.txt HTTP/1.0\n\n", 'abc123', 'Leading dot 1');
+o("GET /...leading.dot.txt HTTP/1.0\n\n", 'abc123', 'Leading dot 2');
+o("GET /../\\\\/.//...leading.dot.txt HTTP/1.0\n\n", 'abc123', 'Leading dot 3')
+ if on_windows();
+o("GET .. HTTP/1.0\n\n", '400 Bad Request', 'Leading dot 4', 0);
+
+mkdir $test_dir unless -d $test_dir;
+o("GET /$test_dir_uri/not_exist HTTP/1.0\n\n",
+ 'HTTP/1.1 404', 'PATH_INFO loop problem');
+o("GET /$test_dir_uri HTTP/1.0\n\n", 'HTTP/1.1 301', 'Directory redirection');
+o("GET /$test_dir_uri/ HTTP/1.0\n\n", 'Modified', 'Directory listing');
+write_file("$test_dir/index.html", "tralala");
+o("GET /$test_dir_uri/ HTTP/1.0\n\n", 'tralala', 'Index substitution');
+o("GET / HTTP/1.0\n\n", 'embed.c', 'Directory listing - file name');
+o("GET /ta/ HTTP/1.0\n\n", 'Modified', 'Aliases');
+o("GET /not-exist HTTP/1.0\r\n\n", 'HTTP/1.1 404', 'Not existent file');
+mkdir $test_dir . $dir_separator . 'x';
+my $path = $test_dir . $dir_separator . 'x' . $dir_separator . 'index.cgi';
+write_file($path, read_file($root . $dir_separator . 'env.cgi'));
+chmod(0755, $path);
+o("GET /$test_dir_uri/x/ HTTP/1.0\n\n", "Content-Type: text/html\r\n\r\n",
+ 'index.cgi execution');
+
+my $cwd = getcwd();
+o("GET /$test_dir_uri/x/ HTTP/1.0\n\n",
+ "SCRIPT_FILENAME=$cwd/test/test_dir/x/index.cgi", 'SCRIPT_FILENAME');
+o("GET /ta/x/ HTTP/1.0\n\n", "SCRIPT_NAME=/ta/x/index.cgi",
+ 'Aliases SCRIPT_NAME');
+o("GET /hello.txt HTTP/1.1\nConnection: close\n\n", 'Connection: close',
+ 'No keep-alive');
+
+$path = $test_dir . $dir_separator . 'x' . $dir_separator . 'a.cgi';
+system("ln -s `which perl` $root/myperl") == 0 or fail("Can't symlink perl");
+write_file($path, "#!../../myperl\n" .
+ "print \"Content-Type: text/plain\\n\\nhi\";");
+chmod(0755, $path);
+o("GET /$test_dir_uri/x/a.cgi HTTP/1.0\n\n", "hi", 'Relative CGI interp path');
+o("GET * HTTP/1.0\n\n", "^HTTP/1.1 404", '* URI');
+
+my $mime_types = {
+ html => 'text/html',
+ htm => 'text/html',
+ txt => 'text/plain',
+ unknown_extension => 'text/plain',
+ js => 'application/x-javascript',
+ css => 'text/css',
+ jpg => 'image/jpeg',
+ c => 'text/plain',
+ 'tar.gz' => 'blah',
+ bar => 'foo/bar',
+ baz => 'foo',
+};
+
+foreach my $key (keys %$mime_types) {
+ my $filename = "_mime_file_test.$key";
+ write_file("$root/$filename", '');
+ o("GET /$filename HTTP/1.0\n\n",
+ "Content-Type: $mime_types->{$key}", ".$key mime type");
+ unlink "$root/$filename";
+}
+
+# Get binary file and check the integrity
+my $binary_file = 'binary_file';
+my $f2 = '';
+foreach (0..123456) { $f2 .= chr(int(rand() * 255)); }
+write_file("$root/$binary_file", $f2);
+my $f1 = req("GET /$binary_file HTTP/1.0\r\n\n");
+while ($f1 =~ /^.*\r\n/) { $f1 =~ s/^.*\r\n// }
+$f1 eq $f2 or fail("Integrity check for downloaded binary file");
+
+my $range_request = "GET /hello.txt HTTP/1.1\nConnection: close\n".
+"Range: bytes=3-5\r\n\r\n";
+o($range_request, '206 Partial Content', 'Range: 206 status code');
+o($range_request, 'Content-Length: 3\s', 'Range: Content-Length');
+o($range_request, 'Content-Range: bytes 3-5/17', 'Range: Content-Range');
+o($range_request, '\nple$', 'Range: body content');
+
+# Test directory sorting. Sleep between file creation for 1.1 seconds,
+# to make sure modification time are different.
+mkdir "$test_dir/sort";
+write_file("$test_dir/sort/11", 'xx');
+select undef, undef, undef, 1.1;
+write_file("$test_dir/sort/aa", 'xxxx');
+select undef, undef, undef, 1.1;
+write_file("$test_dir/sort/bb", 'xxx');
+select undef, undef, undef, 1.1;
+write_file("$test_dir/sort/22", 'x');
+
+o("GET /$test_dir_uri/sort/?n HTTP/1.0\n\n",
+ '200 OK.+>11<.+>22<.+>aa<.+>bb<',
+ 'Directory listing (name, ascending)');
+o("GET /$test_dir_uri/sort/?nd HTTP/1.0\n\n",
+ '200 OK.+>bb<.+>aa<.+>22<.+>11<',
+ 'Directory listing (name, descending)');
+o("GET /$test_dir_uri/sort/?s HTTP/1.0\n\n",
+ '200 OK.+>22<.+>11<.+>bb<.+>aa<',
+ 'Directory listing (size, ascending)');
+o("GET /$test_dir_uri/sort/?sd HTTP/1.0\n\n",
+ '200 OK.+>aa<.+>bb<.+>11<.+>22<',
+ 'Directory listing (size, descending)');
+o("GET /$test_dir_uri/sort/?d HTTP/1.0\n\n",
+ '200 OK.+>11<.+>aa<.+>bb<.+>22<',
+ 'Directory listing (modification time, ascending)');
+o("GET /$test_dir_uri/sort/?dd HTTP/1.0\n\n",
+ '200 OK.+>22<.+>bb<.+>aa<.+>11<',
+ 'Directory listing (modification time, descending)');
+
+unless (scalar(@ARGV) > 0 and $ARGV[0] eq "basic_tests") {
+ # Check that .htpasswd file existence trigger authorization
+ write_file("$root/.htpasswd", 'user with space, " and comma:mydomain.com:5deda12442309cbdcdffc6b2737a894f');
+ o("GET /hello.txt HTTP/1.1\n\n", '401 Unauthorized',
+ '.htpasswd - triggering auth on file request');
+ o("GET / HTTP/1.1\n\n", '401 Unauthorized',
+ '.htpasswd - triggering auth on directory request');
+
+ # Test various funky things in an authentication header.
+ o("GET /hello.txt HTTP/1.0\nAuthorization: Digest eq== empty=\"\", empty2=, quoted=\"blah foo bar, baz\\\"\\\" more\\\"\", unterminatedquoted=\" doesn't stop\n\n",
+ '401 Unauthorized', 'weird auth values should not cause crashes');
+ my $auth_header = "Digest username=\"user with space, \\\" and comma\", ".
+ "realm=\"mydomain.com\", nonce=\"1291376417\", uri=\"/\",".
+ "response=\"e8dec0c2a1a0c8a7e9a97b4b5ea6a6e6\", qop=auth, nc=00000001, cnonce=\"1a49b53a47a66e82\"";
+ o("GET /hello.txt HTTP/1.0\nAuthorization: $auth_header\n\n", 'HTTP/1.1 200 OK', 'GET regular file with auth');
+ o("GET / HTTP/1.0\nAuthorization: $auth_header\n\n", '^(.(?!(.htpasswd)))*$',
+ '.htpasswd is hidden from the directory list');
+ o("GET / HTTP/1.0\nAuthorization: $auth_header\n\n", '^(.(?!(exploit.pl)))*$',
+ 'hidden file is hidden from the directory list');
+ o("GET /.htpasswd HTTP/1.0\nAuthorization: $auth_header\n\n",
+ '^HTTP/1.1 404 ', '.htpasswd must not be shown');
+ o("GET /exploit.pl HTTP/1.0\nAuthorization: $auth_header\n\n",
+ '^HTTP/1.1 404', 'hidden files must not be shown');
+ unlink "$root/.htpasswd";
+
+
+ o("GET /dir%20with%20spaces/hello.cgi HTTP/1.0\n\r\n",
+ 'HTTP/1.1 200 OK.+hello', 'CGI script with spaces in path');
+ o("GET /env.cgi HTTP/1.0\n\r\n", 'HTTP/1.1 200 OK', 'GET CGI file');
+ o("GET /bad2.cgi HTTP/1.0\n\n", "HTTP/1.1 123 Please pass me to the client\r",
+ 'CGI Status code text');
+ o("GET /sh.cgi HTTP/1.0\n\r\n", 'shell script CGI',
+ 'GET sh CGI file') unless on_windows();
+ o("GET /env.cgi?var=HELLO HTTP/1.0\n\n", 'QUERY_STRING=var=HELLO',
+ 'QUERY_STRING wrong');
+ o("POST /env.cgi HTTP/1.0\r\nContent-Length: 9\r\n\r\nvar=HELLO",
+ 'var=HELLO', 'CGI POST wrong');
+ o("POST /env.cgi HTTP/1.0\r\nContent-Length: 9\r\n\r\nvar=HELLO",
+ '\x0aCONTENT_LENGTH=9', 'Content-Length not being passed to CGI');
+ o("GET /env.cgi HTTP/1.0\nMy-HdR: abc\n\r\n",
+ 'HTTP_MY_HDR=abc', 'HTTP_* env');
+ o("GET /env.cgi HTTP/1.0\n\r\nSOME_TRAILING_DATA_HERE",
+ 'HTTP/1.1 200 OK', 'GET CGI with trailing data');
+
+ o("GET /env.cgi%20 HTTP/1.0\n\r\n",
+ 'HTTP/1.1 404', 'CGI Win32 code disclosure (%20)');
+ o("GET /env.cgi%ff HTTP/1.0\n\r\n",
+ 'HTTP/1.1 404', 'CGI Win32 code disclosure (%ff)');
+ o("GET /env.cgi%2e HTTP/1.0\n\r\n",
+ 'HTTP/1.1 404', 'CGI Win32 code disclosure (%2e)');
+ o("GET /env.cgi%2b HTTP/1.0\n\r\n",
+ 'HTTP/1.1 404', 'CGI Win32 code disclosure (%2b)');
+ o("GET /env.cgi HTTP/1.0\n\r\n", '\nHTTPS=off\n', 'CGI HTTPS');
+ o("GET /env.cgi HTTP/1.0\n\r\n", '\nCGI_FOO=foo\n', '-cgi_env 1');
+ o("GET /env.cgi HTTP/1.0\n\r\n", '\nCGI_BAR=bar\n', '-cgi_env 2');
+ o("GET /env.cgi HTTP/1.0\n\r\n", '\nCGI_BAZ=baz\n', '-cgi_env 3');
+ o("GET /env.cgi/a/b/98 HTTP/1.0\n\r\n", 'PATH_INFO=/a/b/98\n', 'PATH_INFO');
+ o("GET /env.cgi/a/b/9 HTTP/1.0\n\r\n", 'PATH_INFO=/a/b/9\n', 'PATH_INFO');
+
+ # Check that CGI's current directory is set to script's directory
+ my $copy_cmd = on_windows() ? 'copy' : 'cp';
+ system("$copy_cmd $root" . $dir_separator . "env.cgi $test_dir" .
+ $dir_separator . 'env.cgi');
+ o("GET /$test_dir_uri/env.cgi HTTP/1.0\n\n",
+ "CURRENT_DIR=.*$root/$test_dir_uri", "CGI chdir()");
+
+ # SSI tests
+ o("GET /ssi1.shtml HTTP/1.0\n\n",
+ 'ssi_begin.+CFLAGS.+ssi_end', 'SSI #include file=');
+ o("GET /ssi2.shtml HTTP/1.0\n\n",
+ 'ssi_begin.+Unit test.+ssi_end', 'SSI #include virtual=');
+ my $ssi_exec = on_windows() ? 'ssi4.shtml' : 'ssi3.shtml';
+ o("GET /$ssi_exec HTTP/1.0\n\n",
+ 'ssi_begin.+Makefile.+ssi_end', 'SSI #exec');
+ my $abs_path = on_windows() ? 'ssi6.shtml' : 'ssi5.shtml';
+ my $word = on_windows() ? 'boot loader' : 'root';
+ o("GET /$abs_path HTTP/1.0\n\n",
+ "ssi_begin.+$word.+ssi_end", 'SSI #include abspath');
+ o("GET /ssi7.shtml HTTP/1.0\n\n",
+ 'ssi_begin.+Unit test.+ssi_end', 'SSI #include "..."');
+ o("GET /ssi8.shtml HTTP/1.0\n\n",
+ 'ssi_begin.+CFLAGS.+ssi_end', 'SSI nested #includes');
+
+ # Manipulate the passwords file
+ my $path = 'test_htpasswd';
+ unlink $path;
+ system("$civetweb_exe -A $path a b c") == 0
+ or fail("Cannot add user in a passwd file");
+ system("$civetweb_exe -A $path a b c2") == 0
+ or fail("Cannot edit user in a passwd file");
+ my $content = read_file($path);
+ $content =~ /^b:a:\w+$/gs or fail("Bad content of the passwd file");
+ unlink $path;
+
+ do_PUT_test();
+ kill_spawned_child();
+ do_unit_test();
+}
+
+sub do_PUT_test {
+ # This only works because civetweb currently doesn't look at the nonce.
+ # It should really be rejected...
+ my $auth_header = "Authorization: Digest username=guest, ".
+ "realm=mydomain.com, nonce=1145872809, uri=/put.txt, ".
+ "response=896327350763836180c61d87578037d9, qop=auth, ".
+ "nc=00000002, cnonce=53eddd3be4e26a98\n";
+
+ o("PUT /a/put.txt HTTP/1.0\nContent-Length: 7\n$auth_header\n1234567",
+ "HTTP/1.1 201 OK", 'PUT file, status 201');
+ fail("PUT content mismatch")
+ unless read_file("$root/a/put.txt") eq '1234567';
+ o("PUT /a/put.txt HTTP/1.0\nContent-Length: 4\n$auth_header\nabcd",
+ "HTTP/1.1 200 OK", 'PUT file, status 200');
+ fail("PUT content mismatch")
+ unless read_file("$root/a/put.txt") eq 'abcd';
+ o("PUT /a/put.txt HTTP/1.0\n$auth_header\nabcd",
+ "HTTP/1.1 411 Length Required", 'PUT 411 error');
+ o("PUT /a/put.txt HTTP/1.0\nExpect: blah\nContent-Length: 1\n".
+ "$auth_header\nabcd",
+ "HTTP/1.1 417 Expectation Failed", 'PUT 417 error');
+ o("PUT /a/put.txt HTTP/1.0\nExpect: 100-continue\nContent-Length: 4\n".
+ "$auth_header\nabcd",
+ "HTTP/1.1 100 Continue.+HTTP/1.1 200", 'PUT 100-Continue');
+}
+
+sub do_unit_test {
+ my $target = on_windows() ? 'wi' : 'un';
+ system("make $target") == 0 or fail("Unit test failed!");
+}
+
+print "SUCCESS! All tests passed.\n";
diff --git a/src/civetweb/test/testclient.c b/src/civetweb/test/testclient.c
new file mode 100644
index 00000000..5cc2edb3
--- /dev/null
+++ b/src/civetweb/test/testclient.c
@@ -0,0 +1,151 @@
+#include
+#include
+
+#if defined(_WIN32) || defined(WIN32)
+#include
+void INIT(void) {WSADATA wsaData; WSAStartup(MAKEWORD(2,2), &wsaData);}
+#else
+#define INIT()
+#include
+#include
+#include
+#include
+#include
+#endif
+
+int connect_to_server(const struct sockaddr_in * serv_addr)
+{
+ int sockfd;
+
+ /* Create a socket */
+ sockfd = socket(AF_INET, SOCK_STREAM, 0);
+ if (sockfd < 0) {
+ perror("ERROR opening socket");
+ return -1;
+ }
+
+ /* Connect to the server */
+ if (connect(sockfd, (const sockaddr *)serv_addr, sizeof(*serv_addr)) < 0) {
+ perror("ERROR connecting");
+ close(sockfd);
+ return -2;
+ }
+
+ return sockfd;
+}
+
+int send_to_server(int conn, const char * request)
+{
+ int req_len = strlen(request);
+ int n;
+
+ n = write(conn, request, req_len);
+ if (n < 0) {
+ perror("ERROR writing to socket");
+ return 0;
+ }
+
+ return (n==req_len);
+}
+
+int read_from_server(int conn)
+{
+ char rbuffer[1024];
+ int n;
+ long ret;
+
+ n = read(conn, rbuffer, sizeof(rbuffer));
+ if (n < 0) {
+ perror("ERROR reading from socket");
+ return 0;
+ }
+
+ if (strncmp("HTTP/1.", rbuffer, 7)) {
+ perror("ERROR not a HTTP response");
+ return 0;
+ }
+
+ ret = atol(rbuffer + 9);
+
+ return ret;
+}
+
+
+int main(int argc, char *argv[])
+{
+ long portno;
+ int i, con_count=1;
+ time_t t1,t2,t3,t4;
+ char wbuffer[256];
+ int connlist[1024*65];
+ int result[1024*65];
+ struct hostent *server;
+ struct sockaddr_in serv_addr;
+
+ INIT();
+
+ if (argc != 4) {
+ fprintf(stderr,"Usage:\n\t%s hostname port clients\n\n", argv[0]);
+ exit(0);
+ }
+
+ con_count = atol(argv[3]);
+ if (con_count<1) con_count=1;
+ if (con_count>1024*65) con_count=1024*65;
+
+ portno = atol(argv[2]);
+ if (portno<1l || portno>0xFFFFl) {
+ fprintf(stderr, "ERROR, invalid port\n");
+ exit(0);
+ }
+
+ server = gethostbyname(argv[1]);
+ if (server == NULL) {
+ fprintf(stderr, "ERROR, no such host\n");
+ exit(0);
+ }
+
+ memset(&serv_addr, 0, sizeof(serv_addr));
+ serv_addr.sin_family = AF_INET;
+ memcpy(server->h_addr, &serv_addr.sin_addr.s_addr, server->h_length);
+ serv_addr.sin_port = htons((short)portno);
+
+ sprintf(wbuffer, "GET / HTTP/1.0\r\n\r\n");
+
+ t1 = time(0);
+ for (i=0;i=0) {
+ result[i] = send_to_server(connlist[i], wbuffer);
+ }
+ }
+ t3 = time(0);
+ for (i=0;i=0) {
+ result[i] = read_from_server(connlist[i]);
+ }
+ }
+ t4 = time(0);
+
+ printf("\n");
+ printf("conn: %.0lf\n", difftime(t2,t1));
+ printf("write: %.0lf\n", difftime(t3,t2));
+ printf("read: %.0lf\n", difftime(t4,t3));
+
+ for (i=-10;i<1000;i++) {
+ int j,cnt=0;
+ for(j=0;j0) {
+ printf("%5i\t%7i\n", i, cnt);
+ }
+ }
+
+ return 0;
+}
+
+
diff --git a/src/civetweb/test/timeout.cgi b/src/civetweb/test/timeout.cgi
new file mode 100755
index 00000000..32482056
--- /dev/null
+++ b/src/civetweb/test/timeout.cgi
@@ -0,0 +1,12 @@
+#!/usr/bin/env perl
+
+# Make stdout unbuffered
+use FileHandle;
+STDOUT->autoflush(1);
+
+# This script outputs some content, then sleeps for 5 seconds, then exits.
+# Web server should return the content immediately after it is sent,
+# not waiting until the script exits.
+print "Content-Type: text/html\r\n\r\n";
+print "Some data";
+sleep 3;
diff --git a/src/civetweb/test/timertest.c b/src/civetweb/test/timertest.c
new file mode 100644
index 00000000..3ee98dce
--- /dev/null
+++ b/src/civetweb/test/timertest.c
@@ -0,0 +1,350 @@
+/* Copyright (c) 2016-2017 the Civetweb developers
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+/**
+ * We include the source file so that we have access to the internal private
+ * static functions
+ */
+#ifdef _MSC_VER
+#ifndef _CRT_SECURE_NO_WARNINGS
+#define _CRT_SECURE_NO_WARNINGS
+#endif
+#endif
+
+#if defined(__GNUC__)
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wunused-function"
+#endif
+
+#define CIVETWEB_API static
+#define USE_TIMERS
+
+#include "../src/civetweb.c"
+
+#include
+#include
+
+#include "timertest.h"
+
+static int action_dec_ret;
+
+static int
+action_dec(void *arg)
+{
+ int *p = (int *)arg;
+ (*p)--;
+
+ if (*p < -1) {
+ ck_abort_msg("Periodic timer called too often");
+ /* return 0 here would be unreachable code */
+ }
+
+ return (*p >= -3) ? action_dec_ret : 0;
+}
+
+
+static int
+action_dec_to_0(void *arg)
+{
+ int *p = (int *)arg;
+ (*p)--;
+
+ if (*p <= -1) {
+ ck_abort_msg("Periodic timer called too often");
+ /* return 0 here would be unreachable code */
+ }
+
+ return (*p > 0);
+}
+
+
+START_TEST(test_timer_cyclic)
+{
+ struct mg_context ctx;
+ int c[10];
+ memset(&ctx, 0, sizeof(ctx));
+ memset(c, 0, sizeof(c));
+
+ action_dec_ret = 1;
+
+ mark_point();
+ timers_init(&ctx);
+ mg_sleep(100);
+ mark_point();
+
+ c[0] = 100;
+ timer_add(&ctx, 0.05, 0.1, 1, action_dec, c + 0);
+ c[2] = 20;
+ timer_add(&ctx, 0.25, 0.5, 1, action_dec, c + 2);
+ c[1] = 50;
+ timer_add(&ctx, 0.1, 0.2, 1, action_dec, c + 1);
+
+ mark_point();
+
+ mg_sleep(10000); /* Sleep 10 second - timers will run */
+
+ mark_point();
+ ctx.stop_flag = 99; /* End timer thread */
+ mark_point();
+
+ mg_sleep(2000); /* Sleep 2 second - timers will not run */
+
+ mark_point();
+
+ timers_exit(&ctx);
+
+ mark_point();
+
+ /* If this test runs in a virtual environment, like the CI unit test
+ * containers, there might be some timing deviations, so check the
+ * counter with some tolerance. */
+
+ ck_assert_int_ge(c[0], -1);
+ ck_assert_int_le(c[0], +1);
+ ck_assert_int_ge(c[1], -1);
+ ck_assert_int_le(c[1], +1);
+ ck_assert_int_ge(c[2], -1);
+ ck_assert_int_le(c[2], +1);
+}
+END_TEST
+
+
+START_TEST(test_timer_oneshot_by_callback_retval)
+{
+ struct mg_context ctx;
+ int c[10];
+ memset(&ctx, 0, sizeof(ctx));
+ memset(c, 0, sizeof(c));
+
+ action_dec_ret = 0;
+
+ mark_point();
+ timers_init(&ctx);
+ mg_sleep(100);
+ mark_point();
+
+ c[0] = 10;
+ timer_add(&ctx, 0, 0.1, 1, action_dec, c + 0);
+ c[2] = 2;
+ timer_add(&ctx, 0, 0.5, 1, action_dec, c + 2);
+ c[1] = 5;
+ timer_add(&ctx, 0, 0.2, 1, action_dec, c + 1);
+
+ mark_point();
+
+ mg_sleep(1000); /* Sleep 1 second - timer will run */
+
+ mark_point();
+ ctx.stop_flag = 99; /* End timer thread */
+ mark_point();
+
+ mg_sleep(1000); /* Sleep 1 second - timer will not run */
+
+ mark_point();
+
+ timers_exit(&ctx);
+
+ mark_point();
+ mg_sleep(100);
+
+ ck_assert_int_eq(c[0], 9);
+ ck_assert_int_eq(c[1], 4);
+ ck_assert_int_eq(c[2], 1);
+}
+END_TEST
+
+
+START_TEST(test_timer_oneshot_by_timer_add)
+{
+ struct mg_context ctx;
+ int c[10];
+ memset(&ctx, 0, sizeof(ctx));
+ memset(c, 0, sizeof(c));
+
+ action_dec_ret = 1;
+
+ mark_point();
+ timers_init(&ctx);
+ mg_sleep(100);
+ mark_point();
+
+ c[0] = 10;
+ timer_add(&ctx, 0, 0, 1, action_dec, c + 0);
+ c[2] = 2;
+ timer_add(&ctx, 0, 0, 1, action_dec, c + 2);
+ c[1] = 5;
+ timer_add(&ctx, 0, 0, 1, action_dec, c + 1);
+
+ mark_point();
+
+ mg_sleep(1000); /* Sleep 1 second - timer will run */
+
+ mark_point();
+ ctx.stop_flag = 99; /* End timer thread */
+ mark_point();
+
+ mg_sleep(1000); /* Sleep 1 second - timer will not run */
+
+ mark_point();
+
+ timers_exit(&ctx);
+
+ mark_point();
+ mg_sleep(100);
+
+ ck_assert_int_eq(c[0], 9);
+ ck_assert_int_eq(c[1], 4);
+ ck_assert_int_eq(c[2], 1);
+}
+END_TEST
+
+
+START_TEST(test_timer_mixed)
+{
+ struct mg_context ctx;
+ int c[10];
+ memset(&ctx, 0, sizeof(ctx));
+ memset(c, 0, sizeof(c));
+
+ mark_point();
+ timers_init(&ctx);
+ mg_sleep(100);
+ mark_point();
+
+ /* 3 --> 2, because it is a single shot timer */
+ c[0] = 3;
+ timer_add(&ctx, 0, 0, 1, action_dec_to_0, &c[0]);
+
+ /* 3 --> 0, because it will run until c[1] = 0 and then stop */
+ c[1] = 3;
+ timer_add(&ctx, 0, 0.2, 1, action_dec_to_0, &c[1]);
+
+ /* 3 --> 1, with 750 ms period, it will run once at start,
+ * then once 750 ms later, but not 1500 ms later, since the
+ * timer is already stopped then. */
+ c[2] = 3;
+ timer_add(&ctx, 0, 0.75, 1, action_dec_to_0, &c[2]);
+
+ /* 3 --> 2, will run at start, but no cyclic in 1 second */
+ c[3] = 3;
+ timer_add(&ctx, 0, 2.5, 1, action_dec_to_0, &c[3]);
+
+ /* 3 --> 3, will not run at start */
+ c[4] = 3;
+ timer_add(&ctx, 2.5, 0.1, 1, action_dec_to_0, &c[4]);
+
+ /* 3 --> 2, an absolute timer in the past (-123.456) will still
+ * run once at start, and then with the period */
+ c[5] = 3;
+ timer_add(&ctx, -123.456, 2.5, 0, action_dec_to_0, &c[5]);
+
+ /* 3 --> 1, an absolute timer in the past (-123.456) will still
+ * run once at start, and then with the period */
+ c[6] = 3;
+ timer_add(&ctx, -123.456, 0.75, 0, action_dec_to_0, &c[6]);
+
+ mark_point();
+
+ mg_sleep(1000); /* Sleep 1 second - timer will run */
+
+ mark_point();
+ ctx.stop_flag = 99; /* End timer thread */
+ mark_point();
+
+ mg_sleep(1000); /* Sleep 1 second - timer will not run */
+
+ mark_point();
+
+ timers_exit(&ctx);
+
+ mark_point();
+ mg_sleep(100);
+
+ ck_assert_int_eq(c[0], 2);
+ ck_assert_int_eq(c[1], 0);
+ ck_assert_int_eq(c[2], 1);
+ ck_assert_int_eq(c[3], 2);
+ ck_assert_int_eq(c[4], 3);
+ ck_assert_int_eq(c[5], 2);
+ ck_assert_int_eq(c[6], 1);
+}
+END_TEST
+
+
+#if !defined(REPLACE_CHECK_FOR_LOCAL_DEBUGGING)
+Suite *
+make_timertest_suite(void)
+{
+ Suite *const suite = suite_create("Timer");
+
+ TCase *const tcase_timer_cyclic = tcase_create("Timer Periodic");
+ TCase *const tcase_timer_oneshot = tcase_create("Timer Single Shot");
+ TCase *const tcase_timer_mixed = tcase_create("Timer Mixed");
+
+ tcase_add_test(tcase_timer_cyclic, test_timer_cyclic);
+ tcase_set_timeout(tcase_timer_cyclic, 30);
+ suite_add_tcase(suite, tcase_timer_cyclic);
+
+ tcase_add_test(tcase_timer_oneshot, test_timer_oneshot_by_timer_add);
+ tcase_add_test(tcase_timer_oneshot, test_timer_oneshot_by_callback_retval);
+ tcase_set_timeout(tcase_timer_oneshot, 30);
+ suite_add_tcase(suite, tcase_timer_oneshot);
+
+ tcase_add_test(tcase_timer_mixed, test_timer_mixed);
+ tcase_set_timeout(tcase_timer_mixed, 30);
+ suite_add_tcase(suite, tcase_timer_mixed);
+
+ return suite;
+}
+#endif
+
+
+#ifdef REPLACE_CHECK_FOR_LOCAL_DEBUGGING
+/* Used to debug test cases without using the check framework */
+
+void
+TIMER_PRIVATE(void)
+{
+ unsigned f_avail;
+ unsigned f_ret;
+
+#if defined(_WIN32)
+ WSADATA data;
+ WSAStartup(MAKEWORD(2, 2), &data);
+#endif
+
+ f_avail = mg_check_feature(0xFF);
+ f_ret = mg_init_library(f_avail);
+ ck_assert_uint_eq(f_ret, f_avail);
+
+ test_timer_cyclic(0);
+ test_timer_oneshot_by_timer_add(0);
+ test_timer_oneshot_by_callback_retval(0);
+ test_timer_mixed(0);
+
+ mg_exit_library();
+
+#if defined(_WIN32)
+ WSACleanup();
+#endif
+}
+
+#endif
diff --git a/src/civetweb/test/timertest.h b/src/civetweb/test/timertest.h
new file mode 100644
index 00000000..844a01b0
--- /dev/null
+++ b/src/civetweb/test/timertest.h
@@ -0,0 +1,28 @@
+/* Copyright (c) 2015 the Civetweb developers
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+#ifndef TEST_TIMER_H_
+#define TEST_TIMER_H_
+
+#include "civetweb_check.h"
+
+Suite *make_timertest_suite(void);
+
+#endif /* TEST_TIMER_H_ */
diff --git a/src/civetweb/test/websocket.lua b/src/civetweb/test/websocket.lua
new file mode 100644
index 00000000..7338ed87
--- /dev/null
+++ b/src/civetweb/test/websocket.lua
@@ -0,0 +1,118 @@
+timerID = "timeout"
+--timerID = "interval"
+
+function trace(text)
+ local f = io.open("websocket.trace", "a")
+ f:write(os.date() .. " - " .. text .. "\n")
+ f:close()
+end
+
+function iswebsocket()
+ return mg.lua_type == "websocket"
+ --return pcall(function()
+ -- if (string.upper(mg.request_info.http_headers.Upgrade)~="WEBSOCKET") then error("") end
+ --end)
+end
+
+trace("called with Lua type " .. tostring(mg.lua_type))
+
+if not iswebsocket() then
+ trace("no websocket")
+ mg.write("HTTP/1.0 403 Forbidden\r\n")
+ mg.write("Connection: close\r\n")
+ mg.write("\r\n")
+ mg.write("forbidden")
+ return
+end
+
+
+-- Serialize table to string
+function ser(val)
+ local t
+ if type(val) == "table" then
+ for k,v in pairs(val) do
+ if t then
+ t = t .. ", " .. ser(k) .. "=" .. ser(v)
+ else
+ t = "{" .. ser(k) .. "=" .. ser(v)
+ end
+ end
+ t = t .. "}"
+ else
+ t = tostring(val)
+ end
+ return t
+end
+
+-- table of all active connection
+allConnections = {}
+
+-- function to get a client identification string
+function who(tab)
+ local ri = allConnections[tab.client].request_info
+ return ri.remote_addr .. ":" .. ri.remote_port
+end
+
+-- Callback to accept or reject a connection
+function open(tab)
+ allConnections[tab.client] = tab
+ trace("open[" .. who(tab) .. "]: " .. ser(tab))
+ return true -- return true to accept the connection
+end
+
+-- Callback for "Websocket ready"
+function ready(tab)
+ trace("ready[" .. who(tab) .. "]: " .. ser(tab))
+ mg.write(tab.client, "text", "Websocket ready")
+ mg.write(tab.client, 1, "-->h 180");
+ mg.write(tab.client, "-->m 180");
+ senddata()
+ if timerID == "timeout" then
+ mg.set_timeout("timer()", 1)
+ elseif timerID == "interval" then
+ mg.set_interval("timer()", 1)
+ end
+ return true -- return true to keep the connection open
+end
+
+-- Callback for "Websocket received data"
+function data(tab)
+ trace("data[" .. who(tab) .. "]: " .. ser(tab))
+ senddata()
+ return true -- return true to keep the connection open
+end
+
+-- Callback for "Websocket is closing"
+function close(tab)
+ trace("close[" .. who(tab) .. "]: " .. ser(tab))
+ mg.write("text", "end")
+ allConnections[tab.client] = nil
+end
+
+function senddata()
+ local date = os.date('*t');
+ local hand = (date.hour%12)*60+date.min;
+
+ mg.write("text", string.format("%u:%02u:%02u", date.hour, date.min, date.sec));
+
+ if (hand ~= lasthand) then
+ mg.write(1, string.format("-->h %u", hand*360/(12*60)));
+ mg.write( string.format("-->m %u", date.min*360/60));
+ lasthand = hand;
+ end
+
+ if bits and content then
+ data(bits, content)
+ end
+end
+
+function timer()
+ trace("timer")
+ senddata()
+ if timerID == "timeout" then
+ mg.set_timeout("timer()", 1)
+ else
+ return true -- return true to keep an interval timer running
+ end
+end
+
diff --git a/src/civetweb/test/websocket.xhtml b/src/civetweb/test/websocket.xhtml
new file mode 100644
index 00000000..3e0828f1
--- /dev/null
+++ b/src/civetweb/test/websocket.xhtml
@@ -0,0 +1,117 @@
+
+
+
+
+ Websocket test
+
+
+
+
+
+
+
+
+
diff --git a/src/civetweb/test/windows.cgi b/src/civetweb/test/windows.cgi
new file mode 100644
index 00000000..d8aaabce
--- /dev/null
+++ b/src/civetweb/test/windows.cgi
@@ -0,0 +1,2 @@
+#!windows.cgi.cmd
+
diff --git a/src/civetweb/test/windows.cgi.cmd b/src/civetweb/test/windows.cgi.cmd
new file mode 100644
index 00000000..779abad0
--- /dev/null
+++ b/src/civetweb/test/windows.cgi.cmd
@@ -0,0 +1,7 @@
+@echo off
+@rem echo HTTP/1.1 200 OK -- sent by framework
+echo Connection: close
+echo.
+echo CGI test:
+echo.
+set
diff --git a/src/civetweb/test/windows_fail.cgi b/src/civetweb/test/windows_fail.cgi
new file mode 100644
index 00000000..606fbd23
--- /dev/null
+++ b/src/civetweb/test/windows_fail.cgi
@@ -0,0 +1,2 @@
+#!r:\windows_fail.cgi.cmd
+
diff --git a/src/civetweb/test/windows_fail.cgi.cmd b/src/civetweb/test/windows_fail.cgi.cmd
new file mode 100644
index 00000000..715c0619
--- /dev/null
+++ b/src/civetweb/test/windows_fail.cgi.cmd
@@ -0,0 +1,2 @@
+@echo off
+echo Some error sent to stderr 1>&2
diff --git a/src/civetweb/test/windows_fail_silent.cgi b/src/civetweb/test/windows_fail_silent.cgi
new file mode 100644
index 00000000..198225ae
--- /dev/null
+++ b/src/civetweb/test/windows_fail_silent.cgi
@@ -0,0 +1,2 @@
+#!r:\windows_fail_silent.cgi.cmd
+
diff --git a/src/civetweb/test/windows_fail_silent.cgi.cmd b/src/civetweb/test/windows_fail_silent.cgi.cmd
new file mode 100644
index 00000000..bb2bf1ba
--- /dev/null
+++ b/src/civetweb/test/windows_fail_silent.cgi.cmd
@@ -0,0 +1,3 @@
+@echo off
+echo not a complete header
+echo and nothing sent to stderr
diff --git a/src/civetweb/test/ws_status.lua b/src/civetweb/test/ws_status.lua
new file mode 100644
index 00000000..a19505b2
--- /dev/null
+++ b/src/civetweb/test/ws_status.lua
@@ -0,0 +1,137 @@
+if mg.lua_type ~= "websocket" then
+ mg.write("HTTP/1.0 200 OK\r\n")
+ mg.write("Connection: close\r\n")
+ mg.write("\r\n")
+ mg.write("\r\n")
+ mg.write("\r\n")
+ mg.write("\r\n")
+ mg.write("\r\n")
+ mg.write("Server stats\r\n")
+ mg.write("\r\n")
+ mg.write("\r\n")
+ mg.write([====[
+
+]====])
+
+ mg.write("
Wait for page load
\r\n")
+ mg.write("\r\n")
+ mg.write("\r\n")
+ return
+end
+
+
+function table.count(tab)
+ local count = 0
+ for _ in pairs(tab) do
+ count = count + 1
+ end
+ return count
+end
+
+
+-- table of all active connection
+allConnections = {}
+connCount = table.count(allConnections)
+
+
+-- function to get a client identification string
+function who(tab)
+ local ri = allConnections[tab.client].request_info
+ return ri.remote_addr .. ":" .. ri.remote_port
+end
+
+-- Callback to accept or reject a connection
+function open(tab)
+ allConnections[tab.client] = tab
+ connCount = table.count(allConnections)
+ return true -- return true to accept the connection
+end
+
+-- Callback for "Websocket ready"
+function ready(tab)
+ senddata()
+ return true -- return true to keep the connection open
+end
+
+-- Callback for "Websocket received data"
+function data(tab)
+ senddata()
+ return true -- return true to keep the connection open
+end
+
+-- Callback for "Websocket is closing"
+function close(tab)
+ allConnections[tab.client] = nil
+ connCount = table.count(allConnections)
+end
+
+function senddata()
+ local date = os.date('*t');
+
+ collectgarbage("collect"); -- Avoid adding uncollected Lua memory from this state
+
+ mg.write(string.format([[
+{"Time": "%u:%02u:%02u",
+ "Date": "%04u-%02u-%02u",
+ "Context": %s,
+ "Common": %s,
+ "System": \"%s\",
+ "ws_status": {"Memory": %u, "Connections": %u}
+}]],
+date.hour, date.min, date.sec,
+date.year, date.month, date.day,
+mg.get_info("context"),
+mg.get_info("common"),
+mg.get_info("system"),
+collectgarbage("count")*1024,
+connCount
+));
+
+end
+
+function timer()
+ senddata()
+ mg.set_timeout("timer()", 1)
+end
+
+mg.set_timeout("timer()", 1)
+
diff --git a/src/civetweb/test/x.php b/src/civetweb/test/x.php
new file mode 100644
index 00000000..cd328429
--- /dev/null
+++ b/src/civetweb/test/x.php
@@ -0,0 +1,9 @@
+
+
+
+ echo $_POST["x"]; ?>
+
+
--
cgit v1.2.3